From f9641069711a321f67b83152c8740df194ddc93a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 12 Nov 2026 18:22:12 +0100 Subject: [PATCH 001/230] feat: Auto model routes across subscriptions by level and live usage limits --- .../src/orchestration-v2/Orchestrator.ts | 67 +++++- docs/progress.md | 10 + packages/shared/package.json | 4 + packages/shared/src/autoModel.test.ts | 132 ++++++++++++ packages/shared/src/autoModel.ts | 202 ++++++++++++++++++ 5 files changed, 412 insertions(+), 3 deletions(-) create mode 100644 docs/progress.md create mode 100644 packages/shared/src/autoModel.test.ts create mode 100644 packages/shared/src/autoModel.ts diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 076960f4dc1d..344a8d5e2ec7 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -80,6 +80,8 @@ import { } from "@t3tools/contracts"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { modelSelectionsEqual } from "@t3tools/shared/model"; +import { isAutoModelSelection, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import { modelSwitchSince } from "./modelSwitch.ts"; import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts"; import { recordThreadOpen } from "@t3tools/shared/paletteSearch"; @@ -15698,6 +15700,65 @@ export const layer: Layer.Layer< | RuntimePolicyV2 | ServerSettings.ServerSettingsService | ThreadForkServiceV2 -> = Layer.effect(OrchestratorV2, makeOrchestrator()).pipe( - Layer.provide(ThreadCommandExecutor.layer), -); +> = Layer.effect( + OrchestratorV2, + makeOrchestrator().pipe(Effect.flatMap((orchestrator) => withAutoModelRouting(orchestrator))), +).pipe(Layer.provide(ThreadCommandExecutor.layer)); + +/** Commands whose `auto` model keeps the thread's current model while it still fits. */ +const AUTO_STICKY_COMMANDS: ReadonlySet = new Set([ + "message.dispatch", + "thread.model-selection.set", + "provider.switch", +]); + +/** + * Replaces the `auto` model in any command with the concrete model Auto picks from live usage + * limits, so every surface (web, mobile, MCP, scheduled tasks) gets the same routing. + */ +const withAutoModelRouting = Effect.fn("OrchestratorV2.withAutoModelRouting")(function* ( + orchestrator: OrchestratorV2Shape, +) { + // Optional so layers without provider snapshots (tests, CLI tools) still build; there, Auto + // is rejected instead of routed. + const registry = yield* Effect.serviceOption(ProviderRegistry.ProviderRegistry); + const resolve = Effect.fn("OrchestratorV2.resolveAutoModel")(function* ( + command: OrchestrationV2ServerCommand, + ) { + const selection = (command as { readonly modelSelection?: ModelSelection }).modelSelection; + if (!isAutoModelSelection(selection) || selection === undefined) return command; + const threadId = (command as { readonly threadId?: ThreadId }).threadId; + const current = + threadId !== undefined && AUTO_STICKY_COMMANDS.has(command.type) + ? ((yield* orchestrator.getThreadShell(threadId).pipe(Effect.orElseSucceed(() => null))) + ?.modelSelection ?? null) + : null; + const resolution = resolveAutoModelSelection({ + selection, + providers: Option.isSome(registry) ? yield* registry.value.getProviders : [], + now: DateTime.toEpochMillis(yield* DateTime.now), + current, + }); + if (resolution === null) { + return yield* new OrchestratorCommandRejectedError({ + commandId: command.commandId, + commandType: command.type, + cause: new Error( + "Auto found no usable model: every candidate is disabled, signed out, or at its usage limit.", + ), + }); + } + yield* Effect.logInfo("auto model routing", { + commandType: command.type, + level: resolution.level, + sticky: resolution.sticky, + instanceId: resolution.selection.instanceId, + model: resolution.selection.model, + }); + return { ...command, modelSelection: resolution.selection } as OrchestrationV2ServerCommand; + }); + return { + ...orchestrator, + dispatch: (command) => resolve(command).pipe(Effect.flatMap(orchestrator.dispatch)), + } satisfies OrchestratorV2Shape; +}); diff --git a/docs/progress.md b/docs/progress.md new file mode 100644 index 000000000000..dfb3c4eafab5 --- /dev/null +++ b/docs/progress.md @@ -0,0 +1,10 @@ +# Progress (radys-s fork) + +## 2026-11-12: Auto model + +- What: an "Auto" model with its own Low/Medium/High level. Picking it never reaches a provider; the server replaces it in every command (`OrchestratorV2.dispatch`) with a concrete model chosen from live usage limits: Fable (high), Opus (medium) or Sonnet (low) on whichever Claude account has more room, then Codex, Grok and OpenCode when Claude is out. +- Why: Tomáš wanted one Auto entry in the model picker that routes across all his subscriptions, including Claude A vs B. +- How it shows up: a custom model `auto` (with an `effort` select of low/medium/high) on the Auto Claude instances in settings. No web change was needed; the picker already renders custom models and their options. +- Numbers: resolver 5/5 tests; shared and server typecheck clean (server took 22 min on the first, cold run, ~6 min warm). +- Worked: one wrapper around `dispatch` covers web, mobile, MCP and scheduled tasks. Stickiness keeps a thread on its model until it passes 90% used, so threads do not hop accounts on each message. +- Next: after the first message the composer shows the concrete model, not "Auto"; keeping Auto selected mid-thread needs a client change. diff --git a/packages/shared/package.json b/packages/shared/package.json index f5f769236f90..2e9aeb055f60 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -387,6 +387,10 @@ "types": "./src/usageFormat.ts", "import": "./src/usageFormat.ts" }, + "./autoModel": { + "types": "./src/autoModel.ts", + "import": "./src/autoModel.ts" + }, "./usageLimits": { "types": "./src/usageLimits.ts", "import": "./src/usageLimits.ts" diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts new file mode 100644 index 000000000000..e7846c214e74 --- /dev/null +++ b/packages/shared/src/autoModel.test.ts @@ -0,0 +1,132 @@ +import { + ProviderDriverKind, + ProviderInstanceId, + type ModelSelection, + type ServerProvider, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { AUTO_LEVEL_DESCRIPTOR, resolveAutoModelSelection } from "./autoModel.ts"; + +const now = Date.parse("2026-11-12T12:00:00.000Z"); +const resetsAt = "2026-11-12T15:00:00.000Z"; + +const effortCapabilities = { + optionDescriptors: [ + { + id: "effort", + label: "Effort", + type: "select" as const, + options: ["low", "medium", "high"].map((id) => ({ id, label: id })), + }, + ], +}; + +function claude(id: string, usedPercent: number, autoAware = true): ServerProvider { + return { + instanceId: ProviderInstanceId.make(id), + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-11-12T11:00:00.000Z", + models: [ + ...["claude-fable-5-2", "claude-opus-5-5", "claude-sonnet-5-5"].map((slug) => ({ + slug, + name: slug, + isCustom: false, + capabilities: effortCapabilities, + })), + ...(autoAware + ? [ + { + slug: "auto", + name: "Auto", + isCustom: true, + capabilities: { optionDescriptors: [AUTO_LEVEL_DESCRIPTOR] }, + }, + ] + : []), + ], + slashCommands: [], + skills: [], + usageLimits: { + windows: [{ id: "five_hour", kind: "session", label: "Session", usedPercent, resetsAt }], + }, + } as unknown as ServerProvider; +} + +const auto = (level?: string): ModelSelection => ({ + instanceId: ProviderInstanceId.make("claudeAuto"), + model: "auto", + ...(level ? { options: [{ id: "effort", value: level }] } : {}), +}); + +describe("resolveAutoModelSelection", () => { + it("maps each level to its orchestrator model and effort, medium by default", () => { + const providers = [claude("claudeAuto", 10)]; + expect( + resolveAutoModelSelection({ selection: auto("high"), providers, now })?.selection, + ).toEqual({ + instanceId: "claudeAuto", + model: "claude-fable-5-2", + options: [{ id: "effort", value: "high" }], + }); + expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.model).toBe( + "claude-opus-5-5", + ); + expect( + resolveAutoModelSelection({ selection: auto("low"), providers, now })?.selection, + ).toEqual({ + instanceId: "claudeAuto", + model: "claude-sonnet-5-5", + options: [{ id: "effort", value: "low" }], + }); + }); + + it("picks the Claude account with more room, preferring Auto-aware instances", () => { + const providers = [ + claude("claudeAgent", 0, false), + claude("claudeAuto", 70), + claude("claudeAutoB", 20), + ]; + expect( + resolveAutoModelSelection({ selection: auto("medium"), providers, now })?.selection + .instanceId, + ).toBe("claudeAutoB"); + }); + + it("keeps the thread's current model until it passes 90% used", () => { + const current = { instanceId: ProviderInstanceId.make("claudeAuto"), model: "claude-opus-5-5" }; + const calm = [claude("claudeAuto", 60), claude("claudeAutoB", 5)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: calm, now, current }), + ).toMatchObject({ sticky: true, selection: { instanceId: "claudeAuto" } }); + + const busy = [claude("claudeAuto", 95), claude("claudeAutoB", 5)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: busy, now, current }), + ).toMatchObject({ sticky: false, selection: { instanceId: "claudeAutoB" } }); + }); + + it("steps down to other subscriptions when both Claude accounts are exhausted", () => { + const grok = { + ...claude("grok", 0, false), + driver: ProviderDriverKind.make("grok"), + models: [{ slug: "grok-4.7", name: "Grok 4.7", isCustom: false, capabilities: null }], + usageLimits: undefined, + } as unknown as ServerProvider; + const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100), grok]; + expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection).toEqual({ + instanceId: "grok", + model: "grok-4.7", + }); + }); + + it("returns null when nothing is usable", () => { + const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; + expect(resolveAutoModelSelection({ selection: auto(), providers, now })).toBeNull(); + }); +}); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts new file mode 100644 index 000000000000..87f997204b42 --- /dev/null +++ b/packages/shared/src/autoModel.ts @@ -0,0 +1,202 @@ +import { + isProviderAvailable, + type ModelSelection, + type ProviderDriverKind, + type ProviderOptionDescriptor, + type ServerProvider, +} from "@t3tools/contracts"; + +import { exhaustedUsageWindow } from "./usageLimits.ts"; + +/** + * "Auto" is a custom model (slug `auto`) on any provider instance. Picking it never reaches + * a provider: the server replaces it with a concrete model chosen here, from the providers' + * live usage limits. The level (`low` | `medium` | `high`) rides in the `effort` option. + */ +const AUTO_MODEL_SLUG = "auto"; +const AUTO_LEVELS = ["low", "medium", "high"] as const; +type AutoLevel = (typeof AUTO_LEVELS)[number]; +const DEFAULT_LEVEL: AutoLevel = "medium"; +/** Above this peak usage, a sticky model gives way when another candidate has more room. */ +const STICKY_MAX_USED_PERCENT = 90; + +interface AutoCandidate { + readonly driver: string; + readonly model: string; + /** The candidate's own reasoning effort for this level. */ + readonly effort: string; +} + +const claude = (model: string, effort: string): AutoCandidate => ({ + driver: "claudeAgent", + model, + effort, +}); +const codex = (model: string, effort: string): AutoCandidate => ({ + driver: "codex", + model, + effort, +}); +const grok = (effort: string): AutoCandidate => ({ driver: "grok", model: "grok-4.7", effort }); +const opencode = (model: string, effort: string): AutoCandidate => ({ + driver: "opencode", + model, + effort, +}); + +/** + * Orchestrator candidates per level, best first. Each level starts on its Claude model and + * steps down through the other subscriptions as limits run out. + */ +const AUTO_CANDIDATES: Readonly>> = { + high: [ + claude("claude-fable-5-2", "high"), + claude("claude-opus-5-5", "high"), + codex("gpt-6.1-sol", "high"), + codex("gpt-6-astra", "high"), + grok("high"), + codex("gpt-6-luna", "high"), + ], + medium: [ + claude("claude-opus-5-5", "medium"), + claude("claude-fable-5-2", "medium"), + codex("gpt-6.1-sol", "medium"), + codex("gpt-6-astra", "medium"), + claude("claude-sonnet-5-5", "medium"), + grok("medium"), + codex("gpt-6-luna", "medium"), + ], + low: [ + claude("claude-sonnet-5-5", "low"), + claude("claude-haiku-5-5", "low"), + opencode("opencode/big-pickle", "medium"), + opencode("opencode/deepseek-v4.1-flash-free", "medium"), + codex("gpt-6-luna", "low"), + grok("low"), + ], +}; + +/** The option each driver uses for reasoning effort. */ +const EFFORT_OPTION_ID: Readonly> = { + claudeAgent: "effort", + codex: "reasoningEffort", + grok: "reasoningEffort", + opencode: "variant", +}; + +export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { + return selection?.model === AUTO_MODEL_SLUG; +} + +function autoLevelOf(selection: ModelSelection): AutoLevel { + const value = selection.options?.find((option) => option.id === "effort")?.value; + return AUTO_LEVELS.find((level) => level === value) ?? DEFAULT_LEVEL; +} + +/** The `effort` descriptor an `auto` custom model declares, so pickers show Low/Medium/High. */ +export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { + id: "effort", + label: "Auto level", + type: "select", + options: [ + { id: "low", label: "Low", description: "Sonnet orchestrates; cheaper models do more" }, + { id: "medium", label: "Medium", description: "Opus orchestrates", isDefault: true }, + { id: "high", label: "High", description: "Fable orchestrates" }, + ], +}; + +function peakUsedPercent(provider: ServerProvider): number { + return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); +} + +/** Instances that list the `auto` model carry the Auto-mode prompt, so they win ties. */ +function isAutoAware(provider: ServerProvider): boolean { + return provider.models.some((model) => model.slug === AUTO_MODEL_SLUG); +} + +function usable(provider: ServerProvider, model: string, now: number): boolean { + return ( + provider.enabled && + provider.installed && + provider.auth.status !== "unauthenticated" && + isProviderAvailable(provider) && + provider.models.some((entry) => entry.slug === model) && + exhaustedUsageWindow(provider, now, model) === undefined + ); +} + +function effortOptions(provider: ServerProvider, candidate: AutoCandidate) { + const id = EFFORT_OPTION_ID[candidate.driver]; + const descriptor = provider.models + .find((entry) => entry.slug === candidate.model) + ?.capabilities?.optionDescriptors?.find((entry) => entry.id === id); + if (!id || descriptor?.type !== "select") return undefined; + return descriptor.options.some((choice) => choice.id === candidate.effort) + ? [{ id, value: candidate.effort }] + : undefined; +} + +function toSelection(provider: ServerProvider, candidate: AutoCandidate): ModelSelection { + const options = effortOptions(provider, candidate); + return { + instanceId: provider.instanceId, + model: candidate.model, + ...(options ? { options } : {}), + }; +} + +interface AutoResolution { + readonly selection: ModelSelection; + readonly level: AutoLevel; + /** True when the thread's current model was kept. */ + readonly sticky: boolean; +} + +/** + * Keeps the thread's model while it fits this level and is under 90% used (no account hop, no + * lost prompt cache); otherwise the first usable candidate, Auto-aware and least-used instance + * first. Null when nothing is usable. + */ +export function resolveAutoModelSelection(input: { + readonly selection: ModelSelection; + readonly providers: ReadonlyArray; + readonly now: number; + readonly current?: ModelSelection | null; +}): AutoResolution | null { + const level = autoLevelOf(input.selection); + const candidates = AUTO_CANDIDATES[level]; + + const current = input.current; + if (current && !isAutoModelSelection(current)) { + const provider = input.providers.find((entry) => entry.instanceId === current.instanceId); + const candidate = candidates.find( + (entry) => entry.driver === provider?.driver && entry.model === current.model, + ); + if ( + provider && + candidate && + usable(provider, candidate.model, input.now) && + peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT + ) { + return { selection: toSelection(provider, candidate), level, sticky: true }; + } + } + + for (const candidate of candidates) { + const instances = input.providers + .filter( + (provider) => + provider.driver === (candidate.driver as ProviderDriverKind) && + usable(provider, candidate.model, input.now), + ) + // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. + .sort( + (a, b) => + Number(isAutoAware(b)) - Number(isAutoAware(a)) || + peakUsedPercent(a) - peakUsedPercent(b), + ); + const provider = instances[0]; + if (provider) return { selection: toSelection(provider, candidate), level, sticky: false }; + } + return null; +} From 19dbbde8b205e1b8a5a801eda13f14e0e7955196 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 09:45:23 +0100 Subject: [PATCH 002/230] Give the Auto model its own icon in the model picker --- apps/web/src/components/chat/ModelListRow.tsx | 1 + apps/web/src/components/chat/ProviderInstanceIcon.tsx | 9 +++++++-- apps/web/src/components/chat/ProviderModelPicker.tsx | 2 ++ docs/progress.md | 8 ++++++++ 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/ModelListRow.tsx b/apps/web/src/components/chat/ModelListRow.tsx index 69da770f1f84..512364b5e875 100644 --- a/apps/web/src/components/chat/ModelListRow.tsx +++ b/apps/web/src/components/chat/ModelListRow.tsx @@ -57,6 +57,7 @@ export const ModelListRow = memo(function ModelListRow(props: { - {isAcpRegistry ? ( + {props.modelSlug === "auto" ? ( + + ) : isAcpRegistry ? ( )} - {isCustomEndpoint ? null : props.showBadge ? ( + {isCustomEndpoint || props.modelSlug === "auto" ? null : props.showBadge ? ( Date: Thu, 12 Nov 2026 17:51:46 +0100 Subject: [PATCH 003/230] feat(web): pooled quota view with burn projection on Usage limits Every account of a provider adds into one pool (two Claude accounts = 200%). Each limits card now shows the summed headline, when the pool and the first account run out, the next reset, the burn rate, and a recorded and projected chart. Readings are kept in this browser to draw history and measure burn. --- .../usage/UsageLimitsPooled.browser.test.tsx | 52 ++++ .../components/usage/UsageLimitsPooled.tsx | 122 +++++++-- .../src/components/usage/UsagePoolChart.tsx | 250 ++++++++++++++++++ .../src/components/usage/usagePoolHistory.ts | 64 +++++ packages/shared/package.json | 4 + .../shared/src/usagePoolProjection.test.ts | 143 ++++++++++ packages/shared/src/usagePoolProjection.ts | 179 +++++++++++++ 7 files changed, 792 insertions(+), 22 deletions(-) create mode 100644 apps/web/src/components/usage/UsagePoolChart.tsx create mode 100644 apps/web/src/components/usage/usagePoolHistory.ts create mode 100644 packages/shared/src/usagePoolProjection.test.ts create mode 100644 packages/shared/src/usagePoolProjection.ts diff --git a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx index ab114fbbd6f2..dc806b1341b2 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx @@ -63,3 +63,55 @@ describe("UsageLimitsPooled ChatGPT usage card", () => { .toBeVisible(); }); }); + +function claude(instanceId: string, displayName: string, weeklyUsed: number, resetsAt: string) { + return { + ...managedChatGpt(instanceId, displayName), + driver: ProviderDriverKind.make("claudeAgent"), + usageLimits: { + checkedAt, + windows: [ + { + id: "seven_day", + kind: "weekly" as const, + label: "Weekly", + usedPercent: weeklyUsed, + resetsAt, + windowDurationMins: 7 * 24 * 60, + }, + ], + }, + } satisfies ServerProvider; +} + +describe("UsageLimitsPooled pooled quota", () => { + it("adds the accounts into one pool and projects when it runs out", async () => { + const presentations = new Map([ + [ + EnvironmentId.make("desk"), + { + entry: { target: { label: "Desk" } }, + serverConfig: { + providers: [ + claude("claude_a", "Auto", 68, "2026-10-27T12:00:00.000Z"), + claude("claude_b", "Auto B", 27, "2026-10-31T13:00:00.000Z"), + ], + }, + }, + ], + ]); + await using screen = await render( + , + ); + + await expect.element(screen.getByText("105%", { exact: true })).toBeVisible(); + await expect.element(screen.getByText("of 200%")).toBeVisible(); + await expect.element(screen.getByText("Pool empty")).toBeVisible(); + await expect.element(screen.getByText("Burn, window avg")).toBeVisible(); + await expect + .element( + screen.getByRole("img", { name: "Weekly: pooled quota left, recorded and projected" }), + ) + .toBeVisible(); + }); +}); diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index d5f46398fa31..179cbaa21104 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -6,6 +6,7 @@ import { collectLimitPools, cursorUsageWindowDetails, displayLimitWindows, + formatDuration, formatResetsIn, type LimitAccount, type LimitPool, @@ -16,6 +17,12 @@ import { type ResetCreditChoice, resetCreditChoices, } from "@t3tools/shared/usageLimits"; +import { + poolBurn, + projectionHorizon, + projectPool, + recordedPool, +} from "@t3tools/shared/usagePoolProjection"; import type { Popover as PopoverPrimitive } from "@base-ui/react/popover"; import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; import { AlertTriangleIcon, ExternalLinkIcon, TicketIcon } from "lucide-react"; @@ -25,6 +32,7 @@ import { type ReactNode, type RefObject, use, + useEffect, useLayoutEffect, useRef, useState, @@ -42,6 +50,10 @@ import { OpenAI } from "../Icons"; import { Alert, AlertTitle } from "../ui/alert"; import { Popover, PopoverCreateHandle, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { PaceIcon, ResetCreditDialog, barColor, usePaceMark, useResetCredit } from "./UsageLimits"; +import { UsagePoolChart } from "./UsagePoolChart"; +import { poolHistoryKey, readPoolHistory, recordPoolReadings } from "./usagePoolHistory"; + +const BURN_LOOKBACK_MS = 3 * 3_600_000; function accountInitials(email: string): string { const [local = "", domain = ""] = email.split("@"); @@ -530,45 +542,104 @@ function PoolBar({ ); } +function PoolStat({ label, children }: { readonly label: string; readonly children: ReactNode }) { + return ( +
+ {label} + {children} +
+ ); +} + function PoolWindowCard({ pool, + historyKey, color, now, label, description, }: { readonly pool: LimitPoolWindow; + readonly historyKey: string; readonly color: string; readonly now: number; readonly label?: string | null | undefined; readonly description?: string | undefined; }) { - const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0); + const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat); + const samples = readPoolHistory(historyKey); + const horizon = projectionHorizon(pool); + const burn = poolBurn(pool, samples, now, BURN_LOOKBACK_MS); + const projection = projectPool(pool, now, { burnPerHour: burn.perHour, horizonMs: horizon }); + const from = now - horizon * 0.3; + const formatTime = (at: number) => + formatUpcomingTimestamp(new Date(at).toISOString(), timestampFormat, now); + const nextRefill = projection.refills[0]; + const firstEmpty = projection.firstEmpty + ? pool.members.find((member) => member.account.key === projection.firstEmpty?.accountKey) + : undefined; + const burnText = `${burn.perHour >= 10 ? Math.round(burn.perHour) : burn.perHour.toFixed(1)}%/h`; return ( -
-
- {label !== null ? ( - {label ?? pool.label} - ) : null} - - - {pool.remainingPercent}% - - - left - {pool.pace ? : null} - - - {nextRefill && pool.columns.length > 1 ? ( - - ↻ +{nextRefill.restoresPercent}% +
+
+
+ {label !== null ? ( + {label ?? pool.label} + ) : null} + + + {Math.round(projection.remaining)}% + + + of {projection.capacity}% + {pool.pace ? : null} + - ) : null} +
+
+ + {projection.poolEmpty === null + ? `Not by ${new Date(now + horizon).toLocaleDateString([], { month: "short", day: "numeric" })}` + : projection.poolEmpty <= now + ? "Empty now" + : formatTime(projection.poolEmpty)} + + + {firstEmpty && projection.firstEmpty ? ( + + {pool.members.length > 1 ? ( + + ) : null} + + {projection.firstEmpty.at <= now + ? "now" + : `in ${formatDuration(projection.firstEmpty.at - now)}`} + + + ) : ( + "None" + )} + + + {nextRefill ? `+${Math.round(nextRefill.restores)}% ${formatTime(nextRefill.at)}` : "–"} + + + {burnText} + +
+ - {description ? ( -

{description}

- ) : null} + {description ?

{description}

: null}
); } @@ -596,6 +667,7 @@ function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: nu PopoverCreateHandle()); const segmentPopoverActions = useRef(null); const pools = collectLimitPools(collectLimitAccounts(presentations), now); + // Readings are stamped with each provider's checkedAt, so re-renders of the same data store + // nothing new. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps this browser's localStorage reading history in step with the limits it has been shown + useEffect(() => { + recordPoolReadings(pools, now); + }, [pools, now]); const notices = collectLimitNotices(presentations); const externalLinks = collectExternalUsageLinks(presentations); return ( diff --git a/apps/web/src/components/usage/UsagePoolChart.tsx b/apps/web/src/components/usage/UsagePoolChart.tsx new file mode 100644 index 000000000000..fe5c7de1a6b4 --- /dev/null +++ b/apps/web/src/components/usage/UsagePoolChart.tsx @@ -0,0 +1,250 @@ +import type { PoolProjection } from "@t3tools/shared/usagePoolProjection"; +import { useId, useLayoutEffect, useRef, useState } from "react"; + +import { observeResize } from "../../lib/observeResize"; + +const HEIGHT = 190; +const PAD = { left: 44, right: 8, top: 22, bottom: 22 }; +const DAY = 86_400_000; +const HOUR = 3_600_000; + +type Point = { readonly at: number; readonly remaining: number }; + +function percent(value: number) { + return `${Math.round(value)}%`; +} + +function timeTicks(from: number, to: number): ReadonlyArray<{ at: number; label: string }> { + const span = to - from; + if (span > 2 * DAY) { + const every = Math.max(1, Math.ceil(span / DAY / 10)); + const start = new Date(from); + start.setHours(24, 0, 0, 0); + const ticks = []; + for (let at = start.getTime(); at < to; at += every * DAY) { + ticks.push({ + at: at + DAY / 2, + label: new Date(at).toLocaleDateString([], { weekday: "short", day: "numeric" }), + }); + } + return ticks; + } + const start = new Date(from); + start.setMinutes(60, 0, 0); + while (start.getHours() % 3 !== 0) start.setHours(start.getHours() + 1); + const ticks = []; + for (let at = start.getTime(); at < to; at += 3 * HOUR) { + ticks.push({ + at, + label: new Date(at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }), + }); + } + return ticks; +} + +/** Drops a label that would overlap the one before it. */ +function spacedLabels(labels: readonly T[]): T[] { + const shown: T[] = []; + for (const label of labels) { + if (label.x - (shown.at(-1)?.x ?? -Infinity) >= 34) shown.push(label); + } + return shown; +} + +/** Pooled remaining quota: readings so far as a solid line, the projection dashed. */ +export function UsagePoolChart({ + color, + label, + recorded, + projection, + from, + to, + now, + formatTime, +}: { + readonly color: string; + readonly label: string; + readonly recorded: readonly Point[]; + readonly projection: PoolProjection; + readonly from: number; + readonly to: number; + readonly now: number; + readonly formatTime: (at: number) => string; +}) { + const box = useRef(null); + const [width, setWidth] = useState(0); + const [hover, setHover] = useState(null); + const gradient = useId(); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the container DOM width before paint and remeasures through a ResizeObserver + useLayoutEffect(() => { + const element = box.current; + if (!element) return; + const measure = () => setWidth(element.getBoundingClientRect().width); + measure(); + return observeResize(element, measure); + }, []); + + const cap = Math.max(100, projection.capacity); + const x = (at: number) => + PAD.left + ((at - from) / (to - from)) * Math.max(0, width - PAD.left - PAD.right); + const y = (value: number) => PAD.top + (HEIGHT - PAD.top - PAD.bottom) * (1 - value / cap); + const line = (points: readonly Point[]) => + points + .map((p, i) => `${i === 0 ? "M" : "L"}${x(p.at).toFixed(1)},${y(p.remaining).toFixed(1)}`) + .join(""); + const all = [...recorded, ...projection.points]; + const first = all[0]; + const last = all.at(-1); + const area = first && last ? `${line(all)}L${x(last.at)},${y(0)}L${x(first.at)},${y(0)}Z` : ""; + const start = projection.points[0]; + + const refillLabels = spacedLabels( + projection.refills.map((refill) => ({ ...refill, x: x(refill.at) })), + ); + + const pick = (clientX: number) => { + const rect = box.current?.getBoundingClientRect(); + if (!rect || all.length === 0) return; + const at = + from + ((clientX - rect.left - PAD.left) / (width - PAD.left - PAD.right)) * (to - from); + setHover( + all.reduce((best, p) => (Math.abs(p.at - at) < Math.abs(best.at - at) ? p : best), all[0]!), + ); + }; + + return ( +
+ {width > 0 ? ( + pick(event.clientX)} + onPointerLeave={() => setHover(null)} + > + + + + + + + {[0, cap / 2, cap].map((value) => ( + + + + {percent(value)} + + + ))} + {timeTicks(from, to).map((tick) => ( + + {tick.label} + + ))} + + {recorded.length > 0 && start ? ( + + ) : null} + + {refillLabels.map((refill) => ( + + +{percent(refill.restores)} + + ))} + + + Now + + {start ? ( + + ) : null} + {projection.poolEmpty !== null && projection.poolEmpty > now ? ( + + + + Empty {formatTime(projection.poolEmpty)} + + + ) : null} + {hover ? : null} + + ) : null} + {hover ? ( +
+
+ {formatTime(hover.at)} + {hover.at > now ? " · projected" : ""} +
+
+ {percent(hover.remaining)} of {percent(projection.capacity)} +
+
+ ) : null} +
+ ); +} diff --git a/apps/web/src/components/usage/usagePoolHistory.ts b/apps/web/src/components/usage/usagePoolHistory.ts new file mode 100644 index 000000000000..3780d4e6af53 --- /dev/null +++ b/apps/web/src/components/usage/usagePoolHistory.ts @@ -0,0 +1,64 @@ +import type { LimitPool, LimitPoolWindow } from "@t3tools/shared/usageLimits"; +import type { PoolSample } from "@t3tools/shared/usagePoolProjection"; +import * as Schema from "effect/Schema"; + +import { getLocalStorageItem, setLocalStorageItem } from "../../hooks/useLocalStorage"; + +// Providers report limits only as a current percentage, so this browser keeps the readings it +// has seen to draw the recorded line and measure burn. +const STORAGE_KEY = "t3code:usage-pool-history:v1"; +const KEEP_MS = 14 * 24 * 3_600_000; +const MIN_GAP_MS = 4 * 60_000; + +const Sample = Schema.Struct({ + at: Schema.Number, + used: Schema.Record(Schema.String, Schema.Number), +}); +const History = Schema.Record(Schema.String, Schema.Array(Sample)); +type History = typeof History.Type; + +export function poolHistoryKey(pool: LimitPool, window: LimitPoolWindow): string { + return `${pool.driver}:${window.kind}:${window.id}`; +} + +function read(): History { + try { + return getLocalStorageItem(STORAGE_KEY, History) ?? {}; + } catch { + return {}; + } +} + +export function readPoolHistory(key: string): readonly PoolSample[] { + return read()[key] ?? []; +} + +/** Stores one reading per window, stamped with when the provider was checked. */ +export function recordPoolReadings(pools: readonly LimitPool[], now: number): void { + const history: Record = { ...read() }; + let changed = false; + for (const pool of pools) { + for (const window of pool.windows) { + const checked = window.members + .map((member) => Date.parse(member.account.limits.checkedAt)) + .filter(Number.isFinite); + if (checked.length === 0) continue; + const at = Math.min(now, Math.max(...checked)); + const key = poolHistoryKey(pool, window); + const samples = (history[key] ?? []).filter((sample) => sample.at >= now - KEEP_MS); + const last = samples.at(-1); + if (last && at - last.at < MIN_GAP_MS) continue; + const used = Object.fromEntries( + window.members.map((member) => [member.account.key, member.window.usedPercent]), + ); + history[key] = [...samples, { at, used }]; + changed = true; + } + } + if (!changed) return; + try { + setLocalStorageItem(STORAGE_KEY, history, History); + } catch (error) { + console.error("Could not save usage limit readings.", error); + } +} diff --git a/packages/shared/package.json b/packages/shared/package.json index 2e9aeb055f60..87bf8f535ce8 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -395,6 +395,10 @@ "types": "./src/usageLimits.ts", "import": "./src/usageLimits.ts" }, + "./usagePoolProjection": { + "types": "./src/usagePoolProjection.ts", + "import": "./src/usagePoolProjection.ts" + }, "./desktopAppControl": { "types": "./src/desktopAppControl.ts", "import": "./src/desktopAppControl.ts" diff --git a/packages/shared/src/usagePoolProjection.test.ts b/packages/shared/src/usagePoolProjection.test.ts new file mode 100644 index 000000000000..d96745368449 --- /dev/null +++ b/packages/shared/src/usagePoolProjection.test.ts @@ -0,0 +1,143 @@ +import { describe, expect, it } from "vite-plus/test"; + +import type { LimitPoolWindow } from "./usageLimits.ts"; +import { poolBurn, projectionHorizon, projectPool, recordedPool } from "./usagePoolProjection.ts"; + +const HOUR = 3_600_000; +const now = Date.parse("2026-11-12T12:00:00.000Z"); +const iso = (at: number) => new Date(at).toISOString(); + +function pool( + members: ReadonlyArray<{ key: string; used: number; resetsIn?: number; mins?: number }>, + kind: LimitPoolWindow["kind"] = "weekly", +): LimitPoolWindow { + const list = members.map((m) => ({ + account: { key: m.key } as LimitPoolWindow["members"][number]["account"], + window: { + id: "seven_day", + kind, + label: "Weekly", + usedPercent: m.used, + ...(m.resetsIn === undefined ? {} : { resetsAt: iso(now + m.resetsIn) }), + windowDurationMins: m.mins ?? 7 * 24 * 60, + }, + refillPercent: m.used, + })); + return { + id: "seven_day", + kind, + label: "Weekly", + members: list, + columns: list, + remainingPercent: 0, + usedPercent: 0, + pace: null, + resets: [], + }; +} + +describe("projectPool", () => { + it("sums every account into one pool", () => { + const projection = projectPool( + pool([ + { key: "a", used: 60, resetsIn: 48 * HOUR }, + { key: "b", used: 30, resetsIn: 120 * HOUR }, + ]), + now, + { burnPerHour: 0, horizonMs: 7 * 24 * HOUR }, + ); + expect(projection.capacity).toBe(200); + expect(projection.remaining).toBe(110); + expect(projection.poolEmpty).toBeNull(); + // With no spend, each reset gives back what that account had used. + expect(projection.refills.map((r) => [r.accountKey, r.restores, r.remainingAfter])).toEqual([ + ["a", 60, 170], + ["b", 30, 200], + ]); + expect(projection.points.at(-1)?.remaining).toBe(200); + }); + + it("spends the account that resets first and finds when the pool runs dry", () => { + const projection = projectPool( + pool([ + { key: "late", used: 0, resetsIn: 150 * HOUR }, + { key: "soon", used: 50, resetsIn: 140 * HOUR }, + ]), + now, + { burnPerHour: 10, horizonMs: 24 * HOUR, steps: 240 }, + ); + // 50 points left on "soon" at 10/h: empty after 5 h; then 100 on "late": pool dry at 15 h. + expect(projection.firstEmpty).toEqual({ at: now + 5 * HOUR, accountKey: "soon" }); + expect(projection.poolEmpty).toBe(now + 15 * HOUR); + }); + + it("reports an exhausted account as empty now", () => { + const projection = projectPool( + pool([ + { key: "a", used: 100, resetsIn: HOUR }, + { key: "b", used: 0, resetsIn: 5 * HOUR }, + ]), + now, + { burnPerHour: 0, horizonMs: 24 * HOUR }, + ); + expect(projection.firstEmpty).toEqual({ at: now, accountKey: "a" }); + expect(projection.poolEmpty).toBeNull(); + }); +}); + +describe("poolBurn", () => { + const twoAccounts = pool([ + { key: "a", used: 35, resetsIn: 100 * HOUR }, + { key: "b", used: 5, resetsIn: 100 * HOUR }, + ]); + + it("measures spend from stored readings and counts a drop as a reset", () => { + const burn = poolBurn( + twoAccounts, + [ + { at: now - 2 * HOUR, used: { a: 10, b: 90 } }, + { at: now - HOUR, used: { a: 20, b: 100 } }, + { at: now, used: { a: 35, b: 5 } }, + ], + now, + 3 * HOUR, + ); + // a: +10 +15, b: +10 then a reset worth 5 → 40 points over 2 h. + expect(burn).toEqual({ perHour: 20, source: "measured" }); + }); + + it("falls back to the average since each window opened", () => { + // Weekly windows with 100 h left have run 68 h: 35/68 + 5/68 points per hour. + const burn = poolBurn(twoAccounts, [{ at: now, used: { a: 35, b: 5 } }], now, 3 * HOUR); + expect(burn.source).toBe("window"); + expect(burn.perHour).toBeCloseTo(40 / 68, 6); + }); +}); + +describe("recordedPool", () => { + it("carries an account's last reading forward", () => { + const series = recordedPool( + pool([ + { key: "a", used: 0 }, + { key: "b", used: 0 }, + ]), + [ + { at: now - 3 * HOUR, used: { a: 10 } }, + { at: now - 2 * HOUR, used: { a: 20, b: 50 } }, + { at: now - HOUR, used: { b: 60 } }, + ], + now - 24 * HOUR, + ); + expect(series).toEqual([ + { at: now - 2 * HOUR, remaining: 130 }, + { at: now - HOUR, remaining: 120 }, + ]); + }); +}); + +describe("projectionHorizon", () => { + it("looks a day ahead for session windows and a week for weekly ones", () => { + expect(projectionHorizon(pool([{ key: "a", used: 0, mins: 300 }], "session"))).toBe(24 * HOUR); + expect(projectionHorizon(pool([{ key: "a", used: 0 }]))).toBe(7 * 24 * HOUR); + }); +}); diff --git a/packages/shared/src/usagePoolProjection.ts b/packages/shared/src/usagePoolProjection.ts new file mode 100644 index 000000000000..b157ac57fac5 --- /dev/null +++ b/packages/shared/src/usagePoolProjection.ts @@ -0,0 +1,179 @@ +/** + * Pooled quota projection: every account of a provider counts toward one pool (two Claude + * subscriptions = 200%). The pool drains at the current burn rate, spending the account that + * resets first, and each account refills when its window resets. + */ +import type { LimitPoolWindow } from "./usageLimits.ts"; + +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; +/** Measured burn needs at least this much history; shorter spans are mostly noise. */ +const MIN_MEASURED_SPAN = 15 * MINUTE; + +/** One reading of a pool: used percent per account key. */ +export interface PoolSample { + readonly at: number; + readonly used: Readonly>; +} + +interface PoolBurn { + /** Percentage points of the pool spent per hour. */ + readonly perHour: number; + /** "measured" comes from stored readings, "window" from the average since each window opened. */ + readonly source: "measured" | "window"; +} + +export interface PoolProjection { + readonly capacity: number; + readonly remaining: number; + readonly points: ReadonlyArray<{ readonly at: number; readonly remaining: number }>; + readonly refills: ReadonlyArray<{ + readonly at: number; + readonly accountKey: string; + /** Percentage points this reset gives back. */ + readonly restores: number; + /** Pool remaining right after the reset. */ + readonly remainingAfter: number; + }>; + readonly firstEmpty: { readonly at: number; readonly accountKey: string } | null; + readonly poolEmpty: number | null; +} + +const clampUsed = (value: number) => Math.max(0, Math.min(100, value)); + +function resetAt(resetsAt: string | undefined): number | null { + if (resetsAt === undefined) return null; + const at = Date.parse(resetsAt); + return Number.isFinite(at) ? at : null; +} + +/** How far ahead to project: a day for session windows, otherwise one full window. */ +export function projectionHorizon(pool: LimitPoolWindow): number { + const longest = Math.max(0, ...pool.members.map((m) => m.window.windowDurationMins ?? 0)); + if (pool.kind === "session" || (longest > 0 && longest <= 12 * 60)) return DAY; + if (pool.kind === "monthly" || longest >= 28 * 24 * 60) return 31 * DAY; + return 7 * DAY; +} + +function windowAverageBurn(pool: LimitPoolWindow, now: number): number { + let perHour = 0; + for (const { window } of pool.members) { + const at = resetAt(window.resetsAt); + if (at === null || !window.windowDurationMins) continue; + const elapsed = window.windowDurationMins * MINUTE - (at - now); + if (elapsed >= MIN_MEASURED_SPAN) perHour += clampUsed(window.usedPercent) / (elapsed / HOUR); + } + return perHour; +} + +/** + * Burn over the last `lookbackMs` from stored readings. A drop between readings means the + * window reset, so the new value counts as fresh spend. Falls back to the window average while + * the readings span less than 15 minutes. + */ +export function poolBurn( + pool: LimitPoolWindow, + samples: readonly PoolSample[], + now: number, + lookbackMs: number, +): PoolBurn { + const recent = samples.filter((sample) => sample.at >= now - lookbackMs && sample.at <= now); + const first = recent[0]; + const last = recent.at(-1); + if (!first || !last || last.at - first.at < MIN_MEASURED_SPAN) { + return { perHour: windowAverageBurn(pool, now), source: "window" }; + } + let spent = 0; + for (const { account } of pool.members) { + let previous: number | undefined; + for (const sample of recent) { + const used = sample.used[account.key]; + if (used === undefined) continue; + if (previous !== undefined) spent += used >= previous ? used - previous : used; + previous = used; + } + } + return { perHour: spent / ((last.at - first.at) / HOUR), source: "measured" }; +} + +export function projectPool( + pool: LimitPoolWindow, + now: number, + options: { readonly burnPerHour: number; readonly horizonMs: number; readonly steps?: number }, +): PoolProjection { + const accounts = pool.members.map((member) => ({ + key: member.account.key, + used: clampUsed(member.window.usedPercent), + reset: resetAt(member.window.resetsAt), + length: (member.window.windowDurationMins ?? 0) * MINUTE, + })); + const remainingNow = () => accounts.reduce((sum, account) => sum + 100 - account.used, 0); + const capacity = accounts.length * 100; + const remaining = remainingNow(); + const points = [{ at: now, remaining }]; + const refills: Array = []; + const exhausted = accounts.find((account) => account.used >= 100); + let firstEmpty = exhausted ? { at: now, accountKey: exhausted.key } : null; + let poolEmpty = accounts.length > 0 && remaining <= 0 ? now : null; + const steps = options.steps ?? 480; + const step = options.horizonMs / steps; + + for (let index = 1; index <= steps; index += 1) { + const at = now + index * step; + for (const account of accounts) { + while (account.reset !== null && account.reset <= at) { + const restores = account.used; + account.used = 0; + if (restores > 0.5) { + refills.push({ + at: account.reset, + accountKey: account.key, + restores, + remainingAfter: remainingNow(), + }); + } + account.reset = account.length > 0 ? account.reset + account.length : null; + } + } + let drain = (options.burnPerHour * step) / HOUR; + const spendable = accounts + .filter((account) => account.used < 100) + .sort((left, right) => (left.reset ?? Infinity) - (right.reset ?? Infinity)); + for (const account of spendable) { + if (drain <= 0) break; + // An unused window opens on first spend. + if (account.reset === null && account.used === 0 && account.length > 0) { + account.reset = at + account.length; + } + const take = Math.min(drain, 100 - account.used); + account.used += take; + drain -= take; + if (account.used >= 100 && firstEmpty === null) firstEmpty = { at, accountKey: account.key }; + } + const left = remainingNow(); + if (left <= 1e-6 && poolEmpty === null) poolEmpty = at; + points.push({ at, remaining: left }); + } + return { capacity, remaining, points, refills, firstEmpty, poolEmpty }; +} + +/** Pool remaining at each stored reading since `from`, carrying an account's last value forward. */ +export function recordedPool( + pool: LimitPoolWindow, + samples: readonly PoolSample[], + from: number, +): ReadonlyArray<{ readonly at: number; readonly remaining: number }> { + const keys = pool.members.map((member) => member.account.key); + const last: Record = {}; + const series: Array<{ at: number; remaining: number }> = []; + for (const sample of samples) { + for (const key of keys) { + const used = sample.used[key]; + if (used !== undefined) last[key] = clampUsed(used); + } + if (sample.at < from || keys.some((key) => last[key] === undefined)) continue; + series.push({ at: sample.at, remaining: keys.reduce((sum, key) => sum + 100 - last[key]!, 0) }); + } + return series; +} From 3c85f0a4c6463dc7aa9a157565787c5c5e6b9f91 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 12:44:18 +0100 Subject: [PATCH 004/230] Show the model and account Auto routes to in the model picker --- .../chat/ComposerFooterControls.tsx | 3 + .../components/chat/ModelPickerContent.tsx | 9 ++- .../components/chat/ProviderInstanceIcon.tsx | 21 ++++-- .../components/chat/ProviderModelPicker.tsx | 38 +++++++--- .../web/src/components/chat/autoRoute.test.ts | 75 +++++++++++++++++++ apps/web/src/components/chat/autoRoute.ts | 54 +++++++++++++ docs/progress.md | 7 ++ 7 files changed, 191 insertions(+), 16 deletions(-) create mode 100644 apps/web/src/components/chat/autoRoute.test.ts create mode 100644 apps/web/src/components/chat/autoRoute.ts diff --git a/apps/web/src/components/chat/ComposerFooterControls.tsx b/apps/web/src/components/chat/ComposerFooterControls.tsx index ff8ea79ebd31..61bde4cff4f9 100644 --- a/apps/web/src/components/chat/ComposerFooterControls.tsx +++ b/apps/web/src/components/chat/ComposerFooterControls.tsx @@ -314,6 +314,9 @@ export function ComposerModelPicker({ return ( ; onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; lockedProvider: ProviderDriverKind | null; @@ -776,6 +779,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { modelJumpLabelByKey, activeModelKey, selectedModelKeySet, + autoRouteLabel: props.autoRoute?.label, }; const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { @@ -1035,15 +1039,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { } const disabledReason = getModelDisabledReason?.(model.instanceId, model.slug) ?? null; + const autoRoute = model.slug === "auto" ? props.autoRoute : null; return ( - {props.modelSlug === "auto" ? ( - - ) : isAcpRegistry ? ( + {isAcpRegistry ? ( )} - {isCustomEndpoint || props.modelSlug === "auto" ? null : props.showBadge ? ( + {isCustomEndpoint ? null : props.modelSlug === "auto" ? ( + // Auto keeps the logo of the provider it routes to and marks it with a route badge. + + + + ) : props.showBadge ? ( ; onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; lockedProvider: ProviderDriverKind | null; @@ -128,6 +133,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { footer?: ReactNode; }) { const composerFloatingLayerProps = useComposerMenuProps(); + const nowMinute = useNowMinute(); const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false); const isMenuOpen = props.open ?? uncontrolledIsMenuOpen; const registry = useContext(RegistryContext); @@ -167,14 +173,27 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { (activeEntry?.driverKind === "opencode" || activeEntry?.driverKind === "antigravity" ? undefined : selectedInstanceOptions[0]); - const triggerTitle = selectedModel - ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) - : props.model === ANTIGRAVITY_DEFAULT_MODEL - ? "Choose model" - : props.model || "Choose model"; - const triggerLabel = selectedModel - ? `${getDisplayModelName(selectedModel)}${selectedModel.isUnavailable ? " (Unavailable)" : ""}` - : triggerTitle; + const isAuto = props.model === "auto"; + // Names the model Auto would pick now, at this selection's level (default level elsewhere). + const autoRoute = describeAutoRoute({ + entries: props.instanceEntries, + ...(isAuto && props.modelSelectionOptions ? { options: props.modelSelectionOptions } : {}), + now: Date.parse(nowMinute), + }); + const triggerTitle = + isAuto && autoRoute + ? `Auto · ${autoRoute.label}` + : selectedModel + ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) + : props.model === ANTIGRAVITY_DEFAULT_MODEL + ? "Choose model" + : props.model || "Choose model"; + const triggerLabel = + isAuto && autoRoute + ? triggerTitle + : selectedModel + ? `${getDisplayModelName(selectedModel)}${selectedModel.isUnavailable ? " (Unavailable)" : ""}` + : triggerTitle; const showInstanceBadge = activeEntry !== null && shouldShowInstanceBadge(activeEntry, props.instanceEntries); @@ -284,6 +303,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { workspaceCwd={props.workspaceCwd ?? null} activeInstanceId={activeInstanceId} model={props.model} + autoRoute={autoRoute} {...(props.selectedModels !== undefined ? { selectedModels: props.selectedModels } : {})} {...(props.onToggleModel ? { @@ -404,7 +424,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { // Narrow compacted composers hide the provider icon before truncating the name. , + usedPercent: number, +): ServerProvider { + return { + instanceId: ProviderInstanceId.make(id), + driver: ProviderDriverKind.make(driver), + displayName, + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-11-13T11:00:00.000Z", + models: models.map((model) => ({ ...model, isCustom: false, capabilities: null })), + slashCommands: [], + skills: [], + usageLimits: { + windows: [ + { + id: "five_hour", + kind: "session", + label: "Session", + usedPercent, + resetsAt: "2026-11-13T15:00:00.000Z", + }, + ], + }, + } as unknown as ServerProvider; +} + +const claudeModels = [ + { slug: "claude-fable-5-2", name: "Claude Fable 5.2" }, + { slug: "claude-opus-5-5", name: "Claude Opus 5.5" }, + { slug: "claude-sonnet-5-5", name: "Claude Sonnet 5.5" }, + { slug: "auto", name: "Auto" }, +]; + +describe("describeAutoRoute", () => { + it("names the Claude model and account Auto would use", () => { + const entries = deriveProviderInstanceEntries([ + provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 70), + provider("claudeAutoB", "Auto B", "claudeAgent", claudeModels, 10), + ]); + const medium = describeAutoRoute({ entries, now }); + expect(medium?.driverKind).toBe("claudeAgent"); + expect(medium?.label).toMatch(/^.*Opus 5\.5 \(B\)$/); + + const high = describeAutoRoute({ entries, options: [{ id: "effort", value: "high" }], now }); + expect(high?.label).toMatch(/Fable 5\.2 \(B\)$/); + }); + + it("names another provider when both Claude accounts are used up", () => { + const entries = deriveProviderInstanceEntries([ + provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 100), + provider("claudeAutoB", "Auto B", "claudeAgent", claudeModels, 100), + provider("grok", "Grok Build", "grok", [{ slug: "grok-4.7", name: "Grok 4.7" }], 0), + ]); + expect(describeAutoRoute({ entries, now })).toMatchObject({ + driverKind: "grok", + label: expect.stringMatching(/Grok 4\.7 \(Grok Build\)$/), + }); + }); +}); diff --git a/apps/web/src/components/chat/autoRoute.ts b/apps/web/src/components/chat/autoRoute.ts new file mode 100644 index 000000000000..d1a89457bf7f --- /dev/null +++ b/apps/web/src/components/chat/autoRoute.ts @@ -0,0 +1,54 @@ +import { + ProviderInstanceId, + type ModelSelection, + type ProviderDriverKind, +} from "@t3tools/contracts"; +import { resolveAutoModelSelection } from "@t3tools/shared/autoModel"; + +import type { ProviderInstanceEntry } from "../../providerInstances"; +import { getTriggerDisplayModelName } from "./providerIconUtils"; + +/** What the `auto` model would run as right now, for labels such as "Auto · Opus 5.5 (B)". */ +export interface AutoRoute { + readonly driverKind: ProviderDriverKind; + /** The concrete model and its account, such as "Opus 5.5 (B)". */ + readonly label: string; +} + +/** + * Mirrors the server's routing (same resolver, same live usage snapshots), so the picker shows + * the model a new message would get. The server still decides per message; a thread already on + * a model may stay on it. + */ +export function describeAutoRoute(input: { + readonly entries: ReadonlyArray; + readonly options?: ModelSelection["options"]; + readonly now: number; +}): AutoRoute | null { + const resolution = resolveAutoModelSelection({ + selection: { + instanceId: ProviderInstanceId.make("auto"), + model: "auto", + ...(input.options ? { options: input.options } : {}), + }, + providers: input.entries.map((entry) => entry.snapshot), + now: input.now, + }); + if (!resolution) return null; + const entry = input.entries.find( + (candidate) => candidate.instanceId === resolution.selection.instanceId, + ); + const model = entry?.models.find((candidate) => candidate.slug === resolution.selection.model); + if (!entry || !model) return null; + // Claude instances are named "Auto" (account A) and "Auto B"; other providers keep their name. + const account = + entry.driverKind === "claudeAgent" + ? /\bB$/.test(entry.displayName) + ? "B" + : "A" + : entry.displayName; + return { + driverKind: entry.driverKind, + label: `${getTriggerDisplayModelName(model, entry.driverKind)} (${account})`, + }; +} diff --git a/docs/progress.md b/docs/progress.md index 46c2223b1d5c..3ba9579db6ab 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -16,3 +16,10 @@ - How: `ProviderInstanceIcon` takes an optional `modelSlug`; `ModelListRow` and `ProviderModelPicker` pass it. Lint rules ruled out Sparkles and raw palette colors. - Deploy: web-only, so the new `apps/web/dist` was copied into `apps/server/dist/client`; no service restart. The web build took ~45 min on the hub (disk-bound). - Next: keep "Auto" shown in the composer after the first message (needs the thread to remember the Auto selection). + +## 2026-11-13 — Auto shows the model it routes to + +- What: the `auto` entry keeps the logo of the provider it routes to (the Claude logo while Claude has room) with a small route badge, and its label names the model and account, e.g. "Auto · Opus 5.5 (B)", in the picker rows and on the composer button. +- Why: Tomáš wanted to see which Claude model Auto uses; the plain route icon hid it. +- How: `describeAutoRoute` (web) runs the server's `resolveAutoModelSelection` on the client's provider snapshots, at the composer's Auto level, on a minute clock. The server still decides per message (a thread may stay on its current model until 90% used). +- Tests: `autoRoute.test.ts` (2 tests: A/B pick per level, fallback to Grok). The test run alone took ~14 min on the hub. From e6304da64a2e814995cdbde6b0ddca89c2673f5f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 13:03:44 +0100 Subject: [PATCH 005/230] Auto routes Claude A/B by 5-hour use and weekly reset, adds Antigravity, lists levels as picker rows Between Claude accounts, Auto takes the freer 5-hour window; within 10 points it spends the account whose weekly quota resets first. Antigravity's Claude models follow the Claude subscriptions at every level. auto-low/auto-medium/auto-high fix the level in the slug so the Auto picker tab lists one row per level. Usage limits open with a per-subscription overview. --- .../components/chat/ModelPickerContent.tsx | 13 ++- .../components/chat/ProviderInstanceIcon.tsx | 3 +- .../components/chat/ProviderModelPicker.tsx | 12 ++- apps/web/src/components/chat/autoRoute.ts | 4 +- .../components/usage/UsageLimitsPooled.tsx | 53 +++++++++++++ docs/progress.md | 8 ++ packages/shared/src/autoModel.test.ts | 79 ++++++++++++++++++- packages/shared/src/autoModel.ts | 68 +++++++++++++--- 8 files changed, 221 insertions(+), 19 deletions(-) diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index c3471bbd1e92..c91ae18874eb 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -41,6 +41,7 @@ import { ComboboxListVirtualized, } from "../ui/combobox"; import { ModelEsque } from "./providerIconUtils"; +import { isAutoModelSlug } from "@t3tools/shared/autoModel"; import type { AutoRoute } from "./autoRoute"; import { isCommandPaletteOpen } from "../../commandPaletteBus"; import { registerModelPickerContent } from "../../modelPickerVisibility"; @@ -329,8 +330,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { workspaceCwd?: string | null; activeInstanceId: ProviderInstanceId; model: string; - /** What the `auto` model routes to right now; its rows show it. */ - autoRoute?: AutoRoute | null; + /** What an Auto model row (`auto`, `auto-low`, ...) routes to right now; its row shows it. */ + autoRouteFor?: (slug: string) => AutoRoute | null; selectedModels?: ReadonlyArray<{ instanceId: ProviderInstanceId; model: string }>; onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; lockedProvider: ProviderDriverKind | null; @@ -779,7 +780,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { modelJumpLabelByKey, activeModelKey, selectedModelKeySet, - autoRouteLabel: props.autoRoute?.label, + autoRouteLabels: ["auto", "auto-low", "auto-medium", "auto-high"] + .map((slug) => props.autoRouteFor?.(slug)?.label ?? "") + .join("|"), }; const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { @@ -1039,7 +1042,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { } const disabledReason = getModelDisabledReason?.(model.instanceId, model.slug) ?? null; - const autoRoute = model.slug === "auto" ? props.autoRoute : null; + const autoRoute = isAutoModelSlug(model.slug) + ? (props.autoRouteFor?.(model.slug) ?? null) + : null; return ( )} - {isCustomEndpoint ? null : props.modelSlug === "auto" ? ( + {isCustomEndpoint ? null : isAutoModelSlug(props.modelSlug) ? ( // Auto keeps the logo of the provider it routes to and marks it with a route badge. + describeAutoRoute({ entries: props.instanceEntries, model: slug, now }); const triggerTitle = isAuto && autoRoute ? `Auto · ${autoRoute.label}` @@ -303,7 +309,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { workspaceCwd={props.workspaceCwd ?? null} activeInstanceId={activeInstanceId} model={props.model} - autoRoute={autoRoute} + autoRouteFor={autoRouteFor} {...(props.selectedModels !== undefined ? { selectedModels: props.selectedModels } : {})} {...(props.onToggleModel ? { diff --git a/apps/web/src/components/chat/autoRoute.ts b/apps/web/src/components/chat/autoRoute.ts index d1a89457bf7f..eff72e2a9e71 100644 --- a/apps/web/src/components/chat/autoRoute.ts +++ b/apps/web/src/components/chat/autoRoute.ts @@ -22,13 +22,15 @@ export interface AutoRoute { */ export function describeAutoRoute(input: { readonly entries: ReadonlyArray; + /** `auto`, or a fixed-level `auto-low` / `auto-medium` / `auto-high`. */ + readonly model?: string; readonly options?: ModelSelection["options"]; readonly now: number; }): AutoRoute | null { const resolution = resolveAutoModelSelection({ selection: { instanceId: ProviderInstanceId.make("auto"), - model: "auto", + model: input.model ?? "auto", ...(input.options ? { options: input.options } : {}), }, providers: input.entries.map((entry) => entry.snapshot), diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index 179cbaa21104..ced95f36626e 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -679,6 +679,58 @@ function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: nu ); } +/** One row per subscription: every window it reports, so no account hides inside a pool. */ +function SubscriptionsOverview({ + pools, + now, +}: { + readonly pools: readonly LimitPool[]; + readonly now: number; +}) { + const rows = pools.flatMap((pool) => pool.accounts.map((account) => ({ pool, account }))); + if (rows.length === 0) return null; + return ( +
+

Subscriptions

+
+ {rows.map(({ pool, account }) => ( +
+ + + + + {account.limits.windows.map((window) => { + const resetsIn = formatResetsIn(window, now); + return ( + + {window.label} + {remainingPercent(window)}% + {resetsIn ? {resetsIn.replace("resets in ", "↻ ")} : null} + + ); + })} +
+ ))} +
+
+ ); +} + export function UsageLimitsPooled({ presentations, now, @@ -704,6 +756,7 @@ export function UsageLimitsPooled({ No provider on the selected environments reports subscription limits.

) : null} + {pools.map((pool) => ( diff --git a/docs/progress.md b/docs/progress.md index 3ba9579db6ab..1a91af83a5bb 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -23,3 +23,11 @@ - Why: Tomáš wanted to see which Claude model Auto uses; the plain route icon hid it. - How: `describeAutoRoute` (web) runs the server's `resolveAutoModelSelection` on the client's provider snapshots, at the composer's Auto level, on a minute clock. The server still decides per message (a thread may stay on its current model until 90% used). - Tests: `autoRoute.test.ts` (2 tests: A/B pick per level, fallback to Grok). The test run alone took ~14 min on the hub. + +## 2026-11-13: Auto routes by 5-hour use and weekly reset; Auto levels as picker rows; subscriptions overview + +- What: Auto now picks between Claude accounts by the freer 5-hour window; when two accounts are within 10 points, it spends the one whose weekly quota resets first (unused quota is lost at reset). Antigravity's Claude models (Opus 4.6 Thinking, Sonnet 4.6) sit right after the Claude subscriptions in every level. `auto-low` / `auto-medium` / `auto-high` fix the level in the model slug, so the Auto tab in the picker lists one row per level, each naming its current route. Usage → Limits opens with a Subscriptions table: one row per account with every window's remaining % and reset. +- Why: Tomáš wants Auto to always use Claude A/B first and route by 5-hour room and weekly expiry, use the Antigravity subscription too, show its levels like other models, and see each subscription next to the pooled view. +- Numbers: autoModel tests 9/9 (3 new routing cases failed before the change, plus a level-slug test). Web typecheck clean in 47 s warm. +- What worked: the Limits page showed Claude and distinct A/B numbers once the hub was quiet. The missing Claude section and copied numbers came from limit probes timing out while the hub was overloaded (load 11, IO pressure ~90). +- Next: one combined web + server build, deployed with a stop/start of t3code.service, then settings switch the Auto tab to the three level rows. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index e7846c214e74..eda559c93c55 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { AUTO_LEVEL_DESCRIPTOR, resolveAutoModelSelection } from "./autoModel.ts"; +import { AUTO_LEVEL_DESCRIPTOR, isAutoModelSlug, resolveAutoModelSelection } from "./autoModel.ts"; const now = Date.parse("2026-11-12T12:00:00.000Z"); const resetsAt = "2026-11-12T15:00:00.000Z"; @@ -58,6 +58,18 @@ function claude(id: string, usedPercent: number, autoAware = true): ServerProvid } as unknown as ServerProvider; } +function withWeekly(provider: ServerProvider, usedPercent: number, weeklyResetsAt: string) { + return { + ...provider, + usageLimits: { + windows: [ + ...(provider.usageLimits?.windows ?? []), + { id: "seven_day", kind: "weekly", label: "Weekly", usedPercent, resetsAt: weeklyResetsAt }, + ], + }, + } as unknown as ServerProvider; +} + const auto = (level?: string): ModelSelection => ({ instanceId: ProviderInstanceId.make("claudeAuto"), model: "auto", @@ -125,6 +137,71 @@ describe("resolveAutoModelSelection", () => { }); }); + it("routes to the account with less of its 5-hour window used", () => { + // A has the busier week but a nearly unused 5-hour window, so it can take work right now. + const providers = [ + withWeekly(claude("claudeAutoB", 50), 20, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 10), 60, "2026-11-18T12:00:00.000Z"), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, + ).toBe("claudeAuto"); + }); + + it("with similar 5-hour use, spends the account whose weekly limit resets first", () => { + // B has slightly less 5-hour use, but A's unused weekly quota is gone tomorrow. + const providers = [ + withWeekly(claude("claudeAutoB", 25), 40, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 30), 40, "2026-11-13T12:00:00.000Z"), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, + ).toBe("claudeAuto"); + }); + + it("falls back to Claude on the Antigravity subscription before other providers", () => { + const antigravity = { + ...claude("antigravity", 0, false), + driver: ProviderDriverKind.make("antigravity"), + models: ["claude-opus-4-6-thinking", "claude-sonnet-4-6"].map((slug) => ({ + slug, + name: slug, + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "thinking_level", + label: "Thinking", + type: "select" as const, + options: ["low", "medium", "high"].map((id) => ({ id, label: id })), + }, + ], + }, + })), + } as unknown as ServerProvider; + const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100), antigravity]; + expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection).toEqual({ + instanceId: "antigravity", + model: "claude-opus-4-6-thinking", + options: [{ id: "thinking_level", value: "medium" }], + }); + }); + + it("reads the level from auto-low / auto-medium / auto-high", () => { + const providers = [claude("claudeAuto", 10)]; + const pick = (model: string) => + resolveAutoModelSelection({ + selection: { instanceId: ProviderInstanceId.make("claudeAuto"), model }, + providers, + now, + })?.selection.model; + expect(pick("auto-high")).toBe("claude-fable-5-2"); + expect(pick("auto-medium")).toBe("claude-opus-5-5"); + expect(pick("auto-low")).toBe("claude-sonnet-5-5"); + expect(isAutoModelSlug("auto-low")).toBe(true); + expect(isAutoModelSlug("auto-max")).toBe(false); + }); + it("returns null when nothing is usable", () => { const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; expect(resolveAutoModelSelection({ selection: auto(), providers, now })).toBeNull(); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 87f997204b42..d76eda593edb 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -38,6 +38,12 @@ const codex = (model: string, effort: string): AutoCandidate => ({ effort, }); const grok = (effort: string): AutoCandidate => ({ driver: "grok", model: "grok-4.7", effort }); +/** Claude models on the Antigravity (Google) subscription: a third Claude pool. */ +const antigravity = (model: string, effort: string): AutoCandidate => ({ + driver: "antigravity", + model, + effort, +}); const opencode = (model: string, effort: string): AutoCandidate => ({ driver: "opencode", model, @@ -52,6 +58,7 @@ const AUTO_CANDIDATES: Readonly>> high: [ claude("claude-fable-5-2", "high"), claude("claude-opus-5-5", "high"), + antigravity("claude-opus-4-6-thinking", "high"), codex("gpt-6.1-sol", "high"), codex("gpt-6-astra", "high"), grok("high"), @@ -60,6 +67,7 @@ const AUTO_CANDIDATES: Readonly>> medium: [ claude("claude-opus-5-5", "medium"), claude("claude-fable-5-2", "medium"), + antigravity("claude-opus-4-6-thinking", "medium"), codex("gpt-6.1-sol", "medium"), codex("gpt-6-astra", "medium"), claude("claude-sonnet-5-5", "medium"), @@ -69,6 +77,7 @@ const AUTO_CANDIDATES: Readonly>> low: [ claude("claude-sonnet-5-5", "low"), claude("claude-haiku-5-5", "low"), + antigravity("claude-sonnet-4-6", "low"), opencode("opencode/big-pickle", "medium"), opencode("opencode/deepseek-v4.1-flash-free", "medium"), codex("gpt-6-luna", "low"), @@ -82,13 +91,26 @@ const EFFORT_OPTION_ID: Readonly> = { codex: "reasoningEffort", grok: "reasoningEffort", opencode: "variant", + antigravity: "thinking_level", }; +/** + * `auto` takes its level from the `effort` option; `auto-low`, `auto-medium` and `auto-high` + * fix it in the slug, so a picker can list one row per level. + */ +export function isAutoModelSlug(slug: string | null | undefined): boolean { + return ( + slug === AUTO_MODEL_SLUG || AUTO_LEVELS.some((level) => slug === `${AUTO_MODEL_SLUG}-${level}`) + ); +} + export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { - return selection?.model === AUTO_MODEL_SLUG; + return isAutoModelSlug(selection?.model); } function autoLevelOf(selection: ModelSelection): AutoLevel { + const fixed = AUTO_LEVELS.find((level) => selection.model === `${AUTO_MODEL_SLUG}-${level}`); + if (fixed) return fixed; const value = selection.options?.find((option) => option.id === "effort")?.value; return AUTO_LEVELS.find((level) => level === value) ?? DEFAULT_LEVEL; } @@ -105,13 +127,45 @@ export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { ], }; +/** Accounts whose 5-hour use differs by less than this many points count as equally free. */ +const SESSION_BAND_PERCENT = 10; + +function sessionUsedPercent(provider: ServerProvider): number { + const windows = (provider.usageLimits?.windows ?? []).filter((w) => w.kind === "session"); + return Math.max(0, ...windows.map((w) => w.usedPercent ?? 0)); +} + +/** When the soonest weekly window resets; unused weekly quota is lost then. */ +function weeklyResetAt(provider: ServerProvider): number { + const resets = (provider.usageLimits?.windows ?? []) + .filter((w) => w.kind === "weekly" && w.resetsAt !== undefined) + .map((w) => Date.parse(w.resetsAt!)) + .filter(Number.isFinite); + return resets.length > 0 ? Math.min(...resets) : Infinity; +} + +/** + * Best instance first: Auto-aware (carries the Auto prompt), then the freer 5-hour window, + * then, between accounts with similar 5-hour use, the one whose weekly quota resets first. + */ +function compareInstances(a: ServerProvider, b: ServerProvider): number { + const aware = Number(isAutoAware(b)) - Number(isAutoAware(a)); + if (aware !== 0) return aware; + const session = sessionUsedPercent(a) - sessionUsedPercent(b); + if (Math.abs(session) >= SESSION_BAND_PERCENT) return session; + const weekly = weeklyResetAt(a) - weeklyResetAt(b); + if (Number.isFinite(weekly) && weekly !== 0) return weekly; + if (weekly === Infinity || weekly === -Infinity) return weekly > 0 ? 1 : -1; + return session || peakUsedPercent(a) - peakUsedPercent(b); +} + function peakUsedPercent(provider: ServerProvider): number { return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); } /** Instances that list the `auto` model carry the Auto-mode prompt, so they win ties. */ function isAutoAware(provider: ServerProvider): boolean { - return provider.models.some((model) => model.slug === AUTO_MODEL_SLUG); + return provider.models.some((model) => isAutoModelSlug(model.slug)); } function usable(provider: ServerProvider, model: string, now: number): boolean { @@ -154,8 +208,8 @@ interface AutoResolution { /** * Keeps the thread's model while it fits this level and is under 90% used (no account hop, no - * lost prompt cache); otherwise the first usable candidate, Auto-aware and least-used instance - * first. Null when nothing is usable. + * lost prompt cache); otherwise the first usable candidate on the best instance (see + * `compareInstances`). Null when nothing is usable. */ export function resolveAutoModelSelection(input: { readonly selection: ModelSelection; @@ -190,11 +244,7 @@ export function resolveAutoModelSelection(input: { usable(provider, candidate.model, input.now), ) // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. - .sort( - (a, b) => - Number(isAutoAware(b)) - Number(isAutoAware(a)) || - peakUsedPercent(a) - peakUsedPercent(b), - ); + .sort(compareInstances); const provider = instances[0]; if (provider) return { selection: toSelection(provider, candidate), level, sticky: false }; } From 32279ac77760445dd56b8a6646cd9d036e89d593 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 14:24:07 +0100 Subject: [PATCH 006/230] Name the chosen Auto level on the model picker button MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The button showed the model Auto routes to ("Auto · Opus 5.5 (A)"), which read as if Auto Medium were Opus. It now shows the level, such as "Auto Medium", and the tooltip names the current route. --- .../components/chat/ProviderModelPicker.tsx | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index ee9195d1b12f..811d1693e0d5 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -186,20 +186,22 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { // Each Auto level row in the list names its own route. const autoRouteFor = (slug: string) => describeAutoRoute({ entries: props.instanceEntries, model: slug, now }); - const triggerTitle = - isAuto && autoRoute - ? `Auto · ${autoRoute.label}` - : selectedModel - ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) - : props.model === ANTIGRAVITY_DEFAULT_MODEL - ? "Choose model" - : props.model || "Choose model"; - const triggerLabel = - isAuto && autoRoute - ? triggerTitle - : selectedModel - ? `${getDisplayModelName(selectedModel)}${selectedModel.isUnavailable ? " (Unavailable)" : ""}` - : triggerTitle; + // The button names the chosen Auto level; the model it routes to now goes in the tooltip. + const autoName = selectedModel ? getDisplayModelName(selectedModel) : "Auto"; + const triggerTitle = isAuto + ? autoName + : selectedModel + ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) + : props.model === ANTIGRAVITY_DEFAULT_MODEL + ? "Choose model" + : props.model || "Choose model"; + const triggerLabel = isAuto + ? autoRoute + ? `${autoName} · now ${autoRoute.label}` + : autoName + : selectedModel + ? `${getDisplayModelName(selectedModel)}${selectedModel.isUnavailable ? " (Unavailable)" : ""}` + : triggerTitle; const showInstanceBadge = activeEntry !== null && shouldShowInstanceBadge(activeEntry, props.instanceEntries); From 7d81674dd73392ab07fbcb237f43dbc6f60b5edc Mon Sep 17 00:00:00 2001 From: radys-s Date: Fri, 13 Nov 2026 14:24:39 +0100 Subject: [PATCH 007/230] docs: tell agents to commit each medium step with its origin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agents batched a whole task into one commit at the end, so history could not show which request or review finding produced which change. AGENTS.md gains a Commits section: commit and push each finished, verified step of medium size or larger, one idea per commit, with a body that states why and where the change came from (issue, PR, review finding, thread link, or the request in one line). Origin: Tomáš asked for more frequent, traceable orchestrator commits. --- AGENTS.md | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/AGENTS.md b/AGENTS.md index 9073e293deba..a3b55dc679aa 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -146,6 +146,14 @@ For mobile verification, a missing or outdated native client is an install step, `evals/` checks how real models behave with T3 Code's model-facing text: agent instructions, MCP tool descriptions and schemas, and generated titles. Before you change that text, read [evals/README.md](evals/README.md) and run the evals it names. When you fix a model behavior bug, add a case that fails before the fix. +## Commits + +- Commit as you go, not once at the end. Each finished, verified step of medium size or larger gets its own commit right away: a bug fix, a feature slice, a refactor, a test suite, a doc update. Fold small edits (a typo, a rename, a review nit) into the step they belong to. +- One commit is one idea. If the title needs "and", split it. Every commit should build and pass the checks for the files it touches, so `git bisect` and `git revert` work on it alone. +- Title: conventional commit, as for PRs. Body: why the change exists, what it changes, and its origin, the issue, PR, review finding, or thread link that asked for it, or the user's request in one line. A reader of `git log` or `git blame` should reach the reason without the chat. +- Commit worker or delegate output only after you review and check it. Push after each commit on a task branch so the work is never only local. +- Never commit to `main` directly. Never rewrite commits that are already pushed unless the developer asks. + ## Pull requests - Never make a PR unless the developer explicitly asks you to do so. From 1a5cfa8693f613004625afc3a090edac08f261bf Mon Sep 17 00:00:00 2001 From: radys-s Date: Fri, 13 Nov 2026 14:49:09 +0100 Subject: [PATCH 008/230] docs: merge PRs with a merge commit to keep per-step history MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A squash merge collapses the per-step commits from the new Commits section into one, which loses the trail back to each step's origin. Agents now merge with `gh pr merge --merge` unless asked to squash. Origin: Tomáš asked for more commits so issues can be traced back. --- AGENTS.md | 1 + 1 file changed, 1 insertion(+) diff --git a/AGENTS.md b/AGENTS.md index a3b55dc679aa..1423944dbb61 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -163,6 +163,7 @@ For mobile verification, a missing or outdated native client is an install step, - UI changes need before/after images. Motion or timing needs a short video. - Upload PR evidence to GitHub. Never commit PR-only screenshots or assets such as `.github/pr-assets/`. - One request is one PR. Split it only when the maintainer asks. Outside contributions follow the stricter [one problem per PR](CONTRIBUTING.md#one-problem) rule. +- Merge with a merge commit (`gh pr merge --merge`) so the per-step commits stay in `main`'s history. Squash only when the maintainer asks. - When babysitting: call `watch_pull_request` and end your turn. T3 Code wakes you on checks, comments, or conflicts. Do not poll or sleep. Verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit. ## Documentation From ddc94f16b7729cb3bada8876bed605efd5dfb0e8 Mon Sep 17 00:00:00 2001 From: radys-s Date: Fri, 13 Nov 2026 14:49:20 +0100 Subject: [PATCH 009/230] docs: remind PR authors to keep one step per commit MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The PR template is what authors see when they open a PR, so it repeats the Commits rule from AGENTS.md in one line: one step per commit, and a body that says why and where the change came from. Origin: Tomáš asked for more commits so issues can be traced back. --- .github/pull_request_template.md | 1 + 1 file changed, 1 insertion(+) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 94157c4135fa..5325e46142f4 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -3,6 +3,7 @@ Read CONTRIBUTING.md before opening a PR. Review capacity is limited, and meetin the requirements does not guarantee review or merging. Solve one underlying problem. The same requirements apply to drafts. Draft status does not defer triage or closure. Use a conventional commit title in plain language, such as "fix(web): new threads no longer spike CPU". +Keep one step per commit, and say in each commit body why it exists and where it came from. --> ## Problem From 14f91c79a0affb18c7204c6988e308936fe144be Mon Sep 17 00:00:00 2001 From: radys-s Date: Fri, 13 Nov 2026 14:49:30 +0100 Subject: [PATCH 010/230] docs: log the commit-cadence change in progress.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Records what changed, why, and the next step, per the fork's rule to log each larger step in docs/progress.md. Origin: Tomáš asked for more commits so issues can be traced back. --- docs/progress.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/progress.md b/docs/progress.md index 1a91af83a5bb..821d5452b229 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -31,3 +31,10 @@ - Numbers: autoModel tests 9/9 (3 new routing cases failed before the change, plus a level-slug test). Web typecheck clean in 47 s warm. - What worked: the Limits page showed Claude and distinct A/B numbers once the hub was quiet. The missing Claude section and copied numbers came from limit probes timing out while the hub was overloaded (load 11, IO pressure ~90). - Next: one combined web + server build, deployed with a stop/start of t3code.service, then settings switch the Auto tab to the three level rows. + +## 2026-11-13: Agents commit each step with its origin + +- What: `AGENTS.md` gets a Commits section. Agents commit and push each finished, checked step of medium size or larger, one idea per commit, with a body that says why and where the change came from (issue, PR, review finding, thread link, or the request). PRs merge with a merge commit so those steps stay in `main`. The PR template repeats the rule in one line. Outside the repo, `~/.agents/T3-CODE.md` and the `auto` and `swarm` skills got the same rule. +- Why: Tomáš wants to trace a problem back to the step and request that caused it. One big commit per task, or a squash merge, hides that. +- Numbers: docs only, 4 commits in PR #4. The fork runs no CI checks on PRs. +- Next: watch whether agents keep the cadence. If they do not, add the rule to the built-in orchestration instructions (`orchestrationInstructions.ts`, needs evals). From 892f0ba5218ba5e904955fed412b5c50e9930057 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 15:34:21 +0100 Subject: [PATCH 011/230] test(shared): build projection test dates with Effect DateTime The shared typecheck rejects new Date() (effect/globalDate), so the pooled-quota projection test from #2 failed it. Found while type-checking the Auto staggering change. --- packages/shared/src/usagePoolProjection.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/usagePoolProjection.test.ts b/packages/shared/src/usagePoolProjection.test.ts index d96745368449..79ccd0905a18 100644 --- a/packages/shared/src/usagePoolProjection.test.ts +++ b/packages/shared/src/usagePoolProjection.test.ts @@ -1,3 +1,4 @@ +import * as DateTime from "effect/DateTime"; import { describe, expect, it } from "vite-plus/test"; import type { LimitPoolWindow } from "./usageLimits.ts"; @@ -5,7 +6,7 @@ import { poolBurn, projectionHorizon, projectPool, recordedPool } from "./usageP const HOUR = 3_600_000; const now = Date.parse("2026-11-12T12:00:00.000Z"); -const iso = (at: number) => new Date(at).toISOString(); +const iso = (at: number) => DateTime.formatIso(DateTime.makeUnsafe(at)); function pool( members: ReadonlyArray<{ key: string; used: number; resetsIn?: number; mins?: number }>, From 2c7a030f1df5eca25a43109913435eca40c2ee3d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 15:34:22 +0100 Subject: [PATCH 012/230] feat(shared): stagger Claude A/B 5-hour windows in Auto routing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auto sent work to the account with less 5-hour use, so both windows started together and ran out together. It now keeps using the account whose window is already running until any of its windows reaches 90%, then moves to the other, so one refreshes while the other works. Within 10 points of 5-hour use, the sooner weekly reset still goes first. Origin: Tomáš asked that Auto pick the plan closer to running out and offset the 5-hour windows so one refreshes while the other is nearly used up. GPT review loop: 2 rounds, approved. --- .../web/src/components/chat/autoRoute.test.ts | 2 +- docs/progress.md | 7 +++ packages/shared/src/autoModel.test.ts | 46 +++++++++++++------ packages/shared/src/autoModel.ts | 19 ++++++-- 4 files changed, 55 insertions(+), 19 deletions(-) diff --git a/apps/web/src/components/chat/autoRoute.test.ts b/apps/web/src/components/chat/autoRoute.test.ts index fae0bdef7887..85ae44be3be8 100644 --- a/apps/web/src/components/chat/autoRoute.test.ts +++ b/apps/web/src/components/chat/autoRoute.test.ts @@ -50,7 +50,7 @@ const claudeModels = [ describe("describeAutoRoute", () => { it("names the Claude model and account Auto would use", () => { const entries = deriveProviderInstanceEntries([ - provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 70), + provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 95), provider("claudeAutoB", "Auto B", "claudeAgent", claudeModels, 10), ]); const medium = describeAutoRoute({ entries, now }); diff --git a/docs/progress.md b/docs/progress.md index 821d5452b229..22b8a6855e87 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -38,3 +38,10 @@ - Why: Tomáš wants to trace a problem back to the step and request that caused it. One big commit per task, or a squash merge, hides that. - Numbers: docs only, 4 commits in PR #4. The fork runs no CI checks on PRs. - Next: watch whether agents keep the cadence. If they do not, add the rule to the built-in orchestration instructions (`orchestrationInstructions.ts`, needs evals). + +## 2026-11-13: Auto staggers Claude A/B 5-hour windows + +- What: Auto now keeps sending work to the account whose 5-hour window is already running, until any of its windows reaches 90%, then moves to the other account. Within 10 points of 5-hour use, the sooner weekly reset wins. Past 90% everywhere, the account with the most left wins. +- Why: preferring the emptier account started both 5-hour windows at the same time, so both ran out together. Staggered windows let one refresh while the other is in use. +- Numbers: 11 routing tests (3 new), a mutation check (dropping the 90% rule fails 3 tests). +- Next: watch real routing on the hub for a day of use. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index eda559c93c55..b52ad8733ed9 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -98,12 +98,8 @@ describe("resolveAutoModelSelection", () => { }); }); - it("picks the Claude account with more room, preferring Auto-aware instances", () => { - const providers = [ - claude("claudeAgent", 0, false), - claude("claudeAuto", 70), - claude("claudeAutoB", 20), - ]; + it("prefers Auto-aware instances", () => { + const providers = [claude("claudeAgent", 0, false), claude("claudeAutoB", 20)]; expect( resolveAutoModelSelection({ selection: auto("medium"), providers, now })?.selection .instanceId, @@ -137,22 +133,46 @@ describe("resolveAutoModelSelection", () => { }); }); - it("routes to the account with less of its 5-hour window used", () => { - // A has the busier week but a nearly unused 5-hour window, so it can take work right now. + it("drains the account whose 5-hour window is already running, so the windows stagger", () => { + // A's window is half spent; B stays untouched and its window starts only when A is nearly + // out, so A refreshes while B is in use. const providers = [ - withWeekly(claude("claudeAutoB", 50), 20, "2026-11-18T12:00:00.000Z"), - withWeekly(claude("claudeAuto", 10), 60, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAutoB", 0), 20, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 50), 20, "2026-11-18T12:00:00.000Z"), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, + ).toBe("claudeAuto"); + }); + + it("switches to the other account once a 5-hour or weekly window is 90% used", () => { + const sessionFull = [claude("claudeAuto", 92), claude("claudeAutoB", 0)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: sessionFull, now })?.selection + .instanceId, + ).toBe("claudeAutoB"); + const weeklyFull = [ + withWeekly(claude("claudeAuto", 50), 95, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAutoB", 0), 20, "2026-11-18T12:00:00.000Z"), ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: weeklyFull, now })?.selection + .instanceId, + ).toBe("claudeAutoB"); + }); + + it("when every account is past 90%, uses the one with the most left", () => { + const providers = [claude("claudeAuto", 92), claude("claudeAutoB", 97)]; expect( resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, ).toBe("claudeAuto"); }); it("with similar 5-hour use, spends the account whose weekly limit resets first", () => { - // B has slightly less 5-hour use, but A's unused weekly quota is gone tomorrow. + // B's window is slightly further along, but A's unused weekly quota is gone tomorrow. const providers = [ - withWeekly(claude("claudeAutoB", 25), 40, "2026-11-18T12:00:00.000Z"), - withWeekly(claude("claudeAuto", 30), 40, "2026-11-13T12:00:00.000Z"), + withWeekly(claude("claudeAutoB", 30), 40, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 25), 40, "2026-11-13T12:00:00.000Z"), ]; expect( resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index d76eda593edb..5d41207539c7 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -17,7 +17,8 @@ const AUTO_MODEL_SLUG = "auto"; const AUTO_LEVELS = ["low", "medium", "high"] as const; type AutoLevel = (typeof AUTO_LEVELS)[number]; const DEFAULT_LEVEL: AutoLevel = "medium"; -/** Above this peak usage, a sticky model gives way when another candidate has more room. */ +/** At this peak usage an account counts as nearly out: a sticky model gives way and routing + * moves to an account with room. */ const STICKY_MAX_USED_PERCENT = 90; interface AutoCandidate { @@ -127,7 +128,7 @@ export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { ], }; -/** Accounts whose 5-hour use differs by less than this many points count as equally free. */ +/** Accounts whose 5-hour use differs by less than this many points count as equally far along. */ const SESSION_BAND_PERCENT = 10; function sessionUsedPercent(provider: ServerProvider): number { @@ -145,13 +146,17 @@ function weeklyResetAt(provider: ServerProvider): number { } /** - * Best instance first: Auto-aware (carries the Auto prompt), then the freer 5-hour window, - * then, between accounts with similar 5-hour use, the one whose weekly quota resets first. + * Best instance first: Auto-aware, then accounts under 90% everywhere. Among those, the further + * along 5-hour window, so windows stagger (one refreshes while the other runs); within 10 + * points, the sooner weekly reset. Past 90% everywhere, the most left. */ function compareInstances(a: ServerProvider, b: ServerProvider): number { const aware = Number(isAutoAware(b)) - Number(isAutoAware(a)); if (aware !== 0) return aware; - const session = sessionUsedPercent(a) - sessionUsedPercent(b); + const room = Number(hasRoom(b)) - Number(hasRoom(a)); + if (room !== 0) return room; + if (!hasRoom(a)) return peakUsedPercent(a) - peakUsedPercent(b); + const session = sessionUsedPercent(b) - sessionUsedPercent(a); if (Math.abs(session) >= SESSION_BAND_PERCENT) return session; const weekly = weeklyResetAt(a) - weeklyResetAt(b); if (Number.isFinite(weekly) && weekly !== 0) return weekly; @@ -159,6 +164,10 @@ function compareInstances(a: ServerProvider, b: ServerProvider): number { return session || peakUsedPercent(a) - peakUsedPercent(b); } +function hasRoom(provider: ServerProvider): boolean { + return peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT; +} + function peakUsedPercent(provider: ServerProvider): number { return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); } From ba5b9d894f802c3488ffb8c18a4ab1011e6bc0fc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 15:38:36 +0100 Subject: [PATCH 013/230] feat(shared): route Auto through every subscription on the hub MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After Claude A/B and Claude on Antigravity A/B, Auto now falls back per level to ChatGPT (Codex), then Grok, then Gemini 3.8 Flash on Antigravity, and at low and medium to the free OpenCode models. ChatGPT now comes before Grok, matching the hub's model ranking (Grok is the slowest on the hard test). Models a provider does not list are skipped, so paid-plan Codex models wait for a plan. Origin: Tomáš asked for full Auto routing by level across the AI subscriptions on the hub (Antigravity, Grok, ChatGPT, and the rest). --- packages/shared/src/autoModel.test.ts | 44 +++++++++++++++++++++++++++ packages/shared/src/autoModel.ts | 16 +++++++--- 2 files changed, 56 insertions(+), 4 deletions(-) diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index b52ad8733ed9..ecd8389c4ba3 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -207,6 +207,50 @@ describe("resolveAutoModelSelection", () => { }); }); + it("after every Claude subscription, uses ChatGPT, then Grok, then Gemini", () => { + const other = (id: string, driver: string, slug: string, optionId: string) => + ({ + ...claude(id, 0, false), + driver: ProviderDriverKind.make(driver), + models: [ + { + slug, + name: slug, + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: optionId, + label: "Effort", + type: "select" as const, + options: ["low", "medium", "high"].map((value) => ({ id: value, label: value })), + }, + ], + }, + }, + ], + usageLimits: undefined, + }) as unknown as ServerProvider; + const claudeOut = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; + const codex = other("codex", "codex", "gpt-6-luna", "reasoningEffort"); + const grok = other("grok", "grok", "grok-4.7", "reasoningEffort"); + const gemini = other("antigravity", "antigravity", "gemini-3.8-flash", "thinking_level"); + const route = (providers: ServerProvider[]) => + resolveAutoModelSelection({ selection: auto("high"), providers, now })?.selection; + + expect(route([...claudeOut, gemini, grok, codex])).toEqual({ + instanceId: "codex", + model: "gpt-6-luna", + options: [{ id: "reasoningEffort", value: "high" }], + }); + expect(route([...claudeOut, gemini, grok])?.instanceId).toBe("grok"); + expect(route([...claudeOut, gemini])).toEqual({ + instanceId: "antigravity", + model: "gemini-3.8-flash", + options: [{ id: "thinking_level", value: "high" }], + }); + }); + it("reads the level from auto-low / auto-medium / auto-high", () => { const providers = [claude("claudeAuto", 10)]; const pick = (model: string) => diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 5d41207539c7..db3e53c713da 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -52,8 +52,9 @@ const opencode = (model: string, effort: string): AutoCandidate => ({ }); /** - * Orchestrator candidates per level, best first. Each level starts on its Claude model and - * steps down through the other subscriptions as limits run out. + * Orchestrator candidates per level, best first: Claude A/B, Claude on Antigravity A/B, ChatGPT + * (Codex), Grok, Gemini, then free OpenCode models. Models a provider does not list are skipped, + * so paid-plan models (Sol, Astra) wait until the plan has them. */ const AUTO_CANDIDATES: Readonly>> = { high: [ @@ -62,8 +63,9 @@ const AUTO_CANDIDATES: Readonly>> antigravity("claude-opus-4-6-thinking", "high"), codex("gpt-6.1-sol", "high"), codex("gpt-6-astra", "high"), - grok("high"), codex("gpt-6-luna", "high"), + grok("high"), + antigravity("gemini-3.8-flash", "high"), ], medium: [ claude("claude-opus-5-5", "medium"), @@ -72,15 +74,21 @@ const AUTO_CANDIDATES: Readonly>> codex("gpt-6.1-sol", "medium"), codex("gpt-6-astra", "medium"), claude("claude-sonnet-5-5", "medium"), - grok("medium"), + antigravity("claude-sonnet-4-6", "medium"), codex("gpt-6-luna", "medium"), + grok("medium"), + antigravity("gemini-3.8-flash", "medium"), + opencode("opencode/big-pickle", "medium"), ], low: [ claude("claude-sonnet-5-5", "low"), claude("claude-haiku-5-5", "low"), antigravity("claude-sonnet-4-6", "low"), + antigravity("gemini-3.8-flash", "low"), opencode("opencode/big-pickle", "medium"), + opencode("opencode/beam-free", "medium"), opencode("opencode/deepseek-v4.1-flash-free", "medium"), + opencode("opencode/glm-5.3-flash-free", "medium"), codex("gpt-6-luna", "low"), grok("low"), ], From 155e1fb0c9f645f798d4ed5b2886ca7eca15dfc9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 16:51:15 +0100 Subject: [PATCH 014/230] feat(server): list Auto levels on every Claude provider MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auto Low, Medium and High existed only as custom models in the hub's settings, so a fork server on another machine (Tomáš's PC) showed no Auto at all. Every Claude provider now lists them as built-in models; a custom model with the same slug still works because built-ins win. Origin: Tomáš asked that Auto work in threads that run only on his own device. --- .../src/provider/ClaudeProvider.test.ts | 21 +++++++++++++++++++ apps/server/src/provider/ClaudeProvider.ts | 9 +++++++- .../src/provider/ProviderRegistry.test.ts | 5 ++++- packages/shared/src/autoModel.ts | 7 +++++++ 4 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 apps/server/src/provider/ClaudeProvider.test.ts diff --git a/apps/server/src/provider/ClaudeProvider.test.ts b/apps/server/src/provider/ClaudeProvider.test.ts new file mode 100644 index 000000000000..998479f85b05 --- /dev/null +++ b/apps/server/src/provider/ClaudeProvider.test.ts @@ -0,0 +1,21 @@ +import { describe, expect, it } from "@effect/vitest"; +import { ClaudeSettings } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { makePendingClaudeProvider } from "./ClaudeProvider.ts"; + +const defaultSettings = Schema.decodeSync(ClaudeSettings)({}); + +describe("makePendingClaudeProvider", () => { + it.effect("lists Auto Low, Medium and High without any custom model settings", () => + Effect.gen(function* () { + const provider = yield* makePendingClaudeProvider(defaultSettings); + expect(provider.models.slice(0, 3).map((model) => [model.slug, model.name])).toEqual([ + ["auto-low", "Auto Low"], + ["auto-medium", "Auto Medium"], + ["auto-high", "Auto High"], + ]); + }), + ); +}); diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.ts index eafd128d610f..a736290744f4 100644 --- a/apps/server/src/provider/ClaudeProvider.ts +++ b/apps/server/src/provider/ClaudeProvider.ts @@ -16,6 +16,7 @@ import * as Ref from "effect/Ref"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { AUTO_LEVEL_MODELS } from "@t3tools/shared/autoModel"; import { createModelCapabilities } from "@t3tools/shared/model"; import { resolveSpawnCommand } from "@t3tools/shared/shell"; import { @@ -75,12 +76,18 @@ const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabili optionDescriptors: [], }); +const AUTO_MODELS: ReadonlyArray = AUTO_LEVEL_MODELS.map((model) => ({ + ...model, + isCustom: false, + capabilities: DEFAULT_CLAUDE_MODEL_CAPABILITIES, +})); + function claudeProviderModels( builtInModels: ReadonlyArray, customModels: ClaudeSettings["customModels"], ): ReadonlyArray { return providerModelsFromSettings( - builtInModels, + [...AUTO_MODELS, ...builtInModels], customModels, DEFAULT_CLAUDE_MODEL_CAPABILITIES, ).map((model) => diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index b5501943ca04..39216b70d3e0 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -41,6 +41,7 @@ import { HttpClient, HttpClientResponse } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { deepMerge } from "@t3tools/shared/Struct"; +import { isAutoModelSlug } from "@t3tools/shared/autoModel"; import { createModelCapabilities } from "@t3tools/shared/model"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; @@ -3598,7 +3599,9 @@ it.layer( }), ); const catalogSlugs = new Set(BUNDLED_CLAUDE_MODEL_CATALOG.models.map((m) => m.model.slug)); - const added = status.models.filter((model) => !catalogSlugs.has(model.slug)); + const added = status.models.filter( + (model) => !catalogSlugs.has(model.slug) && !isAutoModelSlug(model.slug), + ); assert.deepStrictEqual( added.map((model) => [model.slug, model.name, model.isCustom]), diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index db3e53c713da..312468f38d01 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -113,6 +113,13 @@ export function isAutoModelSlug(slug: string | null | undefined): boolean { ); } +/** One picker row per level; every Claude provider lists them, so Auto needs no settings. */ +export const AUTO_LEVEL_MODELS: ReadonlyArray<{ readonly slug: string; readonly name: string }> = + AUTO_LEVELS.map((level) => ({ + slug: `${AUTO_MODEL_SLUG}-${level}`, + name: `Auto ${level[0]!.toUpperCase()}${level.slice(1)}`, + })); + export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { return isAutoModelSlug(selection?.model); } From aa69f7d1f1f2e9a52173f6aa600163255178fedb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 16:51:16 +0100 Subject: [PATCH 015/230] feat(web): pin Auto levels at the top of Favorites MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Favorites live in each server's settings, so a machine without the hub's settings had no Auto pinned. The picker now puts Auto High, Medium and Low from the first Claude instance that lists them at the top of Favorites, until the user stars an Auto level themselves. Origin: Tomáš asked for the Auto levels to be the main pinned models in every thread. --- .../components/chat/ModelPickerContent.tsx | 4 +- .../chat/ProviderModelPicker.logic.test.ts | 41 ++++++++++++++++++- .../chat/ProviderModelPicker.logic.ts | 30 +++++++++++++- docs/progress.md | 7 ++++ 4 files changed, 78 insertions(+), 4 deletions(-) diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index c91ae18874eb..92f8a4a70951 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -40,6 +40,7 @@ import { ComboboxItem, ComboboxListVirtualized, } from "../ui/combobox"; +import { withPinnedAutoLevels } from "./ProviderModelPicker.logic"; import { ModelEsque } from "./providerIconUtils"; import { isAutoModelSlug } from "@t3tools/shared/autoModel"; import type { AutoRoute } from "./autoRoute"; @@ -370,7 +371,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes this picker's mount to global keydown handlers useLayoutEffect(() => registerModelPickerContent(), []); const highlightedModelKeyRef = useRef(null); - const { favorites } = useEnvironmentModelPreferences(props.environmentId); + const { favorites: savedFavorites } = useEnvironmentModelPreferences(props.environmentId); + const favorites = withPinnedAutoLevels(savedFavorites, instanceEntries, modelOptionsByInstance); const activeEntry = props.instanceEntries.find( (entry) => entry.instanceId === props.activeInstanceId, ); diff --git a/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts b/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts index 7602a362d30c..b20481a82750 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts +++ b/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts @@ -1,7 +1,10 @@ -import { ProviderDriverKind } from "@t3tools/contracts"; +import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { retainedModelWhileProviderLocked } from "./ProviderModelPicker.logic"; +import { + retainedModelWhileProviderLocked, + withPinnedAutoLevels, +} from "./ProviderModelPicker.logic"; const claude = ProviderDriverKind.make("claudeAgent"); const opus = { slug: "claude-opus-5-5", name: "Claude Opus 5.5", shortName: "Opus 5.5" }; @@ -18,3 +21,37 @@ describe("retainedModelWhileProviderLocked", () => { expect(retainedModelWhileProviderLocked(null, opus.slug)).toBeUndefined(); }); }); + +describe("withPinnedAutoLevels", () => { + const id = (value: string) => ProviderInstanceId.make(value); + const autoRows = ["auto-low", "auto-medium", "auto-high"].map((slug) => ({ slug })); + const entries = [ + { instanceId: id("codex"), driverKind: ProviderDriverKind.make("codex") }, + { instanceId: id("claudeAgent"), driverKind: claude }, + { instanceId: id("claudeAgent_2"), driverKind: claude }, + ]; + const options = new Map([ + [id("codex"), [{ slug: "gpt-6-luna" }]], + [id("claudeAgent"), [...autoRows, opus]], + [id("claudeAgent_2"), [...autoRows, opus]], + ]); + const saved = [{ provider: id("codex"), model: "gpt-6-luna" }]; + + it("pins the first Claude instance's Auto levels above saved favorites", () => { + expect(withPinnedAutoLevels(saved, entries, options)).toEqual([ + { provider: "claudeAgent", model: "auto-high" }, + { provider: "claudeAgent", model: "auto-medium" }, + { provider: "claudeAgent", model: "auto-low" }, + ...saved, + ]); + }); + + it("keeps the user's own choice once any Auto level is starred", () => { + const own = [{ provider: id("claudeAgent_2"), model: "auto-low" }, ...saved]; + expect(withPinnedAutoLevels(own, entries, options)).toBe(own); + }); + + it("changes nothing when no Claude instance lists the Auto levels", () => { + expect(withPinnedAutoLevels(saved, entries.slice(0, 1), options)).toBe(saved); + }); +}); diff --git a/apps/web/src/components/chat/ProviderModelPicker.logic.ts b/apps/web/src/components/chat/ProviderModelPicker.logic.ts index dd3d6871e7c2..9a581c1ad538 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.logic.ts +++ b/apps/web/src/components/chat/ProviderModelPicker.logic.ts @@ -1,7 +1,10 @@ -import type { ProviderDriverKind } from "@t3tools/contracts"; +import type { ModelFavorite, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; +import { AUTO_LEVEL_MODELS, isAutoModelSlug } from "@t3tools/shared/autoModel"; import type { ModelEsque } from "./providerIconUtils"; +type Favorite = typeof ModelFavorite.Type; + /** Keeps a hidden model visible while its provider is locked or turned off. */ export function retainedModelWhileProviderLocked( entry: { @@ -16,3 +19,28 @@ export function retainedModelWhileProviderLocked( if (entry.driverKind === "opencode" || entry.driverKind === "antigravity") return undefined; return entry.models.find((candidate) => candidate.slug === model) ?? { slug: model, name: model }; } + +/** + * Auto High, Medium and Low lead Favorites on every machine, from the first Claude instance that + * lists them, until the user stars an Auto level themselves. + */ +export function withPinnedAutoLevels( + favorites: ReadonlyArray, + entries: ReadonlyArray<{ + readonly instanceId: ProviderInstanceId; + readonly driverKind: ProviderDriverKind; + }>, + optionsByInstance: ReadonlyMap>, +): ReadonlyArray { + if (favorites.some((favorite) => isAutoModelSlug(favorite.model))) return favorites; + const levels = AUTO_LEVEL_MODELS.map((model) => model.slug).reverse(); + const host = entries.find( + (entry) => + entry.driverKind === "claudeAgent" && + levels.every((slug) => + (optionsByInstance.get(entry.instanceId) ?? []).some((option) => option.slug === slug), + ), + ); + if (!host) return favorites; + return [...levels.map((model) => ({ provider: host.instanceId, model })), ...favorites]; +} diff --git a/docs/progress.md b/docs/progress.md index 22b8a6855e87..a7a0b2a2b48b 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -45,3 +45,10 @@ - Why: preferring the emptier account started both 5-hour windows at the same time, so both ran out together. Staggered windows let one refresh while the other is in use. - Numbers: 11 routing tests (3 new), a mutation check (dropping the 90% rule fails 3 tests). - Next: watch real routing on the hub for a day of use. + +## 2026-11-13: Auto levels on every machine + +- What: every Claude provider on a fork server lists Auto Low, Medium and High as built-in models, so Auto needs no settings. The model picker pins the three levels at the top of Favorites, from the first Claude instance that lists them, until the user stars an Auto level themselves. +- Why: Tomáš wants Auto in every thread, including threads that run on his PC's own T3 server, which has none of the hub's settings. +- Numbers: 1 new server test, 3 new picker tests; server and web typecheck clean (6 min and 62 s on the hub). +- Next: Tomáš builds the fork desktop app on his PC; Auto there routes only to the providers logged in on that PC. From dec10de4a7e8980a5f45e33bf4c4ab5b8f3f51f8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 16:52:46 +0100 Subject: [PATCH 016/230] fix(server): keep a real Claude model first in the model list Several callers default to a provider's first non-custom model (new Claude threads without a saved model, delegate_task without a model). With the Auto levels first, that default became Auto Low. The Auto levels now follow the real models. Origin: found while checking the Auto-levels-everywhere change before review. --- apps/server/src/provider/ClaudeProvider.test.ts | 5 +++-- apps/server/src/provider/ClaudeProvider.ts | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/apps/server/src/provider/ClaudeProvider.test.ts b/apps/server/src/provider/ClaudeProvider.test.ts index 998479f85b05..0acb897d044b 100644 --- a/apps/server/src/provider/ClaudeProvider.test.ts +++ b/apps/server/src/provider/ClaudeProvider.test.ts @@ -8,10 +8,11 @@ import { makePendingClaudeProvider } from "./ClaudeProvider.ts"; const defaultSettings = Schema.decodeSync(ClaudeSettings)({}); describe("makePendingClaudeProvider", () => { - it.effect("lists Auto Low, Medium and High without any custom model settings", () => + it.effect("lists Auto Low, Medium and High after the real models, with no settings", () => Effect.gen(function* () { const provider = yield* makePendingClaudeProvider(defaultSettings); - expect(provider.models.slice(0, 3).map((model) => [model.slug, model.name])).toEqual([ + expect(provider.models[0]?.slug).toMatch(/^claude-/); + expect(provider.models.slice(-3).map((model) => [model.slug, model.name])).toEqual([ ["auto-low", "Auto Low"], ["auto-medium", "Auto Medium"], ["auto-high", "Auto High"], diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.ts index a736290744f4..2031838236b5 100644 --- a/apps/server/src/provider/ClaudeProvider.ts +++ b/apps/server/src/provider/ClaudeProvider.ts @@ -87,7 +87,8 @@ function claudeProviderModels( customModels: ClaudeSettings["customModels"], ): ReadonlyArray { return providerModelsFromSettings( - [...AUTO_MODELS, ...builtInModels], + // After the real models: callers that default to a provider's first model keep a real one. + [...builtInModels, ...AUTO_MODELS], customModels, DEFAULT_CLAUDE_MODEL_CAPABILITIES, ).map((model) => From 7d5c1c2aa83c4ebc349ee566b9c3ed5dff3423a5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 16:56:27 +0100 Subject: [PATCH 017/230] fix(web): keep Auto levels above other favorites The Favorites view sorts by provider order, so a favorite from a provider listed before Claude (Codex, for example) showed above the pinned Auto levels. The view now lists Auto High, Medium and Low first, then the rest as sorted. Origin: GPT review finding S1 on the Auto-levels-everywhere change. --- .../src/components/chat/ModelPickerContent.tsx | 5 +++-- .../chat/ProviderModelPicker.logic.test.ts | 18 ++++++++++++++++++ .../chat/ProviderModelPicker.logic.ts | 7 +++++++ 3 files changed, 28 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index 92f8a4a70951..efd5c9d97e46 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -40,7 +40,7 @@ import { ComboboxItem, ComboboxListVirtualized, } from "../ui/combobox"; -import { withPinnedAutoLevels } from "./ProviderModelPicker.logic"; +import { autoLevelsFirst, withPinnedAutoLevels } from "./ProviderModelPicker.logic"; import { ModelEsque } from "./providerIconUtils"; import { isAutoModelSlug } from "@t3tools/shared/autoModel"; import type { AutoRoute } from "./autoRoute"; @@ -676,11 +676,12 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { result = result.filter((m) => m.instanceId === selectedInstanceId); } - return sortProviderModelItems(result, { + const sorted = sortProviderModelItems(result, { favoriteModelKeys: favoritesSet, groupFavorites: selectedInstanceId !== "favorites", instanceOrder: selectedInstanceId === "favorites" ? instanceOrder : [], }); + return selectedInstanceId === "favorites" ? autoLevelsFirst(sorted) : sorted; })(); const legacySection = (() => { diff --git a/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts b/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts index b20481a82750..988c683990f0 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts +++ b/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts @@ -2,6 +2,7 @@ import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; import { + autoLevelsFirst, retainedModelWhileProviderLocked, withPinnedAutoLevels, } from "./ProviderModelPicker.logic"; @@ -55,3 +56,20 @@ describe("withPinnedAutoLevels", () => { expect(withPinnedAutoLevels(saved, entries.slice(0, 1), options)).toBe(saved); }); }); + +describe("autoLevelsFirst", () => { + it("puts Auto High, Medium and Low ahead of other favorites, keeping the rest in order", () => { + const items = ["gpt-6-luna", "auto-low", "grok-4.7", "auto-high", "auto-medium"].map( + (slug) => ({ + slug, + }), + ); + expect(autoLevelsFirst(items).map((item) => item.slug)).toEqual([ + "auto-high", + "auto-medium", + "auto-low", + "gpt-6-luna", + "grok-4.7", + ]); + }); +}); diff --git a/apps/web/src/components/chat/ProviderModelPicker.logic.ts b/apps/web/src/components/chat/ProviderModelPicker.logic.ts index 9a581c1ad538..f33cbae9e006 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.logic.ts +++ b/apps/web/src/components/chat/ProviderModelPicker.logic.ts @@ -44,3 +44,10 @@ export function withPinnedAutoLevels( if (!host) return favorites; return [...levels.map((model) => ({ provider: host.instanceId, model })), ...favorites]; } + +/** Favorites view order: Auto High, Medium, Low first, then the rest as sorted. */ +export function autoLevelsFirst(items: ReadonlyArray): T[] { + const levels = AUTO_LEVEL_MODELS.map((model) => model.slug).reverse(); + const auto = levels.flatMap((slug) => items.filter((item) => item.slug === slug)); + return [...auto, ...items.filter((item) => !levels.includes(item.slug))]; +} From 1027141a1aed5ede5aba9edfb834e53fd1f6c361 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 14 Nov 2026 11:06:34 +0100 Subject: [PATCH 018/230] fix(shared): count only Auto-prompt instances as Auto-aware MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Routing prefers instances that carry the Auto-mode prompt (the hub's Auto and Auto B). It recognised them by any Auto slug, but since #6 every Claude provider lists auto-low/medium/high, so plain Claude A/B tied with them and a live auto-low run stayed on Claude B. Only the plain auto model, which just the Auto instances define, counts now. Origin: found in the live check Tomáš asked for after #6 (an auto-low task on Claude B ran on Claude B). --- packages/shared/src/autoModel.test.ts | 21 +++++++++++++++++++++ packages/shared/src/autoModel.ts | 7 +++++-- 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index ecd8389c4ba3..135cf6a2a1f4 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -106,6 +106,27 @@ describe("resolveAutoModelSelection", () => { ).toBe("claudeAutoB"); }); + it("prefers the instances that carry the Auto prompt over plain ones listing the levels", () => { + // Every Claude provider lists auto-low/medium/high; only the Auto instances list `auto`. + // The plain instance's 5-hour window is further along, so only the Auto-aware rule picks B. + const plain = { + ...claude("claudeAgent_2", 40, false), + models: [ + ...claude("claudeAgent_2", 40, false).models, + ...["auto-low", "auto-medium", "auto-high"].map((slug) => ({ + slug, + name: slug, + isCustom: false, + capabilities: { optionDescriptors: [] }, + })), + ], + } as unknown as ServerProvider; + const providers = [plain, claude("claudeAutoB", 0)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, + ).toBe("claudeAutoB"); + }); + it("keeps the thread's current model until it passes 90% used", () => { const current = { instanceId: ProviderInstanceId.make("claudeAuto"), model: "claude-opus-5-5" }; const calm = [claude("claudeAuto", 60), claude("claudeAutoB", 5)]; diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 312468f38d01..07a471ddee8e 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -187,9 +187,12 @@ function peakUsedPercent(provider: ServerProvider): number { return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); } -/** Instances that list the `auto` model carry the Auto-mode prompt, so they win ties. */ +/** + * Instances that list the plain `auto` model carry the Auto-mode prompt, so they win ties. Every + * Claude provider lists the level rows, so those do not count. + */ function isAutoAware(provider: ServerProvider): boolean { - return provider.models.some((model) => isAutoModelSlug(model.slug)); + return provider.models.some((model) => model.slug === AUTO_MODEL_SLUG); } function usable(provider: ServerProvider, model: string, now: number): boolean { From aa69ea3fa3a32afee3702765c6d7c035198c0952 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 12 Nov 2026 18:22:12 +0100 Subject: [PATCH 019/230] feat: Auto model routes across subscriptions by level and live usage limits --- .../src/orchestration-v2/Orchestrator.ts | 67 +++++- docs/progress.md | 10 + packages/shared/package.json | 4 + packages/shared/src/autoModel.test.ts | 132 ++++++++++++ packages/shared/src/autoModel.ts | 202 ++++++++++++++++++ 5 files changed, 412 insertions(+), 3 deletions(-) create mode 100644 docs/progress.md create mode 100644 packages/shared/src/autoModel.test.ts create mode 100644 packages/shared/src/autoModel.ts diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 27f7aa82fd25..40ff5ee716e4 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -81,6 +81,8 @@ import { } from "@t3tools/contracts"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { modelSelectionsEqual } from "@t3tools/shared/model"; +import { isAutoModelSelection, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import { modelSwitchSince } from "./modelSwitch.ts"; import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts"; import { combinePullRequestWatchWakes, type PullRequestWatchWake } from "./pullRequestWatch.ts"; @@ -16453,6 +16455,65 @@ export const layer: Layer.Layer< | RuntimePolicyV2 | ServerSettings.ServerSettingsService | ThreadForkServiceV2 -> = Layer.effect(OrchestratorV2, makeOrchestrator()).pipe( - Layer.provide(ThreadCommandExecutor.layer), -); +> = Layer.effect( + OrchestratorV2, + makeOrchestrator().pipe(Effect.flatMap((orchestrator) => withAutoModelRouting(orchestrator))), +).pipe(Layer.provide(ThreadCommandExecutor.layer)); + +/** Commands whose `auto` model keeps the thread's current model while it still fits. */ +const AUTO_STICKY_COMMANDS: ReadonlySet = new Set([ + "message.dispatch", + "thread.model-selection.set", + "provider.switch", +]); + +/** + * Replaces the `auto` model in any command with the concrete model Auto picks from live usage + * limits, so every surface (web, mobile, MCP, scheduled tasks) gets the same routing. + */ +const withAutoModelRouting = Effect.fn("OrchestratorV2.withAutoModelRouting")(function* ( + orchestrator: OrchestratorV2Shape, +) { + // Optional so layers without provider snapshots (tests, CLI tools) still build; there, Auto + // is rejected instead of routed. + const registry = yield* Effect.serviceOption(ProviderRegistry.ProviderRegistry); + const resolve = Effect.fn("OrchestratorV2.resolveAutoModel")(function* ( + command: OrchestrationV2ServerCommand, + ) { + const selection = (command as { readonly modelSelection?: ModelSelection }).modelSelection; + if (!isAutoModelSelection(selection) || selection === undefined) return command; + const threadId = (command as { readonly threadId?: ThreadId }).threadId; + const current = + threadId !== undefined && AUTO_STICKY_COMMANDS.has(command.type) + ? ((yield* orchestrator.getThreadShell(threadId).pipe(Effect.orElseSucceed(() => null))) + ?.modelSelection ?? null) + : null; + const resolution = resolveAutoModelSelection({ + selection, + providers: Option.isSome(registry) ? yield* registry.value.getProviders : [], + now: DateTime.toEpochMillis(yield* DateTime.now), + current, + }); + if (resolution === null) { + return yield* new OrchestratorCommandRejectedError({ + commandId: command.commandId, + commandType: command.type, + cause: new Error( + "Auto found no usable model: every candidate is disabled, signed out, or at its usage limit.", + ), + }); + } + yield* Effect.logInfo("auto model routing", { + commandType: command.type, + level: resolution.level, + sticky: resolution.sticky, + instanceId: resolution.selection.instanceId, + model: resolution.selection.model, + }); + return { ...command, modelSelection: resolution.selection } as OrchestrationV2ServerCommand; + }); + return { + ...orchestrator, + dispatch: (command) => resolve(command).pipe(Effect.flatMap(orchestrator.dispatch)), + } satisfies OrchestratorV2Shape; +}); diff --git a/docs/progress.md b/docs/progress.md new file mode 100644 index 000000000000..dfb3c4eafab5 --- /dev/null +++ b/docs/progress.md @@ -0,0 +1,10 @@ +# Progress (radys-s fork) + +## 2026-11-12: Auto model + +- What: an "Auto" model with its own Low/Medium/High level. Picking it never reaches a provider; the server replaces it in every command (`OrchestratorV2.dispatch`) with a concrete model chosen from live usage limits: Fable (high), Opus (medium) or Sonnet (low) on whichever Claude account has more room, then Codex, Grok and OpenCode when Claude is out. +- Why: Tomáš wanted one Auto entry in the model picker that routes across all his subscriptions, including Claude A vs B. +- How it shows up: a custom model `auto` (with an `effort` select of low/medium/high) on the Auto Claude instances in settings. No web change was needed; the picker already renders custom models and their options. +- Numbers: resolver 5/5 tests; shared and server typecheck clean (server took 22 min on the first, cold run, ~6 min warm). +- Worked: one wrapper around `dispatch` covers web, mobile, MCP and scheduled tasks. Stickiness keeps a thread on its model until it passes 90% used, so threads do not hop accounts on each message. +- Next: after the first message the composer shows the concrete model, not "Auto"; keeping Auto selected mid-thread needs a client change. diff --git a/packages/shared/package.json b/packages/shared/package.json index 3de18958220e..2129f4416a52 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -407,6 +407,10 @@ "types": "./src/usageFormat.ts", "import": "./src/usageFormat.ts" }, + "./autoModel": { + "types": "./src/autoModel.ts", + "import": "./src/autoModel.ts" + }, "./usageLimits": { "types": "./src/usageLimits.ts", "import": "./src/usageLimits.ts" diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts new file mode 100644 index 000000000000..e7846c214e74 --- /dev/null +++ b/packages/shared/src/autoModel.test.ts @@ -0,0 +1,132 @@ +import { + ProviderDriverKind, + ProviderInstanceId, + type ModelSelection, + type ServerProvider, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { AUTO_LEVEL_DESCRIPTOR, resolveAutoModelSelection } from "./autoModel.ts"; + +const now = Date.parse("2026-11-12T12:00:00.000Z"); +const resetsAt = "2026-11-12T15:00:00.000Z"; + +const effortCapabilities = { + optionDescriptors: [ + { + id: "effort", + label: "Effort", + type: "select" as const, + options: ["low", "medium", "high"].map((id) => ({ id, label: id })), + }, + ], +}; + +function claude(id: string, usedPercent: number, autoAware = true): ServerProvider { + return { + instanceId: ProviderInstanceId.make(id), + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-11-12T11:00:00.000Z", + models: [ + ...["claude-fable-5-2", "claude-opus-5-5", "claude-sonnet-5-5"].map((slug) => ({ + slug, + name: slug, + isCustom: false, + capabilities: effortCapabilities, + })), + ...(autoAware + ? [ + { + slug: "auto", + name: "Auto", + isCustom: true, + capabilities: { optionDescriptors: [AUTO_LEVEL_DESCRIPTOR] }, + }, + ] + : []), + ], + slashCommands: [], + skills: [], + usageLimits: { + windows: [{ id: "five_hour", kind: "session", label: "Session", usedPercent, resetsAt }], + }, + } as unknown as ServerProvider; +} + +const auto = (level?: string): ModelSelection => ({ + instanceId: ProviderInstanceId.make("claudeAuto"), + model: "auto", + ...(level ? { options: [{ id: "effort", value: level }] } : {}), +}); + +describe("resolveAutoModelSelection", () => { + it("maps each level to its orchestrator model and effort, medium by default", () => { + const providers = [claude("claudeAuto", 10)]; + expect( + resolveAutoModelSelection({ selection: auto("high"), providers, now })?.selection, + ).toEqual({ + instanceId: "claudeAuto", + model: "claude-fable-5-2", + options: [{ id: "effort", value: "high" }], + }); + expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.model).toBe( + "claude-opus-5-5", + ); + expect( + resolveAutoModelSelection({ selection: auto("low"), providers, now })?.selection, + ).toEqual({ + instanceId: "claudeAuto", + model: "claude-sonnet-5-5", + options: [{ id: "effort", value: "low" }], + }); + }); + + it("picks the Claude account with more room, preferring Auto-aware instances", () => { + const providers = [ + claude("claudeAgent", 0, false), + claude("claudeAuto", 70), + claude("claudeAutoB", 20), + ]; + expect( + resolveAutoModelSelection({ selection: auto("medium"), providers, now })?.selection + .instanceId, + ).toBe("claudeAutoB"); + }); + + it("keeps the thread's current model until it passes 90% used", () => { + const current = { instanceId: ProviderInstanceId.make("claudeAuto"), model: "claude-opus-5-5" }; + const calm = [claude("claudeAuto", 60), claude("claudeAutoB", 5)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: calm, now, current }), + ).toMatchObject({ sticky: true, selection: { instanceId: "claudeAuto" } }); + + const busy = [claude("claudeAuto", 95), claude("claudeAutoB", 5)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: busy, now, current }), + ).toMatchObject({ sticky: false, selection: { instanceId: "claudeAutoB" } }); + }); + + it("steps down to other subscriptions when both Claude accounts are exhausted", () => { + const grok = { + ...claude("grok", 0, false), + driver: ProviderDriverKind.make("grok"), + models: [{ slug: "grok-4.7", name: "Grok 4.7", isCustom: false, capabilities: null }], + usageLimits: undefined, + } as unknown as ServerProvider; + const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100), grok]; + expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection).toEqual({ + instanceId: "grok", + model: "grok-4.7", + }); + }); + + it("returns null when nothing is usable", () => { + const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; + expect(resolveAutoModelSelection({ selection: auto(), providers, now })).toBeNull(); + }); +}); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts new file mode 100644 index 000000000000..87f997204b42 --- /dev/null +++ b/packages/shared/src/autoModel.ts @@ -0,0 +1,202 @@ +import { + isProviderAvailable, + type ModelSelection, + type ProviderDriverKind, + type ProviderOptionDescriptor, + type ServerProvider, +} from "@t3tools/contracts"; + +import { exhaustedUsageWindow } from "./usageLimits.ts"; + +/** + * "Auto" is a custom model (slug `auto`) on any provider instance. Picking it never reaches + * a provider: the server replaces it with a concrete model chosen here, from the providers' + * live usage limits. The level (`low` | `medium` | `high`) rides in the `effort` option. + */ +const AUTO_MODEL_SLUG = "auto"; +const AUTO_LEVELS = ["low", "medium", "high"] as const; +type AutoLevel = (typeof AUTO_LEVELS)[number]; +const DEFAULT_LEVEL: AutoLevel = "medium"; +/** Above this peak usage, a sticky model gives way when another candidate has more room. */ +const STICKY_MAX_USED_PERCENT = 90; + +interface AutoCandidate { + readonly driver: string; + readonly model: string; + /** The candidate's own reasoning effort for this level. */ + readonly effort: string; +} + +const claude = (model: string, effort: string): AutoCandidate => ({ + driver: "claudeAgent", + model, + effort, +}); +const codex = (model: string, effort: string): AutoCandidate => ({ + driver: "codex", + model, + effort, +}); +const grok = (effort: string): AutoCandidate => ({ driver: "grok", model: "grok-4.7", effort }); +const opencode = (model: string, effort: string): AutoCandidate => ({ + driver: "opencode", + model, + effort, +}); + +/** + * Orchestrator candidates per level, best first. Each level starts on its Claude model and + * steps down through the other subscriptions as limits run out. + */ +const AUTO_CANDIDATES: Readonly>> = { + high: [ + claude("claude-fable-5-2", "high"), + claude("claude-opus-5-5", "high"), + codex("gpt-6.1-sol", "high"), + codex("gpt-6-astra", "high"), + grok("high"), + codex("gpt-6-luna", "high"), + ], + medium: [ + claude("claude-opus-5-5", "medium"), + claude("claude-fable-5-2", "medium"), + codex("gpt-6.1-sol", "medium"), + codex("gpt-6-astra", "medium"), + claude("claude-sonnet-5-5", "medium"), + grok("medium"), + codex("gpt-6-luna", "medium"), + ], + low: [ + claude("claude-sonnet-5-5", "low"), + claude("claude-haiku-5-5", "low"), + opencode("opencode/big-pickle", "medium"), + opencode("opencode/deepseek-v4.1-flash-free", "medium"), + codex("gpt-6-luna", "low"), + grok("low"), + ], +}; + +/** The option each driver uses for reasoning effort. */ +const EFFORT_OPTION_ID: Readonly> = { + claudeAgent: "effort", + codex: "reasoningEffort", + grok: "reasoningEffort", + opencode: "variant", +}; + +export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { + return selection?.model === AUTO_MODEL_SLUG; +} + +function autoLevelOf(selection: ModelSelection): AutoLevel { + const value = selection.options?.find((option) => option.id === "effort")?.value; + return AUTO_LEVELS.find((level) => level === value) ?? DEFAULT_LEVEL; +} + +/** The `effort` descriptor an `auto` custom model declares, so pickers show Low/Medium/High. */ +export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { + id: "effort", + label: "Auto level", + type: "select", + options: [ + { id: "low", label: "Low", description: "Sonnet orchestrates; cheaper models do more" }, + { id: "medium", label: "Medium", description: "Opus orchestrates", isDefault: true }, + { id: "high", label: "High", description: "Fable orchestrates" }, + ], +}; + +function peakUsedPercent(provider: ServerProvider): number { + return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); +} + +/** Instances that list the `auto` model carry the Auto-mode prompt, so they win ties. */ +function isAutoAware(provider: ServerProvider): boolean { + return provider.models.some((model) => model.slug === AUTO_MODEL_SLUG); +} + +function usable(provider: ServerProvider, model: string, now: number): boolean { + return ( + provider.enabled && + provider.installed && + provider.auth.status !== "unauthenticated" && + isProviderAvailable(provider) && + provider.models.some((entry) => entry.slug === model) && + exhaustedUsageWindow(provider, now, model) === undefined + ); +} + +function effortOptions(provider: ServerProvider, candidate: AutoCandidate) { + const id = EFFORT_OPTION_ID[candidate.driver]; + const descriptor = provider.models + .find((entry) => entry.slug === candidate.model) + ?.capabilities?.optionDescriptors?.find((entry) => entry.id === id); + if (!id || descriptor?.type !== "select") return undefined; + return descriptor.options.some((choice) => choice.id === candidate.effort) + ? [{ id, value: candidate.effort }] + : undefined; +} + +function toSelection(provider: ServerProvider, candidate: AutoCandidate): ModelSelection { + const options = effortOptions(provider, candidate); + return { + instanceId: provider.instanceId, + model: candidate.model, + ...(options ? { options } : {}), + }; +} + +interface AutoResolution { + readonly selection: ModelSelection; + readonly level: AutoLevel; + /** True when the thread's current model was kept. */ + readonly sticky: boolean; +} + +/** + * Keeps the thread's model while it fits this level and is under 90% used (no account hop, no + * lost prompt cache); otherwise the first usable candidate, Auto-aware and least-used instance + * first. Null when nothing is usable. + */ +export function resolveAutoModelSelection(input: { + readonly selection: ModelSelection; + readonly providers: ReadonlyArray; + readonly now: number; + readonly current?: ModelSelection | null; +}): AutoResolution | null { + const level = autoLevelOf(input.selection); + const candidates = AUTO_CANDIDATES[level]; + + const current = input.current; + if (current && !isAutoModelSelection(current)) { + const provider = input.providers.find((entry) => entry.instanceId === current.instanceId); + const candidate = candidates.find( + (entry) => entry.driver === provider?.driver && entry.model === current.model, + ); + if ( + provider && + candidate && + usable(provider, candidate.model, input.now) && + peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT + ) { + return { selection: toSelection(provider, candidate), level, sticky: true }; + } + } + + for (const candidate of candidates) { + const instances = input.providers + .filter( + (provider) => + provider.driver === (candidate.driver as ProviderDriverKind) && + usable(provider, candidate.model, input.now), + ) + // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. + .sort( + (a, b) => + Number(isAutoAware(b)) - Number(isAutoAware(a)) || + peakUsedPercent(a) - peakUsedPercent(b), + ); + const provider = instances[0]; + if (provider) return { selection: toSelection(provider, candidate), level, sticky: false }; + } + return null; +} From 42d711f2823f062a7844ddf8adb25e5d3e073812 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 09:45:23 +0100 Subject: [PATCH 020/230] Give the Auto model its own icon in the model picker --- apps/web/src/components/chat/ModelListRow.tsx | 1 + apps/web/src/components/chat/ProviderInstanceIcon.tsx | 9 +++++++-- apps/web/src/components/chat/ProviderModelPicker.tsx | 2 ++ docs/progress.md | 8 ++++++++ 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/ModelListRow.tsx b/apps/web/src/components/chat/ModelListRow.tsx index 69da770f1f84..512364b5e875 100644 --- a/apps/web/src/components/chat/ModelListRow.tsx +++ b/apps/web/src/components/chat/ModelListRow.tsx @@ -57,6 +57,7 @@ export const ModelListRow = memo(function ModelListRow(props: { - {isAcpRegistry ? ( + {props.modelSlug === "auto" ? ( + + ) : isAcpRegistry ? ( )} - {isCustomEndpoint ? null : props.showBadge ? ( + {isCustomEndpoint || props.modelSlug === "auto" ? null : props.showBadge ? ( Date: Thu, 12 Nov 2026 17:51:46 +0100 Subject: [PATCH 021/230] feat(web): pooled quota view with burn projection on Usage limits Every account of a provider adds into one pool (two Claude accounts = 200%). Each limits card now shows the summed headline, when the pool and the first account run out, the next reset, the burn rate, and a recorded and projected chart. Readings are kept in this browser to draw history and measure burn. --- .../usage/UsageLimitsPooled.browser.test.tsx | 52 ++++ .../components/usage/UsageLimitsPooled.tsx | 122 +++++++-- .../src/components/usage/UsagePoolChart.tsx | 250 ++++++++++++++++++ .../src/components/usage/usagePoolHistory.ts | 64 +++++ packages/shared/package.json | 4 + .../shared/src/usagePoolProjection.test.ts | 144 ++++++++++ packages/shared/src/usagePoolProjection.ts | 179 +++++++++++++ 7 files changed, 793 insertions(+), 22 deletions(-) create mode 100644 apps/web/src/components/usage/UsagePoolChart.tsx create mode 100644 apps/web/src/components/usage/usagePoolHistory.ts create mode 100644 packages/shared/src/usagePoolProjection.test.ts create mode 100644 packages/shared/src/usagePoolProjection.ts diff --git a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx index ab114fbbd6f2..dc806b1341b2 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx @@ -63,3 +63,55 @@ describe("UsageLimitsPooled ChatGPT usage card", () => { .toBeVisible(); }); }); + +function claude(instanceId: string, displayName: string, weeklyUsed: number, resetsAt: string) { + return { + ...managedChatGpt(instanceId, displayName), + driver: ProviderDriverKind.make("claudeAgent"), + usageLimits: { + checkedAt, + windows: [ + { + id: "seven_day", + kind: "weekly" as const, + label: "Weekly", + usedPercent: weeklyUsed, + resetsAt, + windowDurationMins: 7 * 24 * 60, + }, + ], + }, + } satisfies ServerProvider; +} + +describe("UsageLimitsPooled pooled quota", () => { + it("adds the accounts into one pool and projects when it runs out", async () => { + const presentations = new Map([ + [ + EnvironmentId.make("desk"), + { + entry: { target: { label: "Desk" } }, + serverConfig: { + providers: [ + claude("claude_a", "Auto", 68, "2026-10-27T12:00:00.000Z"), + claude("claude_b", "Auto B", 27, "2026-10-31T13:00:00.000Z"), + ], + }, + }, + ], + ]); + await using screen = await render( + , + ); + + await expect.element(screen.getByText("105%", { exact: true })).toBeVisible(); + await expect.element(screen.getByText("of 200%")).toBeVisible(); + await expect.element(screen.getByText("Pool empty")).toBeVisible(); + await expect.element(screen.getByText("Burn, window avg")).toBeVisible(); + await expect + .element( + screen.getByRole("img", { name: "Weekly: pooled quota left, recorded and projected" }), + ) + .toBeVisible(); + }); +}); diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index 8ec1c7a02afc..50acedba3fe0 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -6,6 +6,7 @@ import { collectLimitPools, cursorUsageWindowDetails, displayLimitWindows, + formatDuration, formatResetsIn, type LimitAccount, type LimitPool, @@ -16,6 +17,12 @@ import { type ResetCreditChoice, resetCreditChoices, } from "@t3tools/shared/usageLimits"; +import { + poolBurn, + projectionHorizon, + projectPool, + recordedPool, +} from "@t3tools/shared/usagePoolProjection"; import type { Popover as PopoverPrimitive } from "@base-ui/react/popover"; import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; import { AlertTriangleIcon, ExternalLinkIcon, TicketIcon } from "lucide-react"; @@ -25,6 +32,7 @@ import { type ReactNode, type RefObject, use, + useEffect, useLayoutEffect, useRef, useState, @@ -42,6 +50,10 @@ import { OpenAI } from "../Icons"; import { Alert, AlertTitle } from "../ui/alert"; import { Popover, PopoverCreateHandle, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { PaceIcon, ResetCreditDialog, barColor, usePaceMark, useResetCredit } from "./UsageLimits"; +import { UsagePoolChart } from "./UsagePoolChart"; +import { poolHistoryKey, readPoolHistory, recordPoolReadings } from "./usagePoolHistory"; + +const BURN_LOOKBACK_MS = 3 * 3_600_000; function accountInitials(email: string): string { const [local = "", domain = ""] = email.split("@"); @@ -542,45 +554,104 @@ function PoolBar({ ); } +function PoolStat({ label, children }: { readonly label: string; readonly children: ReactNode }) { + return ( +
+ {label} + {children} +
+ ); +} + function PoolWindowCard({ pool, + historyKey, color, now, label, description, }: { readonly pool: LimitPoolWindow; + readonly historyKey: string; readonly color: string; readonly now: number; readonly label?: string | null | undefined; readonly description?: string | undefined; }) { - const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0); + const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat); + const samples = readPoolHistory(historyKey); + const horizon = projectionHorizon(pool); + const burn = poolBurn(pool, samples, now, BURN_LOOKBACK_MS); + const projection = projectPool(pool, now, { burnPerHour: burn.perHour, horizonMs: horizon }); + const from = now - horizon * 0.3; + const formatTime = (at: number) => + formatUpcomingTimestamp(new Date(at).toISOString(), timestampFormat, now); + const nextRefill = projection.refills[0]; + const firstEmpty = projection.firstEmpty + ? pool.members.find((member) => member.account.key === projection.firstEmpty?.accountKey) + : undefined; + const burnText = `${burn.perHour >= 10 ? Math.round(burn.perHour) : burn.perHour.toFixed(1)}%/h`; return ( -
-
- {label !== null ? ( - {label ?? pool.label} - ) : null} - - - {pool.remainingPercent}% - - - left - {pool.pace ? : null} - - - {nextRefill && pool.columns.length > 1 ? ( - - ↻ +{nextRefill.restoresPercent}% +
+
+
+ {label !== null ? ( + {label ?? pool.label} + ) : null} + + + {Math.round(projection.remaining)}% + + + of {projection.capacity}% + {pool.pace ? : null} + - ) : null} +
+
+ + {projection.poolEmpty === null + ? `Not by ${new Date(now + horizon).toLocaleDateString([], { month: "short", day: "numeric" })}` + : projection.poolEmpty <= now + ? "Empty now" + : formatTime(projection.poolEmpty)} + + + {firstEmpty && projection.firstEmpty ? ( + + {pool.members.length > 1 ? ( + + ) : null} + + {projection.firstEmpty.at <= now + ? "now" + : `in ${formatDuration(projection.firstEmpty.at - now)}`} + + + ) : ( + "None" + )} + + + {nextRefill ? `+${Math.round(nextRefill.restores)}% ${formatTime(nextRefill.at)}` : "–"} + + + {burnText} + +
+ - {description ? ( -

{description}

- ) : null} + {description ?

{description}

: null}
); } @@ -608,6 +679,7 @@ function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: nu PopoverCreateHandle()); const segmentPopoverActions = useRef(null); const pools = collectLimitPools(collectLimitAccounts(presentations), now); + // Readings are stamped with each provider's checkedAt, so re-renders of the same data store + // nothing new. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps this browser's localStorage reading history in step with the limits it has been shown + useEffect(() => { + recordPoolReadings(pools, now); + }, [pools, now]); const notices = collectLimitNotices(presentations); const externalLinks = collectExternalUsageLinks(presentations); return ( diff --git a/apps/web/src/components/usage/UsagePoolChart.tsx b/apps/web/src/components/usage/UsagePoolChart.tsx new file mode 100644 index 000000000000..fe5c7de1a6b4 --- /dev/null +++ b/apps/web/src/components/usage/UsagePoolChart.tsx @@ -0,0 +1,250 @@ +import type { PoolProjection } from "@t3tools/shared/usagePoolProjection"; +import { useId, useLayoutEffect, useRef, useState } from "react"; + +import { observeResize } from "../../lib/observeResize"; + +const HEIGHT = 190; +const PAD = { left: 44, right: 8, top: 22, bottom: 22 }; +const DAY = 86_400_000; +const HOUR = 3_600_000; + +type Point = { readonly at: number; readonly remaining: number }; + +function percent(value: number) { + return `${Math.round(value)}%`; +} + +function timeTicks(from: number, to: number): ReadonlyArray<{ at: number; label: string }> { + const span = to - from; + if (span > 2 * DAY) { + const every = Math.max(1, Math.ceil(span / DAY / 10)); + const start = new Date(from); + start.setHours(24, 0, 0, 0); + const ticks = []; + for (let at = start.getTime(); at < to; at += every * DAY) { + ticks.push({ + at: at + DAY / 2, + label: new Date(at).toLocaleDateString([], { weekday: "short", day: "numeric" }), + }); + } + return ticks; + } + const start = new Date(from); + start.setMinutes(60, 0, 0); + while (start.getHours() % 3 !== 0) start.setHours(start.getHours() + 1); + const ticks = []; + for (let at = start.getTime(); at < to; at += 3 * HOUR) { + ticks.push({ + at, + label: new Date(at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }), + }); + } + return ticks; +} + +/** Drops a label that would overlap the one before it. */ +function spacedLabels(labels: readonly T[]): T[] { + const shown: T[] = []; + for (const label of labels) { + if (label.x - (shown.at(-1)?.x ?? -Infinity) >= 34) shown.push(label); + } + return shown; +} + +/** Pooled remaining quota: readings so far as a solid line, the projection dashed. */ +export function UsagePoolChart({ + color, + label, + recorded, + projection, + from, + to, + now, + formatTime, +}: { + readonly color: string; + readonly label: string; + readonly recorded: readonly Point[]; + readonly projection: PoolProjection; + readonly from: number; + readonly to: number; + readonly now: number; + readonly formatTime: (at: number) => string; +}) { + const box = useRef(null); + const [width, setWidth] = useState(0); + const [hover, setHover] = useState(null); + const gradient = useId(); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the container DOM width before paint and remeasures through a ResizeObserver + useLayoutEffect(() => { + const element = box.current; + if (!element) return; + const measure = () => setWidth(element.getBoundingClientRect().width); + measure(); + return observeResize(element, measure); + }, []); + + const cap = Math.max(100, projection.capacity); + const x = (at: number) => + PAD.left + ((at - from) / (to - from)) * Math.max(0, width - PAD.left - PAD.right); + const y = (value: number) => PAD.top + (HEIGHT - PAD.top - PAD.bottom) * (1 - value / cap); + const line = (points: readonly Point[]) => + points + .map((p, i) => `${i === 0 ? "M" : "L"}${x(p.at).toFixed(1)},${y(p.remaining).toFixed(1)}`) + .join(""); + const all = [...recorded, ...projection.points]; + const first = all[0]; + const last = all.at(-1); + const area = first && last ? `${line(all)}L${x(last.at)},${y(0)}L${x(first.at)},${y(0)}Z` : ""; + const start = projection.points[0]; + + const refillLabels = spacedLabels( + projection.refills.map((refill) => ({ ...refill, x: x(refill.at) })), + ); + + const pick = (clientX: number) => { + const rect = box.current?.getBoundingClientRect(); + if (!rect || all.length === 0) return; + const at = + from + ((clientX - rect.left - PAD.left) / (width - PAD.left - PAD.right)) * (to - from); + setHover( + all.reduce((best, p) => (Math.abs(p.at - at) < Math.abs(best.at - at) ? p : best), all[0]!), + ); + }; + + return ( +
+ {width > 0 ? ( + pick(event.clientX)} + onPointerLeave={() => setHover(null)} + > + + + + + + + {[0, cap / 2, cap].map((value) => ( + + + + {percent(value)} + + + ))} + {timeTicks(from, to).map((tick) => ( + + {tick.label} + + ))} + + {recorded.length > 0 && start ? ( + + ) : null} + + {refillLabels.map((refill) => ( + + +{percent(refill.restores)} + + ))} + + + Now + + {start ? ( + + ) : null} + {projection.poolEmpty !== null && projection.poolEmpty > now ? ( + + + + Empty {formatTime(projection.poolEmpty)} + + + ) : null} + {hover ? : null} + + ) : null} + {hover ? ( +
+
+ {formatTime(hover.at)} + {hover.at > now ? " · projected" : ""} +
+
+ {percent(hover.remaining)} of {percent(projection.capacity)} +
+
+ ) : null} +
+ ); +} diff --git a/apps/web/src/components/usage/usagePoolHistory.ts b/apps/web/src/components/usage/usagePoolHistory.ts new file mode 100644 index 000000000000..3780d4e6af53 --- /dev/null +++ b/apps/web/src/components/usage/usagePoolHistory.ts @@ -0,0 +1,64 @@ +import type { LimitPool, LimitPoolWindow } from "@t3tools/shared/usageLimits"; +import type { PoolSample } from "@t3tools/shared/usagePoolProjection"; +import * as Schema from "effect/Schema"; + +import { getLocalStorageItem, setLocalStorageItem } from "../../hooks/useLocalStorage"; + +// Providers report limits only as a current percentage, so this browser keeps the readings it +// has seen to draw the recorded line and measure burn. +const STORAGE_KEY = "t3code:usage-pool-history:v1"; +const KEEP_MS = 14 * 24 * 3_600_000; +const MIN_GAP_MS = 4 * 60_000; + +const Sample = Schema.Struct({ + at: Schema.Number, + used: Schema.Record(Schema.String, Schema.Number), +}); +const History = Schema.Record(Schema.String, Schema.Array(Sample)); +type History = typeof History.Type; + +export function poolHistoryKey(pool: LimitPool, window: LimitPoolWindow): string { + return `${pool.driver}:${window.kind}:${window.id}`; +} + +function read(): History { + try { + return getLocalStorageItem(STORAGE_KEY, History) ?? {}; + } catch { + return {}; + } +} + +export function readPoolHistory(key: string): readonly PoolSample[] { + return read()[key] ?? []; +} + +/** Stores one reading per window, stamped with when the provider was checked. */ +export function recordPoolReadings(pools: readonly LimitPool[], now: number): void { + const history: Record = { ...read() }; + let changed = false; + for (const pool of pools) { + for (const window of pool.windows) { + const checked = window.members + .map((member) => Date.parse(member.account.limits.checkedAt)) + .filter(Number.isFinite); + if (checked.length === 0) continue; + const at = Math.min(now, Math.max(...checked)); + const key = poolHistoryKey(pool, window); + const samples = (history[key] ?? []).filter((sample) => sample.at >= now - KEEP_MS); + const last = samples.at(-1); + if (last && at - last.at < MIN_GAP_MS) continue; + const used = Object.fromEntries( + window.members.map((member) => [member.account.key, member.window.usedPercent]), + ); + history[key] = [...samples, { at, used }]; + changed = true; + } + } + if (!changed) return; + try { + setLocalStorageItem(STORAGE_KEY, history, History); + } catch (error) { + console.error("Could not save usage limit readings.", error); + } +} diff --git a/packages/shared/package.json b/packages/shared/package.json index 2129f4416a52..ef7b63036391 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -415,6 +415,10 @@ "types": "./src/usageLimits.ts", "import": "./src/usageLimits.ts" }, + "./usagePoolProjection": { + "types": "./src/usagePoolProjection.ts", + "import": "./src/usagePoolProjection.ts" + }, "./desktopAppControl": { "types": "./src/desktopAppControl.ts", "import": "./src/desktopAppControl.ts" diff --git a/packages/shared/src/usagePoolProjection.test.ts b/packages/shared/src/usagePoolProjection.test.ts new file mode 100644 index 000000000000..79ccd0905a18 --- /dev/null +++ b/packages/shared/src/usagePoolProjection.test.ts @@ -0,0 +1,144 @@ +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; + +import type { LimitPoolWindow } from "./usageLimits.ts"; +import { poolBurn, projectionHorizon, projectPool, recordedPool } from "./usagePoolProjection.ts"; + +const HOUR = 3_600_000; +const now = Date.parse("2026-11-12T12:00:00.000Z"); +const iso = (at: number) => DateTime.formatIso(DateTime.makeUnsafe(at)); + +function pool( + members: ReadonlyArray<{ key: string; used: number; resetsIn?: number; mins?: number }>, + kind: LimitPoolWindow["kind"] = "weekly", +): LimitPoolWindow { + const list = members.map((m) => ({ + account: { key: m.key } as LimitPoolWindow["members"][number]["account"], + window: { + id: "seven_day", + kind, + label: "Weekly", + usedPercent: m.used, + ...(m.resetsIn === undefined ? {} : { resetsAt: iso(now + m.resetsIn) }), + windowDurationMins: m.mins ?? 7 * 24 * 60, + }, + refillPercent: m.used, + })); + return { + id: "seven_day", + kind, + label: "Weekly", + members: list, + columns: list, + remainingPercent: 0, + usedPercent: 0, + pace: null, + resets: [], + }; +} + +describe("projectPool", () => { + it("sums every account into one pool", () => { + const projection = projectPool( + pool([ + { key: "a", used: 60, resetsIn: 48 * HOUR }, + { key: "b", used: 30, resetsIn: 120 * HOUR }, + ]), + now, + { burnPerHour: 0, horizonMs: 7 * 24 * HOUR }, + ); + expect(projection.capacity).toBe(200); + expect(projection.remaining).toBe(110); + expect(projection.poolEmpty).toBeNull(); + // With no spend, each reset gives back what that account had used. + expect(projection.refills.map((r) => [r.accountKey, r.restores, r.remainingAfter])).toEqual([ + ["a", 60, 170], + ["b", 30, 200], + ]); + expect(projection.points.at(-1)?.remaining).toBe(200); + }); + + it("spends the account that resets first and finds when the pool runs dry", () => { + const projection = projectPool( + pool([ + { key: "late", used: 0, resetsIn: 150 * HOUR }, + { key: "soon", used: 50, resetsIn: 140 * HOUR }, + ]), + now, + { burnPerHour: 10, horizonMs: 24 * HOUR, steps: 240 }, + ); + // 50 points left on "soon" at 10/h: empty after 5 h; then 100 on "late": pool dry at 15 h. + expect(projection.firstEmpty).toEqual({ at: now + 5 * HOUR, accountKey: "soon" }); + expect(projection.poolEmpty).toBe(now + 15 * HOUR); + }); + + it("reports an exhausted account as empty now", () => { + const projection = projectPool( + pool([ + { key: "a", used: 100, resetsIn: HOUR }, + { key: "b", used: 0, resetsIn: 5 * HOUR }, + ]), + now, + { burnPerHour: 0, horizonMs: 24 * HOUR }, + ); + expect(projection.firstEmpty).toEqual({ at: now, accountKey: "a" }); + expect(projection.poolEmpty).toBeNull(); + }); +}); + +describe("poolBurn", () => { + const twoAccounts = pool([ + { key: "a", used: 35, resetsIn: 100 * HOUR }, + { key: "b", used: 5, resetsIn: 100 * HOUR }, + ]); + + it("measures spend from stored readings and counts a drop as a reset", () => { + const burn = poolBurn( + twoAccounts, + [ + { at: now - 2 * HOUR, used: { a: 10, b: 90 } }, + { at: now - HOUR, used: { a: 20, b: 100 } }, + { at: now, used: { a: 35, b: 5 } }, + ], + now, + 3 * HOUR, + ); + // a: +10 +15, b: +10 then a reset worth 5 → 40 points over 2 h. + expect(burn).toEqual({ perHour: 20, source: "measured" }); + }); + + it("falls back to the average since each window opened", () => { + // Weekly windows with 100 h left have run 68 h: 35/68 + 5/68 points per hour. + const burn = poolBurn(twoAccounts, [{ at: now, used: { a: 35, b: 5 } }], now, 3 * HOUR); + expect(burn.source).toBe("window"); + expect(burn.perHour).toBeCloseTo(40 / 68, 6); + }); +}); + +describe("recordedPool", () => { + it("carries an account's last reading forward", () => { + const series = recordedPool( + pool([ + { key: "a", used: 0 }, + { key: "b", used: 0 }, + ]), + [ + { at: now - 3 * HOUR, used: { a: 10 } }, + { at: now - 2 * HOUR, used: { a: 20, b: 50 } }, + { at: now - HOUR, used: { b: 60 } }, + ], + now - 24 * HOUR, + ); + expect(series).toEqual([ + { at: now - 2 * HOUR, remaining: 130 }, + { at: now - HOUR, remaining: 120 }, + ]); + }); +}); + +describe("projectionHorizon", () => { + it("looks a day ahead for session windows and a week for weekly ones", () => { + expect(projectionHorizon(pool([{ key: "a", used: 0, mins: 300 }], "session"))).toBe(24 * HOUR); + expect(projectionHorizon(pool([{ key: "a", used: 0 }]))).toBe(7 * 24 * HOUR); + }); +}); diff --git a/packages/shared/src/usagePoolProjection.ts b/packages/shared/src/usagePoolProjection.ts new file mode 100644 index 000000000000..b157ac57fac5 --- /dev/null +++ b/packages/shared/src/usagePoolProjection.ts @@ -0,0 +1,179 @@ +/** + * Pooled quota projection: every account of a provider counts toward one pool (two Claude + * subscriptions = 200%). The pool drains at the current burn rate, spending the account that + * resets first, and each account refills when its window resets. + */ +import type { LimitPoolWindow } from "./usageLimits.ts"; + +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; +/** Measured burn needs at least this much history; shorter spans are mostly noise. */ +const MIN_MEASURED_SPAN = 15 * MINUTE; + +/** One reading of a pool: used percent per account key. */ +export interface PoolSample { + readonly at: number; + readonly used: Readonly>; +} + +interface PoolBurn { + /** Percentage points of the pool spent per hour. */ + readonly perHour: number; + /** "measured" comes from stored readings, "window" from the average since each window opened. */ + readonly source: "measured" | "window"; +} + +export interface PoolProjection { + readonly capacity: number; + readonly remaining: number; + readonly points: ReadonlyArray<{ readonly at: number; readonly remaining: number }>; + readonly refills: ReadonlyArray<{ + readonly at: number; + readonly accountKey: string; + /** Percentage points this reset gives back. */ + readonly restores: number; + /** Pool remaining right after the reset. */ + readonly remainingAfter: number; + }>; + readonly firstEmpty: { readonly at: number; readonly accountKey: string } | null; + readonly poolEmpty: number | null; +} + +const clampUsed = (value: number) => Math.max(0, Math.min(100, value)); + +function resetAt(resetsAt: string | undefined): number | null { + if (resetsAt === undefined) return null; + const at = Date.parse(resetsAt); + return Number.isFinite(at) ? at : null; +} + +/** How far ahead to project: a day for session windows, otherwise one full window. */ +export function projectionHorizon(pool: LimitPoolWindow): number { + const longest = Math.max(0, ...pool.members.map((m) => m.window.windowDurationMins ?? 0)); + if (pool.kind === "session" || (longest > 0 && longest <= 12 * 60)) return DAY; + if (pool.kind === "monthly" || longest >= 28 * 24 * 60) return 31 * DAY; + return 7 * DAY; +} + +function windowAverageBurn(pool: LimitPoolWindow, now: number): number { + let perHour = 0; + for (const { window } of pool.members) { + const at = resetAt(window.resetsAt); + if (at === null || !window.windowDurationMins) continue; + const elapsed = window.windowDurationMins * MINUTE - (at - now); + if (elapsed >= MIN_MEASURED_SPAN) perHour += clampUsed(window.usedPercent) / (elapsed / HOUR); + } + return perHour; +} + +/** + * Burn over the last `lookbackMs` from stored readings. A drop between readings means the + * window reset, so the new value counts as fresh spend. Falls back to the window average while + * the readings span less than 15 minutes. + */ +export function poolBurn( + pool: LimitPoolWindow, + samples: readonly PoolSample[], + now: number, + lookbackMs: number, +): PoolBurn { + const recent = samples.filter((sample) => sample.at >= now - lookbackMs && sample.at <= now); + const first = recent[0]; + const last = recent.at(-1); + if (!first || !last || last.at - first.at < MIN_MEASURED_SPAN) { + return { perHour: windowAverageBurn(pool, now), source: "window" }; + } + let spent = 0; + for (const { account } of pool.members) { + let previous: number | undefined; + for (const sample of recent) { + const used = sample.used[account.key]; + if (used === undefined) continue; + if (previous !== undefined) spent += used >= previous ? used - previous : used; + previous = used; + } + } + return { perHour: spent / ((last.at - first.at) / HOUR), source: "measured" }; +} + +export function projectPool( + pool: LimitPoolWindow, + now: number, + options: { readonly burnPerHour: number; readonly horizonMs: number; readonly steps?: number }, +): PoolProjection { + const accounts = pool.members.map((member) => ({ + key: member.account.key, + used: clampUsed(member.window.usedPercent), + reset: resetAt(member.window.resetsAt), + length: (member.window.windowDurationMins ?? 0) * MINUTE, + })); + const remainingNow = () => accounts.reduce((sum, account) => sum + 100 - account.used, 0); + const capacity = accounts.length * 100; + const remaining = remainingNow(); + const points = [{ at: now, remaining }]; + const refills: Array = []; + const exhausted = accounts.find((account) => account.used >= 100); + let firstEmpty = exhausted ? { at: now, accountKey: exhausted.key } : null; + let poolEmpty = accounts.length > 0 && remaining <= 0 ? now : null; + const steps = options.steps ?? 480; + const step = options.horizonMs / steps; + + for (let index = 1; index <= steps; index += 1) { + const at = now + index * step; + for (const account of accounts) { + while (account.reset !== null && account.reset <= at) { + const restores = account.used; + account.used = 0; + if (restores > 0.5) { + refills.push({ + at: account.reset, + accountKey: account.key, + restores, + remainingAfter: remainingNow(), + }); + } + account.reset = account.length > 0 ? account.reset + account.length : null; + } + } + let drain = (options.burnPerHour * step) / HOUR; + const spendable = accounts + .filter((account) => account.used < 100) + .sort((left, right) => (left.reset ?? Infinity) - (right.reset ?? Infinity)); + for (const account of spendable) { + if (drain <= 0) break; + // An unused window opens on first spend. + if (account.reset === null && account.used === 0 && account.length > 0) { + account.reset = at + account.length; + } + const take = Math.min(drain, 100 - account.used); + account.used += take; + drain -= take; + if (account.used >= 100 && firstEmpty === null) firstEmpty = { at, accountKey: account.key }; + } + const left = remainingNow(); + if (left <= 1e-6 && poolEmpty === null) poolEmpty = at; + points.push({ at, remaining: left }); + } + return { capacity, remaining, points, refills, firstEmpty, poolEmpty }; +} + +/** Pool remaining at each stored reading since `from`, carrying an account's last value forward. */ +export function recordedPool( + pool: LimitPoolWindow, + samples: readonly PoolSample[], + from: number, +): ReadonlyArray<{ readonly at: number; readonly remaining: number }> { + const keys = pool.members.map((member) => member.account.key); + const last: Record = {}; + const series: Array<{ at: number; remaining: number }> = []; + for (const sample of samples) { + for (const key of keys) { + const used = sample.used[key]; + if (used !== undefined) last[key] = clampUsed(used); + } + if (sample.at < from || keys.some((key) => last[key] === undefined)) continue; + series.push({ at: sample.at, remaining: keys.reduce((sum, key) => sum + 100 - last[key]!, 0) }); + } + return series; +} From 5fb7fee253eee9c60404ff59365a127c897eafd8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 12:44:18 +0100 Subject: [PATCH 022/230] Show the model and account Auto routes to in the model picker --- .../chat/ComposerFooterControls.tsx | 3 + .../components/chat/ModelPickerContent.tsx | 9 ++- .../components/chat/ProviderInstanceIcon.tsx | 21 ++++-- .../components/chat/ProviderModelPicker.tsx | 38 +++++++--- .../web/src/components/chat/autoRoute.test.ts | 75 +++++++++++++++++++ apps/web/src/components/chat/autoRoute.ts | 54 +++++++++++++ docs/progress.md | 7 ++ 7 files changed, 191 insertions(+), 16 deletions(-) create mode 100644 apps/web/src/components/chat/autoRoute.test.ts create mode 100644 apps/web/src/components/chat/autoRoute.ts diff --git a/apps/web/src/components/chat/ComposerFooterControls.tsx b/apps/web/src/components/chat/ComposerFooterControls.tsx index ff8ea79ebd31..61bde4cff4f9 100644 --- a/apps/web/src/components/chat/ComposerFooterControls.tsx +++ b/apps/web/src/components/chat/ComposerFooterControls.tsx @@ -314,6 +314,9 @@ export function ComposerModelPicker({ return ( ; onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; lockedProvider: ProviderDriverKind | null; @@ -779,6 +782,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { modelJumpLabelByKey, activeModelKey, selectedModelKeySet, + autoRouteLabel: props.autoRoute?.label, }; const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { @@ -1038,15 +1042,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { } const disabledReason = getModelDisabledReason?.(model.instanceId, model.slug) ?? null; + const autoRoute = model.slug === "auto" ? props.autoRoute : null; return ( - {props.modelSlug === "auto" ? ( - - ) : isAcpRegistry ? ( + {isAcpRegistry ? ( )} - {isCustomEndpoint || props.modelSlug === "auto" ? null : props.showBadge ? ( + {isCustomEndpoint ? null : props.modelSlug === "auto" ? ( + // Auto keeps the logo of the provider it routes to and marks it with a route badge. + + + + ) : props.showBadge ? ( ; onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; lockedProvider: ProviderDriverKind | null; @@ -129,6 +134,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { footer?: ReactNode; }) { const composerFloatingLayerProps = useComposerMenuProps(); + const nowMinute = useNowMinute(); const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false); const isMenuOpen = props.open ?? uncontrolledIsMenuOpen; const registry = useContext(RegistryContext); @@ -170,14 +176,27 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { (activeEntry?.driverKind === "opencode" || activeEntry?.driverKind === "antigravity" ? undefined : selectedInstanceOptions[0]); - const triggerTitle = selectedModel - ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) - : props.model === ANTIGRAVITY_DEFAULT_MODEL - ? "Choose model" - : props.model || "Choose model"; - const triggerLabel = selectedModel - ? `${getDisplayModelName(selectedModel)}${selectedModel.isUnavailable ? " (Unavailable)" : ""}` - : triggerTitle; + const isAuto = props.model === "auto"; + // Names the model Auto would pick now, at this selection's level (default level elsewhere). + const autoRoute = describeAutoRoute({ + entries: props.instanceEntries, + ...(isAuto && props.modelSelectionOptions ? { options: props.modelSelectionOptions } : {}), + now: Date.parse(nowMinute), + }); + const triggerTitle = + isAuto && autoRoute + ? `Auto · ${autoRoute.label}` + : selectedModel + ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) + : props.model === ANTIGRAVITY_DEFAULT_MODEL + ? "Choose model" + : props.model || "Choose model"; + const triggerLabel = + isAuto && autoRoute + ? triggerTitle + : selectedModel + ? `${getDisplayModelName(selectedModel)}${selectedModel.isUnavailable ? " (Unavailable)" : ""}` + : triggerTitle; const showInstanceBadge = activeEntry !== null && shouldShowInstanceBadge(activeEntry, props.instanceEntries); @@ -287,6 +306,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { workspaceCwd={props.workspaceCwd ?? null} activeInstanceId={activeInstanceId} model={props.model} + autoRoute={autoRoute} {...(props.selectedModels !== undefined ? { selectedModels: props.selectedModels } : {})} {...(props.onToggleModel ? { @@ -407,7 +427,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { // Narrow compacted composers hide the provider icon before truncating the name. , + usedPercent: number, +): ServerProvider { + return { + instanceId: ProviderInstanceId.make(id), + driver: ProviderDriverKind.make(driver), + displayName, + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-11-13T11:00:00.000Z", + models: models.map((model) => ({ ...model, isCustom: false, capabilities: null })), + slashCommands: [], + skills: [], + usageLimits: { + windows: [ + { + id: "five_hour", + kind: "session", + label: "Session", + usedPercent, + resetsAt: "2026-11-13T15:00:00.000Z", + }, + ], + }, + } as unknown as ServerProvider; +} + +const claudeModels = [ + { slug: "claude-fable-5-2", name: "Claude Fable 5.2" }, + { slug: "claude-opus-5-5", name: "Claude Opus 5.5" }, + { slug: "claude-sonnet-5-5", name: "Claude Sonnet 5.5" }, + { slug: "auto", name: "Auto" }, +]; + +describe("describeAutoRoute", () => { + it("names the Claude model and account Auto would use", () => { + const entries = deriveProviderInstanceEntries([ + provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 70), + provider("claudeAutoB", "Auto B", "claudeAgent", claudeModels, 10), + ]); + const medium = describeAutoRoute({ entries, now }); + expect(medium?.driverKind).toBe("claudeAgent"); + expect(medium?.label).toMatch(/^.*Opus 5\.5 \(B\)$/); + + const high = describeAutoRoute({ entries, options: [{ id: "effort", value: "high" }], now }); + expect(high?.label).toMatch(/Fable 5\.2 \(B\)$/); + }); + + it("names another provider when both Claude accounts are used up", () => { + const entries = deriveProviderInstanceEntries([ + provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 100), + provider("claudeAutoB", "Auto B", "claudeAgent", claudeModels, 100), + provider("grok", "Grok Build", "grok", [{ slug: "grok-4.7", name: "Grok 4.7" }], 0), + ]); + expect(describeAutoRoute({ entries, now })).toMatchObject({ + driverKind: "grok", + label: expect.stringMatching(/Grok 4\.7 \(Grok Build\)$/), + }); + }); +}); diff --git a/apps/web/src/components/chat/autoRoute.ts b/apps/web/src/components/chat/autoRoute.ts new file mode 100644 index 000000000000..d1a89457bf7f --- /dev/null +++ b/apps/web/src/components/chat/autoRoute.ts @@ -0,0 +1,54 @@ +import { + ProviderInstanceId, + type ModelSelection, + type ProviderDriverKind, +} from "@t3tools/contracts"; +import { resolveAutoModelSelection } from "@t3tools/shared/autoModel"; + +import type { ProviderInstanceEntry } from "../../providerInstances"; +import { getTriggerDisplayModelName } from "./providerIconUtils"; + +/** What the `auto` model would run as right now, for labels such as "Auto · Opus 5.5 (B)". */ +export interface AutoRoute { + readonly driverKind: ProviderDriverKind; + /** The concrete model and its account, such as "Opus 5.5 (B)". */ + readonly label: string; +} + +/** + * Mirrors the server's routing (same resolver, same live usage snapshots), so the picker shows + * the model a new message would get. The server still decides per message; a thread already on + * a model may stay on it. + */ +export function describeAutoRoute(input: { + readonly entries: ReadonlyArray; + readonly options?: ModelSelection["options"]; + readonly now: number; +}): AutoRoute | null { + const resolution = resolveAutoModelSelection({ + selection: { + instanceId: ProviderInstanceId.make("auto"), + model: "auto", + ...(input.options ? { options: input.options } : {}), + }, + providers: input.entries.map((entry) => entry.snapshot), + now: input.now, + }); + if (!resolution) return null; + const entry = input.entries.find( + (candidate) => candidate.instanceId === resolution.selection.instanceId, + ); + const model = entry?.models.find((candidate) => candidate.slug === resolution.selection.model); + if (!entry || !model) return null; + // Claude instances are named "Auto" (account A) and "Auto B"; other providers keep their name. + const account = + entry.driverKind === "claudeAgent" + ? /\bB$/.test(entry.displayName) + ? "B" + : "A" + : entry.displayName; + return { + driverKind: entry.driverKind, + label: `${getTriggerDisplayModelName(model, entry.driverKind)} (${account})`, + }; +} diff --git a/docs/progress.md b/docs/progress.md index 46c2223b1d5c..3ba9579db6ab 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -16,3 +16,10 @@ - How: `ProviderInstanceIcon` takes an optional `modelSlug`; `ModelListRow` and `ProviderModelPicker` pass it. Lint rules ruled out Sparkles and raw palette colors. - Deploy: web-only, so the new `apps/web/dist` was copied into `apps/server/dist/client`; no service restart. The web build took ~45 min on the hub (disk-bound). - Next: keep "Auto" shown in the composer after the first message (needs the thread to remember the Auto selection). + +## 2026-11-13 — Auto shows the model it routes to + +- What: the `auto` entry keeps the logo of the provider it routes to (the Claude logo while Claude has room) with a small route badge, and its label names the model and account, e.g. "Auto · Opus 5.5 (B)", in the picker rows and on the composer button. +- Why: Tomáš wanted to see which Claude model Auto uses; the plain route icon hid it. +- How: `describeAutoRoute` (web) runs the server's `resolveAutoModelSelection` on the client's provider snapshots, at the composer's Auto level, on a minute clock. The server still decides per message (a thread may stay on its current model until 90% used). +- Tests: `autoRoute.test.ts` (2 tests: A/B pick per level, fallback to Grok). The test run alone took ~14 min on the hub. From 71fdfcd5536822e37c3cd98ad02c3d89f620c810 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 13:03:44 +0100 Subject: [PATCH 023/230] Auto routes Claude A/B by 5-hour use and weekly reset, adds Antigravity, lists levels as picker rows Between Claude accounts, Auto takes the freer 5-hour window; within 10 points it spends the account whose weekly quota resets first. Antigravity's Claude models follow the Claude subscriptions at every level. auto-low/auto-medium/auto-high fix the level in the slug so the Auto picker tab lists one row per level. Usage limits open with a per-subscription overview. --- .../components/chat/ModelPickerContent.tsx | 13 ++- .../components/chat/ProviderInstanceIcon.tsx | 3 +- .../components/chat/ProviderModelPicker.tsx | 12 ++- apps/web/src/components/chat/autoRoute.ts | 4 +- .../components/usage/UsageLimitsPooled.tsx | 53 +++++++++++++ docs/progress.md | 8 ++ packages/shared/src/autoModel.test.ts | 79 ++++++++++++++++++- packages/shared/src/autoModel.ts | 68 +++++++++++++--- 8 files changed, 221 insertions(+), 19 deletions(-) diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index b37495b1aadb..0c8465721ac0 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -41,6 +41,7 @@ import { ComboboxListVirtualized, } from "../ui/combobox"; import { ModelEsque } from "./providerIconUtils"; +import { isAutoModelSlug } from "@t3tools/shared/autoModel"; import type { AutoRoute } from "./autoRoute"; import { isCommandPaletteOpen } from "../../commandPaletteBus"; import { registerModelPickerContent } from "../../modelPickerVisibility"; @@ -330,8 +331,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { workspaceCwd?: string | null; activeInstanceId: ProviderInstanceId; model: string; - /** What the `auto` model routes to right now; its rows show it. */ - autoRoute?: AutoRoute | null; + /** What an Auto model row (`auto`, `auto-low`, ...) routes to right now; its row shows it. */ + autoRouteFor?: (slug: string) => AutoRoute | null; selectedModels?: ReadonlyArray<{ instanceId: ProviderInstanceId; model: string }>; onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; lockedProvider: ProviderDriverKind | null; @@ -782,7 +783,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { modelJumpLabelByKey, activeModelKey, selectedModelKeySet, - autoRouteLabel: props.autoRoute?.label, + autoRouteLabels: ["auto", "auto-low", "auto-medium", "auto-high"] + .map((slug) => props.autoRouteFor?.(slug)?.label ?? "") + .join("|"), }; const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { @@ -1042,7 +1045,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { } const disabledReason = getModelDisabledReason?.(model.instanceId, model.slug) ?? null; - const autoRoute = model.slug === "auto" ? props.autoRoute : null; + const autoRoute = isAutoModelSlug(model.slug) + ? (props.autoRouteFor?.(model.slug) ?? null) + : null; return ( )} - {isCustomEndpoint ? null : props.modelSlug === "auto" ? ( + {isCustomEndpoint ? null : isAutoModelSlug(props.modelSlug) ? ( // Auto keeps the logo of the provider it routes to and marks it with a route badge. + describeAutoRoute({ entries: props.instanceEntries, model: slug, now }); const triggerTitle = isAuto && autoRoute ? `Auto · ${autoRoute.label}` @@ -306,7 +312,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { workspaceCwd={props.workspaceCwd ?? null} activeInstanceId={activeInstanceId} model={props.model} - autoRoute={autoRoute} + autoRouteFor={autoRouteFor} {...(props.selectedModels !== undefined ? { selectedModels: props.selectedModels } : {})} {...(props.onToggleModel ? { diff --git a/apps/web/src/components/chat/autoRoute.ts b/apps/web/src/components/chat/autoRoute.ts index d1a89457bf7f..eff72e2a9e71 100644 --- a/apps/web/src/components/chat/autoRoute.ts +++ b/apps/web/src/components/chat/autoRoute.ts @@ -22,13 +22,15 @@ export interface AutoRoute { */ export function describeAutoRoute(input: { readonly entries: ReadonlyArray; + /** `auto`, or a fixed-level `auto-low` / `auto-medium` / `auto-high`. */ + readonly model?: string; readonly options?: ModelSelection["options"]; readonly now: number; }): AutoRoute | null { const resolution = resolveAutoModelSelection({ selection: { instanceId: ProviderInstanceId.make("auto"), - model: "auto", + model: input.model ?? "auto", ...(input.options ? { options: input.options } : {}), }, providers: input.entries.map((entry) => entry.snapshot), diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index 50acedba3fe0..73e6032a229b 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -691,6 +691,58 @@ function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: nu ); } +/** One row per subscription: every window it reports, so no account hides inside a pool. */ +function SubscriptionsOverview({ + pools, + now, +}: { + readonly pools: readonly LimitPool[]; + readonly now: number; +}) { + const rows = pools.flatMap((pool) => pool.accounts.map((account) => ({ pool, account }))); + if (rows.length === 0) return null; + return ( +
+

Subscriptions

+
+ {rows.map(({ pool, account }) => ( +
+ + + + + {account.limits.windows.map((window) => { + const resetsIn = formatResetsIn(window, now); + return ( + + {window.label} + {remainingPercent(window)}% + {resetsIn ? {resetsIn.replace("resets in ", "↻ ")} : null} + + ); + })} +
+ ))} +
+
+ ); +} + export function UsageLimitsPooled({ presentations, now, @@ -716,6 +768,7 @@ export function UsageLimitsPooled({ No provider on the selected environments reports subscription limits.

) : null} + {pools.map((pool) => ( diff --git a/docs/progress.md b/docs/progress.md index 3ba9579db6ab..1a91af83a5bb 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -23,3 +23,11 @@ - Why: Tomáš wanted to see which Claude model Auto uses; the plain route icon hid it. - How: `describeAutoRoute` (web) runs the server's `resolveAutoModelSelection` on the client's provider snapshots, at the composer's Auto level, on a minute clock. The server still decides per message (a thread may stay on its current model until 90% used). - Tests: `autoRoute.test.ts` (2 tests: A/B pick per level, fallback to Grok). The test run alone took ~14 min on the hub. + +## 2026-11-13: Auto routes by 5-hour use and weekly reset; Auto levels as picker rows; subscriptions overview + +- What: Auto now picks between Claude accounts by the freer 5-hour window; when two accounts are within 10 points, it spends the one whose weekly quota resets first (unused quota is lost at reset). Antigravity's Claude models (Opus 4.6 Thinking, Sonnet 4.6) sit right after the Claude subscriptions in every level. `auto-low` / `auto-medium` / `auto-high` fix the level in the model slug, so the Auto tab in the picker lists one row per level, each naming its current route. Usage → Limits opens with a Subscriptions table: one row per account with every window's remaining % and reset. +- Why: Tomáš wants Auto to always use Claude A/B first and route by 5-hour room and weekly expiry, use the Antigravity subscription too, show its levels like other models, and see each subscription next to the pooled view. +- Numbers: autoModel tests 9/9 (3 new routing cases failed before the change, plus a level-slug test). Web typecheck clean in 47 s warm. +- What worked: the Limits page showed Claude and distinct A/B numbers once the hub was quiet. The missing Claude section and copied numbers came from limit probes timing out while the hub was overloaded (load 11, IO pressure ~90). +- Next: one combined web + server build, deployed with a stop/start of t3code.service, then settings switch the Auto tab to the three level rows. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index e7846c214e74..eda559c93c55 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { AUTO_LEVEL_DESCRIPTOR, resolveAutoModelSelection } from "./autoModel.ts"; +import { AUTO_LEVEL_DESCRIPTOR, isAutoModelSlug, resolveAutoModelSelection } from "./autoModel.ts"; const now = Date.parse("2026-11-12T12:00:00.000Z"); const resetsAt = "2026-11-12T15:00:00.000Z"; @@ -58,6 +58,18 @@ function claude(id: string, usedPercent: number, autoAware = true): ServerProvid } as unknown as ServerProvider; } +function withWeekly(provider: ServerProvider, usedPercent: number, weeklyResetsAt: string) { + return { + ...provider, + usageLimits: { + windows: [ + ...(provider.usageLimits?.windows ?? []), + { id: "seven_day", kind: "weekly", label: "Weekly", usedPercent, resetsAt: weeklyResetsAt }, + ], + }, + } as unknown as ServerProvider; +} + const auto = (level?: string): ModelSelection => ({ instanceId: ProviderInstanceId.make("claudeAuto"), model: "auto", @@ -125,6 +137,71 @@ describe("resolveAutoModelSelection", () => { }); }); + it("routes to the account with less of its 5-hour window used", () => { + // A has the busier week but a nearly unused 5-hour window, so it can take work right now. + const providers = [ + withWeekly(claude("claudeAutoB", 50), 20, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 10), 60, "2026-11-18T12:00:00.000Z"), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, + ).toBe("claudeAuto"); + }); + + it("with similar 5-hour use, spends the account whose weekly limit resets first", () => { + // B has slightly less 5-hour use, but A's unused weekly quota is gone tomorrow. + const providers = [ + withWeekly(claude("claudeAutoB", 25), 40, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 30), 40, "2026-11-13T12:00:00.000Z"), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, + ).toBe("claudeAuto"); + }); + + it("falls back to Claude on the Antigravity subscription before other providers", () => { + const antigravity = { + ...claude("antigravity", 0, false), + driver: ProviderDriverKind.make("antigravity"), + models: ["claude-opus-4-6-thinking", "claude-sonnet-4-6"].map((slug) => ({ + slug, + name: slug, + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "thinking_level", + label: "Thinking", + type: "select" as const, + options: ["low", "medium", "high"].map((id) => ({ id, label: id })), + }, + ], + }, + })), + } as unknown as ServerProvider; + const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100), antigravity]; + expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection).toEqual({ + instanceId: "antigravity", + model: "claude-opus-4-6-thinking", + options: [{ id: "thinking_level", value: "medium" }], + }); + }); + + it("reads the level from auto-low / auto-medium / auto-high", () => { + const providers = [claude("claudeAuto", 10)]; + const pick = (model: string) => + resolveAutoModelSelection({ + selection: { instanceId: ProviderInstanceId.make("claudeAuto"), model }, + providers, + now, + })?.selection.model; + expect(pick("auto-high")).toBe("claude-fable-5-2"); + expect(pick("auto-medium")).toBe("claude-opus-5-5"); + expect(pick("auto-low")).toBe("claude-sonnet-5-5"); + expect(isAutoModelSlug("auto-low")).toBe(true); + expect(isAutoModelSlug("auto-max")).toBe(false); + }); + it("returns null when nothing is usable", () => { const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; expect(resolveAutoModelSelection({ selection: auto(), providers, now })).toBeNull(); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 87f997204b42..d76eda593edb 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -38,6 +38,12 @@ const codex = (model: string, effort: string): AutoCandidate => ({ effort, }); const grok = (effort: string): AutoCandidate => ({ driver: "grok", model: "grok-4.7", effort }); +/** Claude models on the Antigravity (Google) subscription: a third Claude pool. */ +const antigravity = (model: string, effort: string): AutoCandidate => ({ + driver: "antigravity", + model, + effort, +}); const opencode = (model: string, effort: string): AutoCandidate => ({ driver: "opencode", model, @@ -52,6 +58,7 @@ const AUTO_CANDIDATES: Readonly>> high: [ claude("claude-fable-5-2", "high"), claude("claude-opus-5-5", "high"), + antigravity("claude-opus-4-6-thinking", "high"), codex("gpt-6.1-sol", "high"), codex("gpt-6-astra", "high"), grok("high"), @@ -60,6 +67,7 @@ const AUTO_CANDIDATES: Readonly>> medium: [ claude("claude-opus-5-5", "medium"), claude("claude-fable-5-2", "medium"), + antigravity("claude-opus-4-6-thinking", "medium"), codex("gpt-6.1-sol", "medium"), codex("gpt-6-astra", "medium"), claude("claude-sonnet-5-5", "medium"), @@ -69,6 +77,7 @@ const AUTO_CANDIDATES: Readonly>> low: [ claude("claude-sonnet-5-5", "low"), claude("claude-haiku-5-5", "low"), + antigravity("claude-sonnet-4-6", "low"), opencode("opencode/big-pickle", "medium"), opencode("opencode/deepseek-v4.1-flash-free", "medium"), codex("gpt-6-luna", "low"), @@ -82,13 +91,26 @@ const EFFORT_OPTION_ID: Readonly> = { codex: "reasoningEffort", grok: "reasoningEffort", opencode: "variant", + antigravity: "thinking_level", }; +/** + * `auto` takes its level from the `effort` option; `auto-low`, `auto-medium` and `auto-high` + * fix it in the slug, so a picker can list one row per level. + */ +export function isAutoModelSlug(slug: string | null | undefined): boolean { + return ( + slug === AUTO_MODEL_SLUG || AUTO_LEVELS.some((level) => slug === `${AUTO_MODEL_SLUG}-${level}`) + ); +} + export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { - return selection?.model === AUTO_MODEL_SLUG; + return isAutoModelSlug(selection?.model); } function autoLevelOf(selection: ModelSelection): AutoLevel { + const fixed = AUTO_LEVELS.find((level) => selection.model === `${AUTO_MODEL_SLUG}-${level}`); + if (fixed) return fixed; const value = selection.options?.find((option) => option.id === "effort")?.value; return AUTO_LEVELS.find((level) => level === value) ?? DEFAULT_LEVEL; } @@ -105,13 +127,45 @@ export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { ], }; +/** Accounts whose 5-hour use differs by less than this many points count as equally free. */ +const SESSION_BAND_PERCENT = 10; + +function sessionUsedPercent(provider: ServerProvider): number { + const windows = (provider.usageLimits?.windows ?? []).filter((w) => w.kind === "session"); + return Math.max(0, ...windows.map((w) => w.usedPercent ?? 0)); +} + +/** When the soonest weekly window resets; unused weekly quota is lost then. */ +function weeklyResetAt(provider: ServerProvider): number { + const resets = (provider.usageLimits?.windows ?? []) + .filter((w) => w.kind === "weekly" && w.resetsAt !== undefined) + .map((w) => Date.parse(w.resetsAt!)) + .filter(Number.isFinite); + return resets.length > 0 ? Math.min(...resets) : Infinity; +} + +/** + * Best instance first: Auto-aware (carries the Auto prompt), then the freer 5-hour window, + * then, between accounts with similar 5-hour use, the one whose weekly quota resets first. + */ +function compareInstances(a: ServerProvider, b: ServerProvider): number { + const aware = Number(isAutoAware(b)) - Number(isAutoAware(a)); + if (aware !== 0) return aware; + const session = sessionUsedPercent(a) - sessionUsedPercent(b); + if (Math.abs(session) >= SESSION_BAND_PERCENT) return session; + const weekly = weeklyResetAt(a) - weeklyResetAt(b); + if (Number.isFinite(weekly) && weekly !== 0) return weekly; + if (weekly === Infinity || weekly === -Infinity) return weekly > 0 ? 1 : -1; + return session || peakUsedPercent(a) - peakUsedPercent(b); +} + function peakUsedPercent(provider: ServerProvider): number { return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); } /** Instances that list the `auto` model carry the Auto-mode prompt, so they win ties. */ function isAutoAware(provider: ServerProvider): boolean { - return provider.models.some((model) => model.slug === AUTO_MODEL_SLUG); + return provider.models.some((model) => isAutoModelSlug(model.slug)); } function usable(provider: ServerProvider, model: string, now: number): boolean { @@ -154,8 +208,8 @@ interface AutoResolution { /** * Keeps the thread's model while it fits this level and is under 90% used (no account hop, no - * lost prompt cache); otherwise the first usable candidate, Auto-aware and least-used instance - * first. Null when nothing is usable. + * lost prompt cache); otherwise the first usable candidate on the best instance (see + * `compareInstances`). Null when nothing is usable. */ export function resolveAutoModelSelection(input: { readonly selection: ModelSelection; @@ -190,11 +244,7 @@ export function resolveAutoModelSelection(input: { usable(provider, candidate.model, input.now), ) // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. - .sort( - (a, b) => - Number(isAutoAware(b)) - Number(isAutoAware(a)) || - peakUsedPercent(a) - peakUsedPercent(b), - ); + .sort(compareInstances); const provider = instances[0]; if (provider) return { selection: toSelection(provider, candidate), level, sticky: false }; } From b3836a17677eae56717d0fac8956bdf5e2d6a2ac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 14:24:07 +0100 Subject: [PATCH 024/230] Name the chosen Auto level on the model picker button MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The button showed the model Auto routes to ("Auto · Opus 5.5 (A)"), which read as if Auto Medium were Opus. It now shows the level, such as "Auto Medium", and the tooltip names the current route. --- .../components/chat/ProviderModelPicker.tsx | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index b08720f68fdc..10961d71ba7c 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -189,20 +189,22 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { // Each Auto level row in the list names its own route. const autoRouteFor = (slug: string) => describeAutoRoute({ entries: props.instanceEntries, model: slug, now }); - const triggerTitle = - isAuto && autoRoute - ? `Auto · ${autoRoute.label}` - : selectedModel - ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) - : props.model === ANTIGRAVITY_DEFAULT_MODEL - ? "Choose model" - : props.model || "Choose model"; - const triggerLabel = - isAuto && autoRoute - ? triggerTitle - : selectedModel - ? `${getDisplayModelName(selectedModel)}${selectedModel.isUnavailable ? " (Unavailable)" : ""}` - : triggerTitle; + // The button names the chosen Auto level; the model it routes to now goes in the tooltip. + const autoName = selectedModel ? getDisplayModelName(selectedModel) : "Auto"; + const triggerTitle = isAuto + ? autoName + : selectedModel + ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) + : props.model === ANTIGRAVITY_DEFAULT_MODEL + ? "Choose model" + : props.model || "Choose model"; + const triggerLabel = isAuto + ? autoRoute + ? `${autoName} · now ${autoRoute.label}` + : autoName + : selectedModel + ? `${getDisplayModelName(selectedModel)}${selectedModel.isUnavailable ? " (Unavailable)" : ""}` + : triggerTitle; const showInstanceBadge = activeEntry !== null && shouldShowInstanceBadge(activeEntry, props.instanceEntries); From d8080c744ed6a5fdf6020a0e0fe575b6ff3aa54d Mon Sep 17 00:00:00 2001 From: radys-s Date: Fri, 13 Nov 2026 14:24:39 +0100 Subject: [PATCH 025/230] docs: tell agents to commit each medium step with its origin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agents batched a whole task into one commit at the end, so history could not show which request or review finding produced which change. AGENTS.md gains a Commits section: commit and push each finished, verified step of medium size or larger, one idea per commit, with a body that states why and where the change came from (issue, PR, review finding, thread link, or the request in one line). Origin: Tomáš asked for more frequent, traceable orchestrator commits. --- .github/pull_request_template.md | 1 + AGENTS.md | 9 +++++++++ docs/progress.md | 7 +++++++ 3 files changed, 17 insertions(+) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 94157c4135fa..5325e46142f4 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -3,6 +3,7 @@ Read CONTRIBUTING.md before opening a PR. Review capacity is limited, and meetin the requirements does not guarantee review or merging. Solve one underlying problem. The same requirements apply to drafts. Draft status does not defer triage or closure. Use a conventional commit title in plain language, such as "fix(web): new threads no longer spike CPU". +Keep one step per commit, and say in each commit body why it exists and where it came from. --> ## Problem diff --git a/AGENTS.md b/AGENTS.md index e5941a175264..1274dfdfc0df 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -147,6 +147,14 @@ For mobile verification, a missing or outdated native client is an install step, `evals/` checks how real models behave with T3 Code's model-facing text: agent instructions, MCP tool descriptions and schemas, and generated titles. Before you change that text, read [evals/README.md](evals/README.md) and run the evals it names. When you fix a model behavior bug, add a case that fails before the fix. +## Commits + +- Commit as you go, not once at the end. Each finished, verified step of medium size or larger gets its own commit right away: a bug fix, a feature slice, a refactor, a test suite, a doc update. Fold small edits (a typo, a rename, a review nit) into the step they belong to. +- One commit is one idea. If the title needs "and", split it. Every commit should build and pass the checks for the files it touches, so `git bisect` and `git revert` work on it alone. +- Title: conventional commit, as for PRs. Body: why the change exists, what it changes, and its origin, the issue, PR, review finding, or thread link that asked for it, or the user's request in one line. A reader of `git log` or `git blame` should reach the reason without the chat. +- Commit worker or delegate output only after you review and check it. Push after each commit on a task branch so the work is never only local. +- Never commit to `main` directly. Never rewrite commits that are already pushed unless the developer asks. + ## Pull requests - Never make a PR unless the developer explicitly asks you to do so. @@ -156,6 +164,7 @@ For mobile verification, a missing or outdated native client is an install step, - UI changes need before/after images. Motion or timing needs a short video. - Upload PR evidence to GitHub. Never commit PR-only screenshots or assets such as `.github/pr-assets/`. - One request is one PR. Split it only when the maintainer asks. Outside contributions follow the stricter [one problem per PR](CONTRIBUTING.md#one-problem) rule. +- Merge with a merge commit (`gh pr merge --merge`) so the per-step commits stay in `main`'s history. Squash only when the maintainer asks. - When babysitting: call `watch_pull_request` and end your turn. T3 Code wakes you on checks, comments, or conflicts. Do not poll or sleep. Verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit. ## Documentation diff --git a/docs/progress.md b/docs/progress.md index 1a91af83a5bb..821d5452b229 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -31,3 +31,10 @@ - Numbers: autoModel tests 9/9 (3 new routing cases failed before the change, plus a level-slug test). Web typecheck clean in 47 s warm. - What worked: the Limits page showed Claude and distinct A/B numbers once the hub was quiet. The missing Claude section and copied numbers came from limit probes timing out while the hub was overloaded (load 11, IO pressure ~90). - Next: one combined web + server build, deployed with a stop/start of t3code.service, then settings switch the Auto tab to the three level rows. + +## 2026-11-13: Agents commit each step with its origin + +- What: `AGENTS.md` gets a Commits section. Agents commit and push each finished, checked step of medium size or larger, one idea per commit, with a body that says why and where the change came from (issue, PR, review finding, thread link, or the request). PRs merge with a merge commit so those steps stay in `main`. The PR template repeats the rule in one line. Outside the repo, `~/.agents/T3-CODE.md` and the `auto` and `swarm` skills got the same rule. +- Why: Tomáš wants to trace a problem back to the step and request that caused it. One big commit per task, or a squash merge, hides that. +- Numbers: docs only, 4 commits in PR #4. The fork runs no CI checks on PRs. +- Next: watch whether agents keep the cadence. If they do not, add the rule to the built-in orchestration instructions (`orchestrationInstructions.ts`, needs evals). From 9e7683469b5e94965e51a2c47daadb0fbe0cc828 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 15:34:22 +0100 Subject: [PATCH 026/230] feat(shared): stagger Claude A/B 5-hour windows in Auto routing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auto sent work to the account with less 5-hour use, so both windows started together and ran out together. It now keeps using the account whose window is already running until any of its windows reaches 90%, then moves to the other, so one refreshes while the other works. Within 10 points of 5-hour use, the sooner weekly reset still goes first. Origin: Tomáš asked that Auto pick the plan closer to running out and offset the 5-hour windows so one refreshes while the other is nearly used up. GPT review loop: 2 rounds, approved. --- .../web/src/components/chat/autoRoute.test.ts | 2 +- docs/progress.md | 7 ++ packages/shared/src/autoModel.test.ts | 90 ++++++++++++++++--- packages/shared/src/autoModel.ts | 35 ++++++-- 4 files changed, 111 insertions(+), 23 deletions(-) diff --git a/apps/web/src/components/chat/autoRoute.test.ts b/apps/web/src/components/chat/autoRoute.test.ts index fae0bdef7887..85ae44be3be8 100644 --- a/apps/web/src/components/chat/autoRoute.test.ts +++ b/apps/web/src/components/chat/autoRoute.test.ts @@ -50,7 +50,7 @@ const claudeModels = [ describe("describeAutoRoute", () => { it("names the Claude model and account Auto would use", () => { const entries = deriveProviderInstanceEntries([ - provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 70), + provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 95), provider("claudeAutoB", "Auto B", "claudeAgent", claudeModels, 10), ]); const medium = describeAutoRoute({ entries, now }); diff --git a/docs/progress.md b/docs/progress.md index 821d5452b229..22b8a6855e87 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -38,3 +38,10 @@ - Why: Tomáš wants to trace a problem back to the step and request that caused it. One big commit per task, or a squash merge, hides that. - Numbers: docs only, 4 commits in PR #4. The fork runs no CI checks on PRs. - Next: watch whether agents keep the cadence. If they do not, add the rule to the built-in orchestration instructions (`orchestrationInstructions.ts`, needs evals). + +## 2026-11-13: Auto staggers Claude A/B 5-hour windows + +- What: Auto now keeps sending work to the account whose 5-hour window is already running, until any of its windows reaches 90%, then moves to the other account. Within 10 points of 5-hour use, the sooner weekly reset wins. Past 90% everywhere, the account with the most left wins. +- Why: preferring the emptier account started both 5-hour windows at the same time, so both ran out together. Staggered windows let one refresh while the other is in use. +- Numbers: 11 routing tests (3 new), a mutation check (dropping the 90% rule fails 3 tests). +- Next: watch real routing on the hub for a day of use. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index eda559c93c55..ecd8389c4ba3 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -98,12 +98,8 @@ describe("resolveAutoModelSelection", () => { }); }); - it("picks the Claude account with more room, preferring Auto-aware instances", () => { - const providers = [ - claude("claudeAgent", 0, false), - claude("claudeAuto", 70), - claude("claudeAutoB", 20), - ]; + it("prefers Auto-aware instances", () => { + const providers = [claude("claudeAgent", 0, false), claude("claudeAutoB", 20)]; expect( resolveAutoModelSelection({ selection: auto("medium"), providers, now })?.selection .instanceId, @@ -137,22 +133,46 @@ describe("resolveAutoModelSelection", () => { }); }); - it("routes to the account with less of its 5-hour window used", () => { - // A has the busier week but a nearly unused 5-hour window, so it can take work right now. + it("drains the account whose 5-hour window is already running, so the windows stagger", () => { + // A's window is half spent; B stays untouched and its window starts only when A is nearly + // out, so A refreshes while B is in use. const providers = [ - withWeekly(claude("claudeAutoB", 50), 20, "2026-11-18T12:00:00.000Z"), - withWeekly(claude("claudeAuto", 10), 60, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAutoB", 0), 20, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 50), 20, "2026-11-18T12:00:00.000Z"), ]; expect( resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, ).toBe("claudeAuto"); }); + it("switches to the other account once a 5-hour or weekly window is 90% used", () => { + const sessionFull = [claude("claudeAuto", 92), claude("claudeAutoB", 0)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: sessionFull, now })?.selection + .instanceId, + ).toBe("claudeAutoB"); + const weeklyFull = [ + withWeekly(claude("claudeAuto", 50), 95, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAutoB", 0), 20, "2026-11-18T12:00:00.000Z"), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: weeklyFull, now })?.selection + .instanceId, + ).toBe("claudeAutoB"); + }); + + it("when every account is past 90%, uses the one with the most left", () => { + const providers = [claude("claudeAuto", 92), claude("claudeAutoB", 97)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, + ).toBe("claudeAuto"); + }); + it("with similar 5-hour use, spends the account whose weekly limit resets first", () => { - // B has slightly less 5-hour use, but A's unused weekly quota is gone tomorrow. + // B's window is slightly further along, but A's unused weekly quota is gone tomorrow. const providers = [ - withWeekly(claude("claudeAutoB", 25), 40, "2026-11-18T12:00:00.000Z"), - withWeekly(claude("claudeAuto", 30), 40, "2026-11-13T12:00:00.000Z"), + withWeekly(claude("claudeAutoB", 30), 40, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 25), 40, "2026-11-13T12:00:00.000Z"), ]; expect( resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, @@ -187,6 +207,50 @@ describe("resolveAutoModelSelection", () => { }); }); + it("after every Claude subscription, uses ChatGPT, then Grok, then Gemini", () => { + const other = (id: string, driver: string, slug: string, optionId: string) => + ({ + ...claude(id, 0, false), + driver: ProviderDriverKind.make(driver), + models: [ + { + slug, + name: slug, + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: optionId, + label: "Effort", + type: "select" as const, + options: ["low", "medium", "high"].map((value) => ({ id: value, label: value })), + }, + ], + }, + }, + ], + usageLimits: undefined, + }) as unknown as ServerProvider; + const claudeOut = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; + const codex = other("codex", "codex", "gpt-6-luna", "reasoningEffort"); + const grok = other("grok", "grok", "grok-4.7", "reasoningEffort"); + const gemini = other("antigravity", "antigravity", "gemini-3.8-flash", "thinking_level"); + const route = (providers: ServerProvider[]) => + resolveAutoModelSelection({ selection: auto("high"), providers, now })?.selection; + + expect(route([...claudeOut, gemini, grok, codex])).toEqual({ + instanceId: "codex", + model: "gpt-6-luna", + options: [{ id: "reasoningEffort", value: "high" }], + }); + expect(route([...claudeOut, gemini, grok])?.instanceId).toBe("grok"); + expect(route([...claudeOut, gemini])).toEqual({ + instanceId: "antigravity", + model: "gemini-3.8-flash", + options: [{ id: "thinking_level", value: "high" }], + }); + }); + it("reads the level from auto-low / auto-medium / auto-high", () => { const providers = [claude("claudeAuto", 10)]; const pick = (model: string) => diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index d76eda593edb..db3e53c713da 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -17,7 +17,8 @@ const AUTO_MODEL_SLUG = "auto"; const AUTO_LEVELS = ["low", "medium", "high"] as const; type AutoLevel = (typeof AUTO_LEVELS)[number]; const DEFAULT_LEVEL: AutoLevel = "medium"; -/** Above this peak usage, a sticky model gives way when another candidate has more room. */ +/** At this peak usage an account counts as nearly out: a sticky model gives way and routing + * moves to an account with room. */ const STICKY_MAX_USED_PERCENT = 90; interface AutoCandidate { @@ -51,8 +52,9 @@ const opencode = (model: string, effort: string): AutoCandidate => ({ }); /** - * Orchestrator candidates per level, best first. Each level starts on its Claude model and - * steps down through the other subscriptions as limits run out. + * Orchestrator candidates per level, best first: Claude A/B, Claude on Antigravity A/B, ChatGPT + * (Codex), Grok, Gemini, then free OpenCode models. Models a provider does not list are skipped, + * so paid-plan models (Sol, Astra) wait until the plan has them. */ const AUTO_CANDIDATES: Readonly>> = { high: [ @@ -61,8 +63,9 @@ const AUTO_CANDIDATES: Readonly>> antigravity("claude-opus-4-6-thinking", "high"), codex("gpt-6.1-sol", "high"), codex("gpt-6-astra", "high"), - grok("high"), codex("gpt-6-luna", "high"), + grok("high"), + antigravity("gemini-3.8-flash", "high"), ], medium: [ claude("claude-opus-5-5", "medium"), @@ -71,15 +74,21 @@ const AUTO_CANDIDATES: Readonly>> codex("gpt-6.1-sol", "medium"), codex("gpt-6-astra", "medium"), claude("claude-sonnet-5-5", "medium"), - grok("medium"), + antigravity("claude-sonnet-4-6", "medium"), codex("gpt-6-luna", "medium"), + grok("medium"), + antigravity("gemini-3.8-flash", "medium"), + opencode("opencode/big-pickle", "medium"), ], low: [ claude("claude-sonnet-5-5", "low"), claude("claude-haiku-5-5", "low"), antigravity("claude-sonnet-4-6", "low"), + antigravity("gemini-3.8-flash", "low"), opencode("opencode/big-pickle", "medium"), + opencode("opencode/beam-free", "medium"), opencode("opencode/deepseek-v4.1-flash-free", "medium"), + opencode("opencode/glm-5.3-flash-free", "medium"), codex("gpt-6-luna", "low"), grok("low"), ], @@ -127,7 +136,7 @@ export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { ], }; -/** Accounts whose 5-hour use differs by less than this many points count as equally free. */ +/** Accounts whose 5-hour use differs by less than this many points count as equally far along. */ const SESSION_BAND_PERCENT = 10; function sessionUsedPercent(provider: ServerProvider): number { @@ -145,13 +154,17 @@ function weeklyResetAt(provider: ServerProvider): number { } /** - * Best instance first: Auto-aware (carries the Auto prompt), then the freer 5-hour window, - * then, between accounts with similar 5-hour use, the one whose weekly quota resets first. + * Best instance first: Auto-aware, then accounts under 90% everywhere. Among those, the further + * along 5-hour window, so windows stagger (one refreshes while the other runs); within 10 + * points, the sooner weekly reset. Past 90% everywhere, the most left. */ function compareInstances(a: ServerProvider, b: ServerProvider): number { const aware = Number(isAutoAware(b)) - Number(isAutoAware(a)); if (aware !== 0) return aware; - const session = sessionUsedPercent(a) - sessionUsedPercent(b); + const room = Number(hasRoom(b)) - Number(hasRoom(a)); + if (room !== 0) return room; + if (!hasRoom(a)) return peakUsedPercent(a) - peakUsedPercent(b); + const session = sessionUsedPercent(b) - sessionUsedPercent(a); if (Math.abs(session) >= SESSION_BAND_PERCENT) return session; const weekly = weeklyResetAt(a) - weeklyResetAt(b); if (Number.isFinite(weekly) && weekly !== 0) return weekly; @@ -159,6 +172,10 @@ function compareInstances(a: ServerProvider, b: ServerProvider): number { return session || peakUsedPercent(a) - peakUsedPercent(b); } +function hasRoom(provider: ServerProvider): boolean { + return peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT; +} + function peakUsedPercent(provider: ServerProvider): number { return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); } From 81b6334ee4f5814d7a865005f62ef5fe44932590 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 16:51:15 +0100 Subject: [PATCH 027/230] feat(server): list Auto levels on every Claude provider MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auto Low, Medium and High existed only as custom models in the hub's settings, so a fork server on another machine (Tomáš's PC) showed no Auto at all. Every Claude provider now lists them as built-in models; a custom model with the same slug still works because built-ins win. Origin: Tomáš asked that Auto work in threads that run only on his own device. --- .../src/provider/ClaudeProvider.test.ts | 22 +++++++++++++++++++ apps/server/src/provider/ClaudeProvider.ts | 10 ++++++++- .../src/provider/ProviderRegistry.test.ts | 5 ++++- packages/shared/src/autoModel.ts | 7 ++++++ 4 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 apps/server/src/provider/ClaudeProvider.test.ts diff --git a/apps/server/src/provider/ClaudeProvider.test.ts b/apps/server/src/provider/ClaudeProvider.test.ts new file mode 100644 index 000000000000..0acb897d044b --- /dev/null +++ b/apps/server/src/provider/ClaudeProvider.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "@effect/vitest"; +import { ClaudeSettings } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { makePendingClaudeProvider } from "./ClaudeProvider.ts"; + +const defaultSettings = Schema.decodeSync(ClaudeSettings)({}); + +describe("makePendingClaudeProvider", () => { + it.effect("lists Auto Low, Medium and High after the real models, with no settings", () => + Effect.gen(function* () { + const provider = yield* makePendingClaudeProvider(defaultSettings); + expect(provider.models[0]?.slug).toMatch(/^claude-/); + expect(provider.models.slice(-3).map((model) => [model.slug, model.name])).toEqual([ + ["auto-low", "Auto Low"], + ["auto-medium", "Auto Medium"], + ["auto-high", "Auto High"], + ]); + }), + ); +}); diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.ts index b657a2b813fe..082a34c4ad02 100644 --- a/apps/server/src/provider/ClaudeProvider.ts +++ b/apps/server/src/provider/ClaudeProvider.ts @@ -20,6 +20,7 @@ import * as Ref from "effect/Ref"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { AUTO_LEVEL_MODELS } from "@t3tools/shared/autoModel"; import { createModelCapabilities } from "@t3tools/shared/model"; import { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -83,12 +84,19 @@ const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabili optionDescriptors: [], }); +const AUTO_MODELS: ReadonlyArray = AUTO_LEVEL_MODELS.map((model) => ({ + ...model, + isCustom: false, + capabilities: DEFAULT_CLAUDE_MODEL_CAPABILITIES, +})); + function claudeProviderModels( builtInModels: ReadonlyArray, customModels: ClaudeSettings["customModels"], ): ReadonlyArray { return providerModelsFromSettings( - builtInModels, + // After the real models: callers that default to a provider's first model keep a real one. + [...builtInModels, ...AUTO_MODELS], customModels, DEFAULT_CLAUDE_MODEL_CAPABILITIES, ).map((model) => diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 2ea6d98c083c..7e15af224c0a 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -44,6 +44,7 @@ import { HttpClient, HttpClientResponse } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { deepMerge } from "@t3tools/shared/Struct"; +import { isAutoModelSlug } from "@t3tools/shared/autoModel"; import { createModelCapabilities } from "@t3tools/shared/model"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; @@ -4220,7 +4221,9 @@ it.layer( }), ); const catalogSlugs = new Set(BUNDLED_CLAUDE_MODEL_CATALOG.models.map((m) => m.model.slug)); - const added = status.models.filter((model) => !catalogSlugs.has(model.slug)); + const added = status.models.filter( + (model) => !catalogSlugs.has(model.slug) && !isAutoModelSlug(model.slug), + ); assert.deepStrictEqual( added.map((model) => [model.slug, model.name, model.isCustom]), diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index db3e53c713da..312468f38d01 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -113,6 +113,13 @@ export function isAutoModelSlug(slug: string | null | undefined): boolean { ); } +/** One picker row per level; every Claude provider lists them, so Auto needs no settings. */ +export const AUTO_LEVEL_MODELS: ReadonlyArray<{ readonly slug: string; readonly name: string }> = + AUTO_LEVELS.map((level) => ({ + slug: `${AUTO_MODEL_SLUG}-${level}`, + name: `Auto ${level[0]!.toUpperCase()}${level.slice(1)}`, + })); + export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { return isAutoModelSlug(selection?.model); } From c19c2b6b9ebdf954d9abbf93adc6bdb7ac25912f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 16:51:16 +0100 Subject: [PATCH 028/230] feat(web): pin Auto levels at the top of Favorites MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Favorites live in each server's settings, so a machine without the hub's settings had no Auto pinned. The picker now puts Auto High, Medium and Low from the first Claude instance that lists them at the top of Favorites, until the user stars an Auto level themselves. Origin: Tomáš asked for the Auto levels to be the main pinned models in every thread. --- .../components/chat/ModelPickerContent.tsx | 7 ++- .../chat/ProviderModelPicker.logic.test.ts | 59 ++++++++++++++++++- .../chat/ProviderModelPicker.logic.ts | 37 +++++++++++- docs/progress.md | 7 +++ 4 files changed, 105 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index 0c8465721ac0..25dece01a7d1 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -40,6 +40,7 @@ import { ComboboxItem, ComboboxListVirtualized, } from "../ui/combobox"; +import { autoLevelsFirst, withPinnedAutoLevels } from "./ProviderModelPicker.logic"; import { ModelEsque } from "./providerIconUtils"; import { isAutoModelSlug } from "@t3tools/shared/autoModel"; import type { AutoRoute } from "./autoRoute"; @@ -371,7 +372,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes this picker's mount to global keydown handlers useLayoutEffect(() => registerModelPickerContent(), []); const highlightedModelKeyRef = useRef(null); - const { favorites } = useEnvironmentModelPreferences(props.environmentId); + const { favorites: savedFavorites } = useEnvironmentModelPreferences(props.environmentId); + const favorites = withPinnedAutoLevels(savedFavorites, instanceEntries, modelOptionsByInstance); const activeEntry = props.instanceEntries.find( (entry) => entry.instanceId === props.activeInstanceId, ); @@ -677,11 +679,12 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { result = result.filter((m) => m.instanceId === selectedInstanceId); } - return sortProviderModelItems(result, { + const sorted = sortProviderModelItems(result, { favoriteModelKeys: favoritesSet, groupFavorites: selectedInstanceId !== "favorites", instanceOrder: selectedInstanceId === "favorites" ? instanceOrder : [], }); + return selectedInstanceId === "favorites" ? autoLevelsFirst(sorted) : sorted; })(); const legacySection = (() => { diff --git a/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts b/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts index 7602a362d30c..988c683990f0 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts +++ b/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts @@ -1,7 +1,11 @@ -import { ProviderDriverKind } from "@t3tools/contracts"; +import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { retainedModelWhileProviderLocked } from "./ProviderModelPicker.logic"; +import { + autoLevelsFirst, + retainedModelWhileProviderLocked, + withPinnedAutoLevels, +} from "./ProviderModelPicker.logic"; const claude = ProviderDriverKind.make("claudeAgent"); const opus = { slug: "claude-opus-5-5", name: "Claude Opus 5.5", shortName: "Opus 5.5" }; @@ -18,3 +22,54 @@ describe("retainedModelWhileProviderLocked", () => { expect(retainedModelWhileProviderLocked(null, opus.slug)).toBeUndefined(); }); }); + +describe("withPinnedAutoLevels", () => { + const id = (value: string) => ProviderInstanceId.make(value); + const autoRows = ["auto-low", "auto-medium", "auto-high"].map((slug) => ({ slug })); + const entries = [ + { instanceId: id("codex"), driverKind: ProviderDriverKind.make("codex") }, + { instanceId: id("claudeAgent"), driverKind: claude }, + { instanceId: id("claudeAgent_2"), driverKind: claude }, + ]; + const options = new Map([ + [id("codex"), [{ slug: "gpt-6-luna" }]], + [id("claudeAgent"), [...autoRows, opus]], + [id("claudeAgent_2"), [...autoRows, opus]], + ]); + const saved = [{ provider: id("codex"), model: "gpt-6-luna" }]; + + it("pins the first Claude instance's Auto levels above saved favorites", () => { + expect(withPinnedAutoLevels(saved, entries, options)).toEqual([ + { provider: "claudeAgent", model: "auto-high" }, + { provider: "claudeAgent", model: "auto-medium" }, + { provider: "claudeAgent", model: "auto-low" }, + ...saved, + ]); + }); + + it("keeps the user's own choice once any Auto level is starred", () => { + const own = [{ provider: id("claudeAgent_2"), model: "auto-low" }, ...saved]; + expect(withPinnedAutoLevels(own, entries, options)).toBe(own); + }); + + it("changes nothing when no Claude instance lists the Auto levels", () => { + expect(withPinnedAutoLevels(saved, entries.slice(0, 1), options)).toBe(saved); + }); +}); + +describe("autoLevelsFirst", () => { + it("puts Auto High, Medium and Low ahead of other favorites, keeping the rest in order", () => { + const items = ["gpt-6-luna", "auto-low", "grok-4.7", "auto-high", "auto-medium"].map( + (slug) => ({ + slug, + }), + ); + expect(autoLevelsFirst(items).map((item) => item.slug)).toEqual([ + "auto-high", + "auto-medium", + "auto-low", + "gpt-6-luna", + "grok-4.7", + ]); + }); +}); diff --git a/apps/web/src/components/chat/ProviderModelPicker.logic.ts b/apps/web/src/components/chat/ProviderModelPicker.logic.ts index dd3d6871e7c2..f33cbae9e006 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.logic.ts +++ b/apps/web/src/components/chat/ProviderModelPicker.logic.ts @@ -1,7 +1,10 @@ -import type { ProviderDriverKind } from "@t3tools/contracts"; +import type { ModelFavorite, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; +import { AUTO_LEVEL_MODELS, isAutoModelSlug } from "@t3tools/shared/autoModel"; import type { ModelEsque } from "./providerIconUtils"; +type Favorite = typeof ModelFavorite.Type; + /** Keeps a hidden model visible while its provider is locked or turned off. */ export function retainedModelWhileProviderLocked( entry: { @@ -16,3 +19,35 @@ export function retainedModelWhileProviderLocked( if (entry.driverKind === "opencode" || entry.driverKind === "antigravity") return undefined; return entry.models.find((candidate) => candidate.slug === model) ?? { slug: model, name: model }; } + +/** + * Auto High, Medium and Low lead Favorites on every machine, from the first Claude instance that + * lists them, until the user stars an Auto level themselves. + */ +export function withPinnedAutoLevels( + favorites: ReadonlyArray, + entries: ReadonlyArray<{ + readonly instanceId: ProviderInstanceId; + readonly driverKind: ProviderDriverKind; + }>, + optionsByInstance: ReadonlyMap>, +): ReadonlyArray { + if (favorites.some((favorite) => isAutoModelSlug(favorite.model))) return favorites; + const levels = AUTO_LEVEL_MODELS.map((model) => model.slug).reverse(); + const host = entries.find( + (entry) => + entry.driverKind === "claudeAgent" && + levels.every((slug) => + (optionsByInstance.get(entry.instanceId) ?? []).some((option) => option.slug === slug), + ), + ); + if (!host) return favorites; + return [...levels.map((model) => ({ provider: host.instanceId, model })), ...favorites]; +} + +/** Favorites view order: Auto High, Medium, Low first, then the rest as sorted. */ +export function autoLevelsFirst(items: ReadonlyArray): T[] { + const levels = AUTO_LEVEL_MODELS.map((model) => model.slug).reverse(); + const auto = levels.flatMap((slug) => items.filter((item) => item.slug === slug)); + return [...auto, ...items.filter((item) => !levels.includes(item.slug))]; +} diff --git a/docs/progress.md b/docs/progress.md index 22b8a6855e87..a7a0b2a2b48b 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -45,3 +45,10 @@ - Why: preferring the emptier account started both 5-hour windows at the same time, so both ran out together. Staggered windows let one refresh while the other is in use. - Numbers: 11 routing tests (3 new), a mutation check (dropping the 90% rule fails 3 tests). - Next: watch real routing on the hub for a day of use. + +## 2026-11-13: Auto levels on every machine + +- What: every Claude provider on a fork server lists Auto Low, Medium and High as built-in models, so Auto needs no settings. The model picker pins the three levels at the top of Favorites, from the first Claude instance that lists them, until the user stars an Auto level themselves. +- Why: Tomáš wants Auto in every thread, including threads that run on his PC's own T3 server, which has none of the hub's settings. +- Numbers: 1 new server test, 3 new picker tests; server and web typecheck clean (6 min and 62 s on the hub). +- Next: Tomáš builds the fork desktop app on his PC; Auto there routes only to the providers logged in on that PC. From dcf72d2b3b804d491cd492260cde2b86531e6fd3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 14 Nov 2026 11:32:21 +0100 Subject: [PATCH 029/230] fix(shared): Auto routes to the instances that carry the Auto prompt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since every Claude provider lists the Auto levels (#6), "lists an Auto model" no longer marks the instances launched with the Auto-mode prompt (Auto, Auto B). The plain Claude instance shares their account and usage and comes first in the registry, so Auto routed turns to it and the orchestrator never got the routing instructions. Instances whose display name starts with "Auto" now win the tie. The unused `auto` custom-model descriptor goes with the old check. Origin: Tomáš reported that Auto model routing does not work. --- docs/progress.md | 7 +++++++ packages/shared/src/autoModel.test.ts | 21 ++++++++++----------- packages/shared/src/autoModel.ts | 20 +++++--------------- 3 files changed, 22 insertions(+), 26 deletions(-) diff --git a/docs/progress.md b/docs/progress.md index a7a0b2a2b48b..3aa0ddb5c309 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -52,3 +52,10 @@ - Why: Tomáš wants Auto in every thread, including threads that run on his PC's own T3 server, which has none of the hub's settings. - Numbers: 1 new server test, 3 new picker tests; server and web typecheck clean (6 min and 62 s on the hub). - Next: Tomáš builds the fork desktop app on his PC; Auto there routes only to the providers logged in on that PC. + +## 2026-11-14: Auto routes to the Auto instances again; fork synced with upstream for hub2 + +- What: Auto prefers instances named "Auto…" (the ones launched with `auto-mode.md`) when accounts tie. The fork merged upstream main (653 commits, no conflicts) and runs on hub2 from `~/projects/t3code-auto`. +- Why: since every Claude provider lists the Auto levels (#6), the old "lists an Auto model" check matched every Claude instance. Plain `claudeAgent` shares account A's usage with `claudeAuto` and comes first in the registry, so Auto sent turns to it and the orchestrator never got the routing prompt. hub2 ran upstream nightly (DB schema 89); the fork stopped at 85, so it could not run there. +- Numbers: autoModel 12/12 (the same-account case failed before the fix), ClaudeProvider + ProviderRegistry 80/80, web Auto tests 7/7; typecheck of contracts, shared, server and web clean (21 s server on hub2). Fork build 59 s on hub2. +- Next: link hub and deploy the same branch there; rebuild the desktop app on the PC. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index ecd8389c4ba3..d18bef35e2f7 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { AUTO_LEVEL_DESCRIPTOR, isAutoModelSlug, resolveAutoModelSelection } from "./autoModel.ts"; +import { AUTO_LEVEL_MODELS, isAutoModelSlug, resolveAutoModelSelection } from "./autoModel.ts"; const now = Date.parse("2026-11-12T12:00:00.000Z"); const resetsAt = "2026-11-12T15:00:00.000Z"; @@ -26,6 +26,7 @@ function claude(id: string, usedPercent: number, autoAware = true): ServerProvid return { instanceId: ProviderInstanceId.make(id), driver: ProviderDriverKind.make("claudeAgent"), + ...(autoAware ? { displayName: id.endsWith("B") ? "Auto B" : "Auto" } : {}), enabled: true, installed: true, version: null, @@ -39,16 +40,8 @@ function claude(id: string, usedPercent: number, autoAware = true): ServerProvid isCustom: false, capabilities: effortCapabilities, })), - ...(autoAware - ? [ - { - slug: "auto", - name: "Auto", - isCustom: true, - capabilities: { optionDescriptors: [AUTO_LEVEL_DESCRIPTOR] }, - }, - ] - : []), + // Every Claude provider lists the Auto levels; only "Auto" instances carry the Auto prompt. + ...AUTO_LEVEL_MODELS.map((model) => ({ ...model, isCustom: false, capabilities: {} })), ], slashCommands: [], skills: [], @@ -104,6 +97,12 @@ describe("resolveAutoModelSelection", () => { resolveAutoModelSelection({ selection: auto("medium"), providers, now })?.selection .instanceId, ).toBe("claudeAutoB"); + // Same account, so same usage: the plain instance comes first in the registry. + const sameAccount = [claude("claudeAgent", 20, false), claude("claudeAuto", 20)]; + expect( + resolveAutoModelSelection({ selection: auto("medium"), providers: sameAccount, now }) + ?.selection.instanceId, + ).toBe("claudeAuto"); }); it("keeps the thread's current model until it passes 90% used", () => { diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 312468f38d01..87278cc6c7c9 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -2,7 +2,6 @@ import { isProviderAvailable, type ModelSelection, type ProviderDriverKind, - type ProviderOptionDescriptor, type ServerProvider, } from "@t3tools/contracts"; @@ -131,18 +130,6 @@ function autoLevelOf(selection: ModelSelection): AutoLevel { return AUTO_LEVELS.find((level) => level === value) ?? DEFAULT_LEVEL; } -/** The `effort` descriptor an `auto` custom model declares, so pickers show Low/Medium/High. */ -export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { - id: "effort", - label: "Auto level", - type: "select", - options: [ - { id: "low", label: "Low", description: "Sonnet orchestrates; cheaper models do more" }, - { id: "medium", label: "Medium", description: "Opus orchestrates", isDefault: true }, - { id: "high", label: "High", description: "Fable orchestrates" }, - ], -}; - /** Accounts whose 5-hour use differs by less than this many points count as equally far along. */ const SESSION_BAND_PERCENT = 10; @@ -187,9 +174,12 @@ function peakUsedPercent(provider: ServerProvider): number { return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); } -/** Instances that list the `auto` model carry the Auto-mode prompt, so they win ties. */ +/** + * Instances named "Auto…" carry the Auto-mode prompt (their launch args), so they win ties. Every + * Claude provider lists the Auto levels, so listing them says nothing about the prompt. + */ function isAutoAware(provider: ServerProvider): boolean { - return provider.models.some((model) => isAutoModelSlug(model.slug)); + return /^auto\b/i.test(provider.displayName ?? ""); } function usable(provider: ServerProvider, model: string, now: number): boolean { From ed4f09336516cfe04bf6c7f0e8216afb936de419 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 14 Nov 2026 11:55:50 +0100 Subject: [PATCH 030/230] fix(client): an Auto thread no longer shows a pending context handoff MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After the first message on Auto, the thread runs on the model Auto chose (for example Auto B / Sonnet), while the composer still holds the Auto selection on the instance it was picked from. The pending-handoff check compared the two and showed "Context handoff pending" after every turn, although the server keeps the thread's model while it fits. The check now resolves an Auto selection the way the server does, so it only shows a handoff when Auto would really move the thread to another account. Web and mobile share the check; callers pass the current minute. Origin: found while checking Auto in the real hub2 web UI for Tomáš. --- .../src/state/use-thread-composer-state.ts | 3 +- apps/web/src/components/ChatView.tsx | 1 + docs/progress.md | 7 +++ packages/client-runtime/src/handoff.test.ts | 55 +++++++++++++++---- packages/client-runtime/src/handoff.ts | 14 +++++ .../client-runtime/src/state/contextWindow.ts | 3 +- 6 files changed, 70 insertions(+), 13 deletions(-) diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 579653502958..8b0bae86ce7c 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -321,12 +321,14 @@ export function useThreadComposerState(input: { const selectedThread = selectedThreadShell; const modelSelection = selectedDraft.modelSelection ?? selectedThread?.modelSelection ?? null; const serverConfig = selectedEnvironmentRuntime?.serverConfig; + const nowMinuteMs = useNowMinuteMs(); const pendingHandoff = resolvePendingHandoff( selectedThreadProjection?.projection, isModelSelectionUnavailable(serverConfig, modelSelection, selectedThread?.projectId ?? null) ? null : modelSelection, serverConfig?.providers ?? [], + nowMinuteMs, ); const runtimeMode = selectedDraft.runtimeMode ?? selectedThread?.runtimeMode ?? null; // Plan mode is not offered to users; every send runs in build mode. @@ -447,7 +449,6 @@ export function useThreadComposerState(input: { now, }) : null; - const nowMinuteMs = useNowMinuteMs(); const compactTokens = selectedDraft.freshContext === true ? null diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index fbec56205975..6a5625ffd942 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2506,6 +2506,7 @@ export default function ChatView(props: ChatViewProps) { serverProjection, pendingHandoffSelectionUsable ? pendingHandoffSelection : null, providerStatuses, + Date.parse(`${nowMinute}:00Z`), ); const compactThreadUnavailable = !canOperateThread || diff --git a/docs/progress.md b/docs/progress.md index 3aa0ddb5c309..b084970a4e8a 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -59,3 +59,10 @@ - Why: since every Claude provider lists the Auto levels (#6), the old "lists an Auto model" check matched every Claude instance. Plain `claudeAgent` shares account A's usage with `claudeAuto` and comes first in the registry, so Auto sent turns to it and the orchestrator never got the routing prompt. hub2 ran upstream nightly (DB schema 89); the fork stopped at 85, so it could not run there. - Numbers: autoModel 12/12 (the same-account case failed before the fix), ClaudeProvider + ProviderRegistry 80/80, web Auto tests 7/7; typecheck of contracts, shared, server and web clean (21 s server on hub2). Fork build 59 s on hub2. - Next: link hub and deploy the same branch there; rebuild the desktop app on the PC. + +## 2026-11-14: Auto threads stop showing a false "Context handoff pending" + +- What: the shared pending-handoff check (web and mobile) resolves an Auto selection the way the server does, keeping the thread's current model while it fits, before deciding a handoff is coming. +- Why: in the real hub2 UI, every Auto thread showed "Context handoff pending: Sonnet 5.5 (AB) → Auto Low (CL)" after each turn, while the server log showed the next message stay on `claudeAutoB` (sticky). +- Numbers: handoff + contextWindow tests 39/39 (the new case failed before); client-runtime, web and mobile typecheck clean. Deployed on hub2 as a web-only build (51 s), no restart. +- Next: link hub and run the same checks there; rebuild the PC desktop app. diff --git a/packages/client-runtime/src/handoff.test.ts b/packages/client-runtime/src/handoff.test.ts index d2f5fb4e7890..071aa10fccd1 100644 --- a/packages/client-runtime/src/handoff.test.ts +++ b/packages/client-runtime/src/handoff.test.ts @@ -87,6 +87,8 @@ const projection = { visibleTurnItems: [{ item: { type: "user_message" } }], } as unknown as OrchestrationV2ThreadProjection; +const now = Date.parse("2026-11-14T12:00:00.000Z"); + describe("pending context handoff", () => { it("removes the preview while the handoff starts", () => { const selection = { instanceId: to, model: "destination" }; @@ -105,10 +107,10 @@ describe("pending context handoff", () => { ], }; - expect(resolvePendingHandoff(projection, selection, providers)).not.toBeNull(); - expect(resolvePendingHandoff(starting, selection, providers)).toBeNull(); + expect(resolvePendingHandoff(projection, selection, providers, now)).not.toBeNull(); + expect(resolvePendingHandoff(starting, selection, providers, now)).toBeNull(); expect( - resolvePendingHandoff(starting, { instanceId: from, model: "source" }, providers), + resolvePendingHandoff(starting, { instanceId: from, model: "source" }, providers, now), ).toEqual({ from: [selection], to: { instanceId: from, model: "source" }, @@ -133,7 +135,7 @@ describe("pending context handoff", () => { ], }; - expect(resolvePendingHandoff(unstarted, selection, [])).toEqual({ + expect(resolvePendingHandoff(unstarted, selection, [], now)).toEqual({ from: [{ instanceId: from, model: "source" }], to: selection, }); @@ -141,28 +143,59 @@ describe("pending context handoff", () => { ); it("appears on selection, updates the destination, and disappears on returning", () => { - expect(resolvePendingHandoff(projection, { instanceId: to, model: "first" }, [])).toEqual({ + expect(resolvePendingHandoff(projection, { instanceId: to, model: "first" }, [], now)).toEqual({ from: [{ instanceId: from, model: "source" }], to: { instanceId: to, model: "first" }, }); expect( - resolvePendingHandoff(projection, { instanceId: to, model: "second" }, [])?.to.model, + resolvePendingHandoff(projection, { instanceId: to, model: "second" }, [], now)?.to.model, ).toBe("second"); - expect(resolvePendingHandoff(projection, { instanceId: from, model: "source" }, [])).toBeNull(); - expect(resolvePendingHandoff(projection, { instanceId: from, model: "other" }, [])).toBeNull(); + expect( + resolvePendingHandoff(projection, { instanceId: from, model: "source" }, [], now), + ).toBeNull(); + expect( + resolvePendingHandoff(projection, { instanceId: from, model: "other" }, [], now), + ).toBeNull(); }); it("stays hidden while the thread's timeline is empty", () => { const empty = { ...projection, visibleTurnItems: [] }; - expect(resolvePendingHandoff(empty, { instanceId: to, model: "first" }, [])).toBeNull(); + expect(resolvePendingHandoff(empty, { instanceId: to, model: "first" }, [], now)).toBeNull(); // Paging can leave a window of only tool rows after the prompt. const toolRowsOnly = { ...projection, visibleTurnItems: [{ item: { type: "command_execution" } }], } as unknown as OrchestrationV2ThreadProjection; expect( - resolvePendingHandoff(toolRowsOnly, { instanceId: to, model: "first" }, [])?.to.model, + resolvePendingHandoff(toolRowsOnly, { instanceId: to, model: "first" }, [], now)?.to.model, ).toBe("first"); }); + it("previews an Auto selection as the model Auto keeps, not as a handoff", () => { + const autoB = ProviderInstanceId.make("claudeAutoB"); + const onAutoB = { + ...projection, + runs: [{ ...projection.runs[0]!, ...run("source", 1, autoB, "claude-sonnet-5-5") }], + } as unknown as OrchestrationV2ThreadProjection; + const claude = (instanceId: ProviderInstanceId, usedPercent: number) => + ({ + instanceId, + driver: "claudeAgent", + enabled: true, + installed: true, + status: "ready", + auth: { status: "authenticated" }, + models: [{ slug: "claude-sonnet-5-5", capabilities: { optionDescriptors: [] } }], + usageLimits: { windows: [{ kind: "session", usedPercent }] }, + }) as unknown as ServerProvider; + const autoLow = { instanceId: to, model: "auto-low" }; + + expect( + resolvePendingHandoff(onAutoB, autoLow, [claude(to, 0), claude(autoB, 20)], now), + ).toBeNull(); + // Past 90% Auto moves the thread to the other account, so the handoff is real. + expect( + resolvePendingHandoff(onAutoB, autoLow, [claude(to, 0), claude(autoB, 95)], now)?.to, + ).toMatchObject({ instanceId: to, model: "claude-sonnet-5-5" }); + }); it("resumes compatible account overlays without showing a handoff", () => { const providers = [from, to].map((instanceId) => ({ instanceId, @@ -170,7 +203,7 @@ describe("pending context handoff", () => { continuation: { groupKey: "shared" }, })) as unknown as ServerProvider[]; expect( - resolvePendingHandoff(projection, { instanceId: to, model: "target" }, providers), + resolvePendingHandoff(projection, { instanceId: to, model: "target" }, providers, now), ).toBeNull(); }); }); diff --git a/packages/client-runtime/src/handoff.ts b/packages/client-runtime/src/handoff.ts index 48a122742931..d8057f946ece 100644 --- a/packages/client-runtime/src/handoff.ts +++ b/packages/client-runtime/src/handoff.ts @@ -11,6 +11,7 @@ import { getModelSelectionStringOptionValue, getProviderOptionCurrentValue, } from "@t3tools/shared/model"; +import { isAutoModelSelection, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; import { isReasoningSelect } from "./modelTraits.ts"; import type { ThreadStructure } from "./state/models.ts"; @@ -27,6 +28,7 @@ export function resolvePendingHandoff( projection: Pick | null | undefined, selection: ModelSelection | null | undefined, providers: ReadonlyArray, + now: number, ): HandoffEndpoints | null { // A thread with an empty timeline has nothing to hand off. Any loaded row // counts: paging can leave a window of only tool rows. @@ -39,6 +41,18 @@ export function resolvePendingHandoff( (run.startedAt !== null || (run.status === "starting" && run.contextHandoffId !== null)), )?.modelSelection; if (from === undefined || selection == null) return null; + // The server swaps Auto for a concrete model per message, keeping the current one while it fits. + if (isAutoModelSelection(selection)) { + const route = resolveAutoModelSelection({ + selection, + providers, + now, + current: from, + }); + return route === null + ? null + : resolvePendingHandoff(projection, route.selection, providers, now); + } const source = providers.find((provider) => provider.instanceId === from.instanceId); const target = providers.find((provider) => provider.instanceId === selection.instanceId); const needsHandoff = diff --git a/packages/client-runtime/src/state/contextWindow.ts b/packages/client-runtime/src/state/contextWindow.ts index a8f7e0f88c35..3a877ea87ba4 100644 --- a/packages/client-runtime/src/state/contextWindow.ts +++ b/packages/client-runtime/src/state/contextWindow.ts @@ -281,7 +281,8 @@ export function compactBeforeSendTokens(input: { COMPACT_COMMAND_PATTERN.test(input.text) || resolveIdleCompaction(input.settings, provider.instanceId) === "off" || !provider.slashCommands.some((command) => command.name === "compact") || - resolvePendingHandoff(projection, input.selection, input.providers) !== null || + resolvePendingHandoff(projection, input.selection, input.providers, Date.parse(input.now)) !== + null || projection.runtimeRequests.some((request) => request.status === "pending") || projection.runs.some((run) => run.status === "queued" && run.queueHeld === true) || (!input.visibleTurnItems.some( From e7e18345c11bc65636fb48a94579a87d752c418d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 14 Nov 2026 12:05:51 +0100 Subject: [PATCH 031/230] feat: threads routed by Auto stay on Auto MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The server replaces Auto with a concrete model per message and stored only that, so after the first message every client showed "Sonnet 5.5 Low" instead of "Auto Low", and a client without the fork's composer kept sending the concrete model, which ended Auto routing for the thread. The model Auto picks now carries an `auto` option with its level. The server treats such a selection as Auto again on the next command (sticky while it fits), and web and mobile show it in the composer as the Auto level it came from. The pending-handoff preview only re-resolves Auto level slugs, so a routed selection does not recurse. Origin: Tomáš saw "Sonnet 5.5 Low" instead of Auto in a thread started on Auto Low. --- .../src/state/use-thread-composer-state.ts | 4 +- apps/web/src/components/ChatView.tsx | 5 +- docs/progress.md | 8 +++ packages/client-runtime/src/handoff.ts | 4 +- packages/shared/src/autoModel.test.ts | 59 +++++++++++++++---- packages/shared/src/autoModel.ts | 38 +++++++++--- 6 files changed, 97 insertions(+), 21 deletions(-) diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 8b0bae86ce7c..5e2202e4d037 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -8,6 +8,7 @@ import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell"; import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; import { threadSteersDuringCompaction } from "@t3tools/client-runtime/state/thread-workflows"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; +import { autoLevelSelection } from "@t3tools/shared/autoModel"; import { announcedRun, isDetailBehindShell, @@ -319,7 +320,8 @@ export function useThreadComposerState(input: { const selectedDraft = useComposerDraftSettings(selectedThreadKey); const selectedThreadQueueCount = selectedThreadQueuedMessages.length; const selectedThread = selectedThreadShell; - const modelSelection = selectedDraft.modelSelection ?? selectedThread?.modelSelection ?? null; + const modelSelection = + selectedDraft.modelSelection ?? autoLevelSelection(selectedThread?.modelSelection) ?? null; const serverConfig = selectedEnvironmentRuntime?.serverConfig; const nowMinuteMs = useNowMinuteMs(); const pendingHandoff = resolvePendingHandoff( diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 6a5625ffd942..3da91a52aba9 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2,6 +2,7 @@ import { ChildThreadApprovals } from "./chat/ChildThreadApprovals"; import { workspaceAreaProps } from "../lib/workspaceFocus"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; +import { autoLevelSelection } from "@t3tools/shared/autoModel"; import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-edit"; import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOverlays"; import { usePasteToFocusComposer } from "./chat/usePasteToFocusComposer"; @@ -3720,7 +3721,9 @@ export default function ChatView(props: ChatViewProps) { activeProjectDefaultModelSelection={ activeProjectDefaultModelSelection } - activeThreadModelSelection={activeThread?.modelSelection} + activeThreadModelSelection={autoLevelSelection( + activeThread?.modelSelection, + )} activeProjectId={activeProject?.id ?? null} projectName={activeProject?.title} compactThreadUnavailable={compactThreadUnavailable} diff --git a/docs/progress.md b/docs/progress.md index b084970a4e8a..1db4eaeb2169 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -66,3 +66,11 @@ - Why: in the real hub2 UI, every Auto thread showed "Context handoff pending: Sonnet 5.5 (AB) → Auto Low (CL)" after each turn, while the server log showed the next message stay on `claudeAutoB` (sticky). - Numbers: handoff + contextWindow tests 39/39 (the new case failed before); client-runtime, web and mobile typecheck clean. Deployed on hub2 as a web-only build (51 s), no restart. - Next: link hub and run the same checks there; rebuild the PC desktop app. + +## 2026-11-14: Threads routed by Auto stay on Auto + +- What: the model Auto picks carries an `auto` option with its level. The server treats it as Auto on the next command (sticky while under 90%), and web and mobile show the thread's composer as "Auto Low · now Sonnet 5.5 (B)" instead of "Sonnet 5.5 Low". +- Why: Tomáš saw "Sonnet 5.5 Low" in a thread started on Auto Low. The server stored only the concrete model, so Auto showed only where a local draft remembered it, and clients without the fork's composer sent the concrete model, ending Auto for that thread. +- Numbers: autoModel 12/12, handoff + contextWindow 39/39 (a recursion the stamp caused was caught by the handoff test); shared, client-runtime, web, mobile and server typecheck clean. Checked in a clean incognito browser on a scratch copy of hub2's data: a thread started on Auto Low over the CLI shows Auto Low in the composer. +- Deploy: service now runs from `~/.t3/fork-current` (a symlink to the deploy checkout), so a new build goes into a fresh checkout and the restart flips the link. +- Next: hub (link it first) and a fork build of the PC desktop app; the stock app still shows the concrete model. diff --git a/packages/client-runtime/src/handoff.ts b/packages/client-runtime/src/handoff.ts index d8057f946ece..1ca0c09ed50e 100644 --- a/packages/client-runtime/src/handoff.ts +++ b/packages/client-runtime/src/handoff.ts @@ -11,7 +11,7 @@ import { getModelSelectionStringOptionValue, getProviderOptionCurrentValue, } from "@t3tools/shared/model"; -import { isAutoModelSelection, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; +import { isAutoModelSlug, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; import { isReasoningSelect } from "./modelTraits.ts"; import type { ThreadStructure } from "./state/models.ts"; @@ -42,7 +42,7 @@ export function resolvePendingHandoff( )?.modelSelection; if (from === undefined || selection == null) return null; // The server swaps Auto for a concrete model per message, keeping the current one while it fits. - if (isAutoModelSelection(selection)) { + if (isAutoModelSlug(selection.model)) { const route = resolveAutoModelSelection({ selection, providers, diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index d18bef35e2f7..e3b6e708f89d 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -6,7 +6,13 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { AUTO_LEVEL_MODELS, isAutoModelSlug, resolveAutoModelSelection } from "./autoModel.ts"; +import { + AUTO_LEVEL_MODELS, + autoLevelSelection, + isAutoModelSelection, + isAutoModelSlug, + resolveAutoModelSelection, +} from "./autoModel.ts"; const now = Date.parse("2026-11-12T12:00:00.000Z"); const resetsAt = "2026-11-12T15:00:00.000Z"; @@ -77,7 +83,10 @@ describe("resolveAutoModelSelection", () => { ).toEqual({ instanceId: "claudeAuto", model: "claude-fable-5-2", - options: [{ id: "effort", value: "high" }], + options: [ + { id: "effort", value: "high" }, + { id: "auto", value: "high" }, + ], }); expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.model).toBe( "claude-opus-5-5", @@ -87,7 +96,10 @@ describe("resolveAutoModelSelection", () => { ).toEqual({ instanceId: "claudeAuto", model: "claude-sonnet-5-5", - options: [{ id: "effort", value: "low" }], + options: [ + { id: "effort", value: "low" }, + { id: "auto", value: "low" }, + ], }); }); @@ -126,7 +138,9 @@ describe("resolveAutoModelSelection", () => { usageLimits: undefined, } as unknown as ServerProvider; const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100), grok]; - expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection).toEqual({ + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection, + ).toMatchObject({ instanceId: "grok", model: "grok-4.7", }); @@ -199,10 +213,15 @@ describe("resolveAutoModelSelection", () => { })), } as unknown as ServerProvider; const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100), antigravity]; - expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection).toEqual({ + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection, + ).toMatchObject({ instanceId: "antigravity", model: "claude-opus-4-6-thinking", - options: [{ id: "thinking_level", value: "medium" }], + options: [ + { id: "thinking_level", value: "medium" }, + { id: "auto", value: "medium" }, + ], }); }); @@ -237,16 +256,22 @@ describe("resolveAutoModelSelection", () => { const route = (providers: ServerProvider[]) => resolveAutoModelSelection({ selection: auto("high"), providers, now })?.selection; - expect(route([...claudeOut, gemini, grok, codex])).toEqual({ + expect(route([...claudeOut, gemini, grok, codex])).toMatchObject({ instanceId: "codex", model: "gpt-6-luna", - options: [{ id: "reasoningEffort", value: "high" }], + options: [ + { id: "reasoningEffort", value: "high" }, + { id: "auto", value: "high" }, + ], }); expect(route([...claudeOut, gemini, grok])?.instanceId).toBe("grok"); - expect(route([...claudeOut, gemini])).toEqual({ + expect(route([...claudeOut, gemini])).toMatchObject({ instanceId: "antigravity", model: "gemini-3.8-flash", - options: [{ id: "thinking_level", value: "high" }], + options: [ + { id: "thinking_level", value: "high" }, + { id: "auto", value: "high" }, + ], }); }); @@ -263,6 +288,20 @@ describe("resolveAutoModelSelection", () => { expect(pick("auto-low")).toBe("claude-sonnet-5-5"); expect(isAutoModelSlug("auto-low")).toBe(true); expect(isAutoModelSlug("auto-max")).toBe(false); + + // The routed model keeps its level, so the thread stays on Auto and clients show it. + const routed = resolveAutoModelSelection({ + selection: auto("low"), + providers, + now, + })!.selection; + expect(isAutoModelSelection(routed)).toBe(true); + expect(autoLevelSelection(routed)).toEqual({ instanceId: "claudeAuto", model: "auto-low" }); + expect( + resolveAutoModelSelection({ selection: routed, providers, now, current: routed }), + ).toMatchObject({ sticky: true, level: "low", selection: routed }); + const plain = { instanceId: ProviderInstanceId.make("claudeAuto"), model: "claude-opus-5-5" }; + expect(autoLevelSelection(plain)).toBe(plain); }); it("returns null when nothing is usable", () => { diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 87278cc6c7c9..74519c6e38e5 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -13,6 +13,8 @@ import { exhaustedUsageWindow } from "./usageLimits.ts"; * live usage limits. The level (`low` | `medium` | `high`) rides in the `effort` option. */ const AUTO_MODEL_SLUG = "auto"; +/** Stamped on the model Auto picks, holding the level, so the thread stays on Auto. */ +const AUTO_OPTION_ID = "auto"; const AUTO_LEVELS = ["low", "medium", "high"] as const; type AutoLevel = (typeof AUTO_LEVELS)[number]; const DEFAULT_LEVEL: AutoLevel = "medium"; @@ -119,11 +121,28 @@ export const AUTO_LEVEL_MODELS: ReadonlyArray<{ readonly slug: string; readonly name: `Auto ${level[0]!.toUpperCase()}${level.slice(1)}`, })); +function stampedLevel(selection: ModelSelection | null | undefined): AutoLevel | undefined { + const value = selection?.options?.find((option) => option.id === AUTO_OPTION_ID)?.value; + return AUTO_LEVELS.find((level) => level === value); +} + export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { - return isAutoModelSlug(selection?.model); + return isAutoModelSlug(selection?.model) || stampedLevel(selection) !== undefined; +} + +/** A routed thread's model as the Auto level it came from, for pickers; others unchanged. */ +export function autoLevelSelection( + selection: T, +): T | ModelSelection { + const level = stampedLevel(selection); + return selection && level + ? { instanceId: selection.instanceId, model: `${AUTO_MODEL_SLUG}-${level}` } + : selection; } function autoLevelOf(selection: ModelSelection): AutoLevel { + const stamped = stampedLevel(selection); + if (stamped) return stamped; const fixed = AUTO_LEVELS.find((level) => selection.model === `${AUTO_MODEL_SLUG}-${level}`); if (fixed) return fixed; const value = selection.options?.find((option) => option.id === "effort")?.value; @@ -204,12 +223,15 @@ function effortOptions(provider: ServerProvider, candidate: AutoCandidate) { : undefined; } -function toSelection(provider: ServerProvider, candidate: AutoCandidate): ModelSelection { - const options = effortOptions(provider, candidate); +function toSelection( + provider: ServerProvider, + candidate: AutoCandidate, + level: AutoLevel, +): ModelSelection { return { instanceId: provider.instanceId, model: candidate.model, - ...(options ? { options } : {}), + options: [...(effortOptions(provider, candidate) ?? []), { id: AUTO_OPTION_ID, value: level }], }; } @@ -235,7 +257,7 @@ export function resolveAutoModelSelection(input: { const candidates = AUTO_CANDIDATES[level]; const current = input.current; - if (current && !isAutoModelSelection(current)) { + if (current && !isAutoModelSlug(current.model)) { const provider = input.providers.find((entry) => entry.instanceId === current.instanceId); const candidate = candidates.find( (entry) => entry.driver === provider?.driver && entry.model === current.model, @@ -246,7 +268,7 @@ export function resolveAutoModelSelection(input: { usable(provider, candidate.model, input.now) && peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT ) { - return { selection: toSelection(provider, candidate), level, sticky: true }; + return { selection: toSelection(provider, candidate, level), level, sticky: true }; } } @@ -260,7 +282,9 @@ export function resolveAutoModelSelection(input: { // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. .sort(compareInstances); const provider = instances[0]; - if (provider) return { selection: toSelection(provider, candidate), level, sticky: false }; + if (provider) { + return { selection: toSelection(provider, candidate, level), level, sticky: false }; + } } return null; } From 2e0c5948453732b8bf97a1aa4e1e92b62725c294 Mon Sep 17 00:00:00 2001 From: radys-s Date: Sat, 14 Nov 2026 14:16:32 +0100 Subject: [PATCH 032/230] feat(usage): add smart reset credit advice to limits page --- .../components/usage/UsageLimitsPooled.tsx | 42 ++++++- packages/shared/src/usageLimits.test.ts | 103 ++++++++++++++++++ packages/shared/src/usageLimits.ts | 81 ++++++++++++++ 3 files changed, 225 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index 73e6032a229b..7dc73e804f46 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -16,6 +16,7 @@ import { remainingPercent, type ResetCreditChoice, resetCreditChoices, + suggestResetCredit, } from "@t3tools/shared/usageLimits"; import { poolBurn, @@ -144,6 +145,7 @@ function SegmentPopover({ account, window, reset, + poolMembers, now, redeem, onRedeem, @@ -151,6 +153,7 @@ function SegmentPopover({ readonly account: LimitAccount; readonly window: LimitPoolMember["window"]; readonly reset: LimitPoolWindow["resets"][number] | undefined; + readonly poolMembers?: readonly LimitPoolMember[] | undefined; readonly now: number; readonly redeem: ReturnType | null; readonly onRedeem: (choice: ResetCreditChoice) => void; @@ -163,6 +166,7 @@ function SegmentPopover({ account.environments.length > 0 ? account.environments.map((environment) => environment.label).join(", ") : account.sourceLabel; + const suggestion = suggestResetCredit(account, window, poolMembers ?? [{ account, window }], now); const choices = redeem && account.redeem && account.limits.resetCredits?.availableCount ? resetCreditChoices(account.limits.resetCredits, account.redeem.input, now, true) @@ -205,6 +209,26 @@ function SegmentPopover({ +{reset.restoresPercent}% of pool ) : null}
+ {suggestion ? ( +
+
+ + Reset advice: + + {suggestion.actionLabel} + +
+ {suggestion.reason} +
+ ) : null} {choices.length > 0 && redeem ? (
{choices.map((choice) => ( @@ -302,6 +326,7 @@ function PoolSegment({ readonly now: number; readonly index: number; readonly showAccountName: boolean; + readonly poolMembers?: readonly LimitPoolMember[] | undefined; }) { return account.redeem ? ( @@ -343,6 +368,7 @@ function SegmentTriggers({ window, reset, redeem, + poolMembers, refillPercent, color, now, @@ -356,7 +382,7 @@ function SegmentTriggers({ readonly showAccountName: boolean; }) { const popover = use(SegmentPopoverContext) ?? undefined; - const payload: SegmentPayload = { account, window, reset, redeem }; + const payload: SegmentPayload = { account, window, reset, redeem, poolMembers }; const remaining = remainingPercent(window); const timeLeft = paceRemainingPercent(window, now); const [segmentRef, paceMark] = usePaceMark(timeLeft); @@ -534,6 +560,7 @@ function PoolBar({ now={now} index={position + 1} showAccountName={pool.columns.length > 1} + poolMembers={pool.members} /> ) : pool.kind === "monthly" && member.account.limits.zeroSpendCap ? (
+ {(() => { + const advice = pool.members + .filter((m) => m.window && (m.account.limits.resetCredits?.availableCount ?? 0) > 0) + .map((m) => suggestResetCredit(m.account, m.window!, pool.members, now)) + .find(Boolean); + return advice ? ( +
+ + {advice.actionLabel}: + {advice.reason} +
+ ) : null; + })()} {description ?

{description}

: null}
); diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index b66001ca1924..64a11a6da8cc 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -25,6 +25,7 @@ import { paceRemainingPercent, usesChatGptSharing, resolveNewThreadModelSelection, + suggestResetCredit, } from "./usageLimits.ts"; const now = Date.parse("2026-09-03T12:00:00.000Z"); @@ -1837,3 +1838,105 @@ describe("ChatGPT sharing presentation", () => { ).toBe(false); }); }); + +describe("suggestResetCredit advice", () => { + const baseAccount: LimitAccount = { + key: "claude_a", + driver: ProviderDriverKind.make("claudeAgent"), + displayName: "Claude A", + email: undefined, + plan: "Max", + accentColor: undefined, + sourceLabel: "Desk", + environments: [], + limits: { + checkedAt: "2026-09-03T11:00:00.000Z", + windows: [], + resetCredits: { + availableCount: 1, + }, + }, + redeem: null, + }; + + const depletedWindow = { + id: "five_hour", + kind: "session" as const, + label: "Session", + usedPercent: 100, + windowDurationMins: 300, + resetsAt: "2026-09-03T15:00:00.000Z", + }; + + it("returns null when no reset credits are available", () => { + const acc = { + ...baseAccount, + limits: { ...baseAccount.limits, resetCredits: { availableCount: 0 } }, + }; + expect(suggestResetCredit(acc, depletedWindow, [], now)).toBeNull(); + }); + + it("suggests waiting when natural reset is within 45 minutes", () => { + const imminentWindow = { ...depletedWindow, resetsAt: "2026-09-03T12:20:00.000Z" }; // 20 mins from now + const advice = suggestResetCredit(baseAccount, imminentWindow, [], now); + expect(advice?.recommendation).toBe("wait"); + expect(advice?.actionLabel).toBe("Wait for natural reset"); + expect(advice?.reason).toContain("20m"); + }); + + it("suggests saving when account still has >20% remaining", () => { + const healthyWindow = { ...depletedWindow, usedPercent: 40 }; // 60% remaining + const advice = suggestResetCredit(baseAccount, healthyWindow, [], now); + expect(advice?.recommendation).toBe("save"); + expect(advice?.actionLabel).toBe("Save for later"); + }); + + it("suggests holding when another account in pool has healthy quota", () => { + const otherAccount: LimitAccount = { + ...baseAccount, + key: "claude_b", + }; + const otherWindow = { ...depletedWindow, usedPercent: 30 }; // 70% remaining + const advice = suggestResetCredit( + baseAccount, + depletedWindow, + [ + { account: baseAccount, window: depletedWindow }, + { account: otherAccount, window: otherWindow }, + ], + now, + ); + expect(advice?.recommendation).toBe("hold"); + expect(advice?.actionLabel).toContain("Hold off"); + expect(advice?.reason).toContain("70%"); + }); + + it("recommends using reset when depleted and next reset is hours away", () => { + const advice = suggestResetCredit( + baseAccount, + depletedWindow, + [{ account: baseAccount, window: depletedWindow }], + now, + ); + expect(advice?.recommendation).toBe("recommended"); + expect(advice?.actionLabel).toBe("Recommended to use now"); + expect(advice?.reason).toContain("in 3h"); + }); + + it("warns when reset credit expires within 24h", () => { + const expiringAccount: LimitAccount = { + ...baseAccount, + limits: { + ...baseAccount.limits, + resetCredits: { + availableCount: 1, + nextExpiresAt: "2026-09-03T18:00:00.000Z", // 6h from now + }, + }, + }; + const advice = suggestResetCredit(expiringAccount, depletedWindow, [], now); + expect(advice?.recommendation).toBe("expiring_soon"); + expect(advice?.actionLabel).toBe("Use before expiry"); + expect(advice?.reason).toContain("6h"); + }); +}); diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 6fe6c70a89a4..6b10d0278097 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -824,6 +824,87 @@ export function formatResetsIn(window: ServerProviderUsageWindow, now: number): return `resets in ${formatDuration(resetsAt - now)}`; } +export interface ResetCreditSuggestion { + readonly recommendation: "recommended" | "wait" | "save" | "hold" | "expiring_soon"; + readonly actionLabel: string; + readonly reason: string; +} + +export function suggestResetCredit( + account: LimitAccount, + window: ServerProviderUsageWindow, + poolMembers: ReadonlyArray<{ + readonly account: LimitAccount; + readonly window?: ServerProviderUsageWindow | null; + }>, + now: number, +): ResetCreditSuggestion | null { + const credits = account.limits.resetCredits; + if (!credits || credits.availableCount <= 0) return null; + + const remaining = remainingPercent(window); + const resetsAt = resetMillis(window); + const resetsInMs = resetsAt !== null ? resetsAt - now : null; + + // 1. Expiring soon: credit expires within 24 hours + const optionExpiries = (credits.options ?? []) + .filter((opt) => opt.availableCount > 0 && opt.expiresAt) + .map((opt) => Date.parse(opt.expiresAt!)) + .filter(Number.isFinite); + const nextExpires = credits.nextExpiresAt ? Date.parse(credits.nextExpiresAt) : null; + if (nextExpires && Number.isFinite(nextExpires)) { + optionExpiries.push(nextExpires); + } + const soonestExpiry = optionExpiries.length > 0 ? Math.min(...optionExpiries) : null; + if (soonestExpiry !== null) { + const timeUntilExpiry = soonestExpiry - now; + if (timeUntilExpiry > 0 && timeUntilExpiry <= 24 * 3600 * 1000) { + return { + recommendation: "expiring_soon", + actionLabel: "Use before expiry", + reason: `Banked reset credit expires in ${formatDuration(timeUntilExpiry)}. Use it before it expires.`, + }; + } + } + + // 2. Natural reset is imminent (within 45 minutes) + if (resetsInMs !== null && resetsInMs > 0 && resetsInMs <= 45 * 60 * 1000) { + return { + recommendation: "wait", + actionLabel: "Wait for natural reset", + reason: `Window resets naturally in ${formatDuration(resetsInMs)}. Save your banked credit.`, + }; + } + + // 3. This account still has plenty of quota (> 20% remaining) + if (remaining > 20) { + return { + recommendation: "save", + actionLabel: "Save for later", + reason: `${remaining}% quota remaining. Reset only when depleted.`, + }; + } + + // 4. Other account in the same pool has plenty of quota (> 25% remaining) + const otherMembers = poolMembers.filter((m) => m.account.key !== account.key && m.window); + const otherMaxRemaining = + otherMembers.length > 0 ? Math.max(...otherMembers.map((m) => remainingPercent(m.window!))) : 0; + if (otherMaxRemaining > 25) { + return { + recommendation: "hold", + actionLabel: "Hold off (other account active)", + reason: `Auto mode has another account with ${otherMaxRemaining}% quota left. Save credit until both are depleted.`, + }; + } + + // 5. Recommended: Account is depleted and next reset is far away (or not soon) + return { + recommendation: "recommended", + actionLabel: "Recommended to use now", + reason: `Quota depleted and next natural reset is ${resetsInMs !== null && resetsInMs > 0 ? `in ${formatDuration(resetsInMs)}` : "hours away"}. Good time to reset.`, + }; +} + export const USAGE_LIMITS_COMMAND = { name: "usage-limits", description: "Show this provider's usage limits", From 63c32ce307362fa5bc6876e3b36daea217ffdbd9 Mon Sep 17 00:00:00 2001 From: radys-s Date: Sat, 14 Nov 2026 21:37:35 +0100 Subject: [PATCH 033/230] feat(auto): fail over to the next subscription when one hits its limit When a run on an Auto thread fails with a usage limit or no capacity, bench that provider instance and send the thread back through Auto, which skips benched instances, so work continues on the next subscription instead of waiting hours for the reset. --- .../src/orchestration-v2/AutoCooldown.ts | 25 +++ .../AutoFailoverService.test.ts | 107 +++++++++++ .../orchestration-v2/AutoFailoverService.ts | 168 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 5 +- apps/server/src/server.ts | 6 + docs/progress.md | 8 + packages/shared/src/autoModel.test.ts | 18 ++ packages/shared/src/autoModel.ts | 16 +- 8 files changed, 350 insertions(+), 3 deletions(-) create mode 100644 apps/server/src/orchestration-v2/AutoCooldown.ts create mode 100644 apps/server/src/orchestration-v2/AutoFailoverService.test.ts create mode 100644 apps/server/src/orchestration-v2/AutoFailoverService.ts diff --git a/apps/server/src/orchestration-v2/AutoCooldown.ts b/apps/server/src/orchestration-v2/AutoCooldown.ts new file mode 100644 index 000000000000..f4eddaf6738e --- /dev/null +++ b/apps/server/src/orchestration-v2/AutoCooldown.ts @@ -0,0 +1,25 @@ +/** + * Provider instances that just failed an Auto thread with a usage limit or no capacity. The + * usage report can lag behind (or never show a gateway's 429), so Auto routing skips these until + * the cooldown ends. Lives in memory: a server restart forgets it, and the usage report takes over. + */ +const cooldowns = new Map(); + +/** Per instance; a model-scoped limit (Antigravity pools) still benches the whole instance. */ +export function markAutoCooldown(instanceId: string, untilMs: number): void { + const current = cooldowns.get(instanceId) ?? 0; + if (untilMs > current) cooldowns.set(instanceId, untilMs); +} + +export function isAutoCoolingDown(instanceId: string, nowMs: number): boolean { + const until = cooldowns.get(instanceId); + if (until === undefined) return false; + if (until > nowMs) return true; + cooldowns.delete(instanceId); + return false; +} + +/** Tests only. */ +export function clearAutoCooldowns(): void { + cooldowns.clear(); +} diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts new file mode 100644 index 000000000000..e037eb675462 --- /dev/null +++ b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts @@ -0,0 +1,107 @@ +import { + ProviderInstanceId, + RunId, + ThreadId, + type OrchestrationV2ThreadShell, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { clearAutoCooldowns, isAutoCoolingDown, markAutoCooldown } from "./AutoCooldown.ts"; +import { admitFailover, autoFailoverPlan, MAX_FAILOVERS_PER_HOUR } from "./AutoFailoverService.ts"; + +const now = Date.parse("2026-11-14T20:00:00.000Z"); +const runId = RunId.make("run:thread:t1:ordinal:3"); + +function shell(overrides: Partial> = {}): OrchestrationV2ThreadShell { + return { + id: ThreadId.make("t1"), + providerInstanceId: ProviderInstanceId.make("claudeAuto"), + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAuto"), + model: "claude-opus-5-5", + options: [ + { id: "effort", value: "medium" }, + { id: "auto", value: "medium" }, + ], + }, + latestRunId: runId, + status: "failed", + lastErrorClass: "usage_limit", + lastErrorCode: "api_error_429", + usageLimitResetAt: null, + archivedAt: null, + settledOverride: null, + pendingRuntimeRequest: null, + ...overrides, + } as unknown as OrchestrationV2ThreadShell; +} + +const plan = (s: OrchestrationV2ThreadShell) => + autoFailoverPlan({ shell: s, runId, failedInstanceId: "claudeAuto", nowMs: now }); + +describe("autoFailoverPlan", () => { + it("sends a limited Auto thread back through Auto at its level", () => { + const result = plan(shell()); + expect(result?.command).toMatchObject({ + type: "message.dispatch", + threadId: "t1", + modelSelection: { instanceId: "claudeAuto", model: "auto-medium" }, + dispatchMode: { type: "start_immediately" }, + createdBy: "agent", + creationSource: "server", + }); + expect(result?.command.commandId).toBe(`server:auto-failover:t1:${runId}`); + // No reported reset: a 30 minute bench. + expect(result?.cooldownUntilMs).toBe(now + 30 * 60_000); + }); + + it("benches the instance until the reported reset", () => { + const resetAt = "2026-11-14T23:00:00.000Z"; + expect(plan(shell({ usageLimitResetAt: resetAt }))?.cooldownUntilMs).toBe(Date.parse(resetAt)); + }); + + it("fails over on no-capacity errors for a short bench", () => { + const result = plan(shell({ lastErrorClass: "provider_error", lastErrorCode: "UNAVAILABLE" })); + expect(result?.cooldownUntilMs).toBe(now + 5 * 60_000); + }); + + it("leaves other failures, non-Auto threads and stale runs alone", () => { + expect( + plan(shell({ lastErrorClass: "provider_error", lastErrorCode: "api_error_404" })), + ).toBeNull(); + expect( + plan( + shell({ + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-opus-5-5", + }, + }), + ), + ).toBeNull(); + expect(plan(shell({ latestRunId: RunId.make("run:newer") }))).toBeNull(); + expect(plan(shell({ status: "idle" }))).toBeNull(); + expect(plan(shell({ settledOverride: "settled" }))).toBeNull(); + }); +}); + +describe("admitFailover", () => { + it("caps failovers per thread per hour", () => { + const history: Array = []; + for (let i = 0; i < MAX_FAILOVERS_PER_HOUR; i++) + expect(admitFailover(history, now + i)).toBe(true); + expect(admitFailover(history, now + 10)).toBe(false); + expect(admitFailover(history, now + 61 * 60_000)).toBe(true); + }); +}); + +describe("AutoCooldown", () => { + it("benches an instance until the time passes", () => { + clearAutoCooldowns(); + markAutoCooldown("claudeAuto", now + 1000); + markAutoCooldown("claudeAuto", now + 500); + expect(isAutoCoolingDown("claudeAuto", now + 999)).toBe(true); + expect(isAutoCoolingDown("claudeAuto", now + 1000)).toBe(false); + expect(isAutoCoolingDown("claudeAutoB", now)).toBe(false); + }); +}); diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.ts b/apps/server/src/orchestration-v2/AutoFailoverService.ts new file mode 100644 index 000000000000..e5185172de09 --- /dev/null +++ b/apps/server/src/orchestration-v2/AutoFailoverService.ts @@ -0,0 +1,168 @@ +import { + CommandId, + MessageId, + type OrchestrationV2ThreadShell, + type RunId, + type ThreadId, +} from "@t3tools/contracts"; +import { routedAutoLevel } from "@t3tools/shared/autoModel"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FiberMap from "effect/FiberMap"; +import * as Stream from "effect/Stream"; + +import { forkParked } from "../serverActivation.ts"; +import { markAutoCooldown } from "./AutoCooldown.ts"; +import * as Orchestrator from "./Orchestrator.ts"; + +/** Failures that mean "this account has no room right now", besides the usage_limit class. */ +const CAPACITY_CODES: ReadonlySet = new Set([ + "UNAVAILABLE", + "RESOURCE_EXHAUSTED", + "api_error_529", + "overloaded_error", +]); +/** A limit without a reported reset benches the instance this long. */ +const LIMIT_COOLDOWN_MS = 30 * 60_000; +/** No capacity is usually short-lived. */ +const CAPACITY_COOLDOWN_MS = 5 * 60_000; +/** A reported reset further out than this is treated as this. */ +const MAX_COOLDOWN_MS = 7 * 24 * 60 * 60_000; +/** At most this many failovers per thread per hour, so a misreported limit cannot loop. */ +export const MAX_FAILOVERS_PER_HOUR = 6; +/** The run's error item lands around the same time as the run update; let the shell catch up. */ +const SETTLE_DELAY_MS = 1_500; + +const AUTO_FAILOVER_TEXT = + "Auto moved this thread to another subscription because the last one hit its usage limit. Continue where you left off."; + +export interface AutoFailoverPlan { + readonly failedInstanceId: string; + readonly cooldownUntilMs: number; + readonly command: Extract< + Parameters[0], + { readonly type: "message.dispatch" } + >; +} + +/** + * What to do when a run on an Auto thread fails: bench the instance that failed and send the + * thread back through Auto, which then picks the next subscription in the chain. Null when the + * run did not fail for lack of room, or the thread is not on Auto, or is no longer the + * thread's latest run. + */ +export function autoFailoverPlan(input: { + readonly shell: OrchestrationV2ThreadShell; + readonly runId: RunId; + readonly failedInstanceId: string; + readonly nowMs: number; +}): AutoFailoverPlan | null { + const { shell, runId, nowMs } = input; + if ( + shell.latestRunId !== runId || + shell.status !== "failed" || + shell.archivedAt !== null || + shell.settledOverride === "settled" || + shell.pendingRuntimeRequest !== null + ) + return null; + const level = routedAutoLevel(shell.modelSelection); + if (level === undefined) return null; + const limited = shell.lastErrorClass === "usage_limit"; + const noCapacity = !limited && CAPACITY_CODES.has(shell.lastErrorCode ?? ""); + if (!limited && !noCapacity) return null; + const resetMs = shell.usageLimitResetAt ? Date.parse(shell.usageLimitResetAt) : Number.NaN; + const cooldownUntilMs = noCapacity + ? nowMs + CAPACITY_COOLDOWN_MS + : Number.isFinite(resetMs) && resetMs > nowMs + ? Math.min(resetMs, nowMs + MAX_COOLDOWN_MS) + : nowMs + LIMIT_COOLDOWN_MS; + return { + failedInstanceId: input.failedInstanceId, + cooldownUntilMs, + command: { + type: "message.dispatch", + // One failover per failed run, even across duplicate events. + commandId: CommandId.make(`server:auto-failover:${shell.id}:${runId}`), + messageId: MessageId.make(`auto-failover:${shell.id}:${runId}`), + threadId: shell.id, + // The Auto level row; routing replaces it with the next usable subscription. + modelSelection: { instanceId: shell.modelSelection.instanceId, model: `auto-${level}` }, + text: AUTO_FAILOVER_TEXT, + attachments: [], + createdBy: "agent", + creationSource: "server", + dispatchMode: { type: "start_immediately" }, + }, + }; +} + +/** Keeps the timestamps of recent failovers under the hourly cap; true when one more fits. */ +export function admitFailover(history: Array, nowMs: number): boolean { + const recent = history.filter((at) => nowMs - at < 60 * 60_000); + history.splice(0, history.length, ...recent); + if (recent.length >= MAX_FAILOVERS_PER_HOUR) return false; + history.push(nowMs); + return true; +} + +/** + * Fork feature: when a run on an Auto thread fails because its subscription hit a usage limit + * (or has no capacity), the thread moves on at once to the next subscription Auto picks, instead + * of waiting hours for that account to reset. + */ +export const make = Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const history = new Map>(); + + const failOver = Effect.fn("AutoFailoverService.failOver")( + function* (threadId: ThreadId, runId: RunId, failedInstanceId: string) { + yield* Effect.sleep(Duration.millis(SETTLE_DELAY_MS)); + const shell = yield* orchestrator.getThreadShell(threadId); + if (shell === null) return; + const nowMs = DateTime.toEpochMillis(yield* DateTime.now); + const plan = autoFailoverPlan({ shell, runId, failedInstanceId, nowMs }); + if (plan === null) return; + markAutoCooldown(plan.failedInstanceId, plan.cooldownUntilMs); + const threadHistory = history.get(threadId) ?? []; + history.set(threadId, threadHistory); + if (!admitFailover(threadHistory, nowMs)) { + yield* Effect.logWarning("auto failover skipped: hourly cap reached", { threadId }); + return; + } + yield* Effect.logInfo("auto failover", { + threadId, + runId, + failedInstanceId, + errorClass: shell.lastErrorClass, + errorCode: shell.lastErrorCode, + cooldownUntil: DateTime.formatIso(DateTime.makeUnsafe(plan.cooldownUntilMs)), + }); + yield* orchestrator.dispatch(plan.command); + }, + (effect, threadId) => + effect.pipe( + Effect.catch((cause) => + // No usable subscription left: the usage-limit recovery worker still resumes at reset. + Effect.logWarning("auto failover did not dispatch", { threadId, cause }), + ), + ), + ); + + const start = Effect.fn("AutoFailoverService.start")(function* () { + const pending = yield* FiberMap.make(); + yield* forkParked( + Stream.runForEach(orchestrator.streamDomainEvents, (event) => + event.type === "run.updated" && event.payload.status === "failed" + ? FiberMap.run( + pending, + event.threadId, + failOver(event.threadId, event.payload.id, event.payload.providerInstanceId), + ) + : Effect.void, + ), + ); + }); + return { start }; +}); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 40ff5ee716e4..13bfe041d753 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -82,6 +82,7 @@ import { import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { modelSelectionsEqual } from "@t3tools/shared/model"; import { isAutoModelSelection, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; +import { isAutoCoolingDown } from "./AutoCooldown.ts"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import { modelSwitchSince } from "./modelSwitch.ts"; import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts"; @@ -16488,11 +16489,13 @@ const withAutoModelRouting = Effect.fn("OrchestratorV2.withAutoModelRouting")(fu ? ((yield* orchestrator.getThreadShell(threadId).pipe(Effect.orElseSucceed(() => null))) ?.modelSelection ?? null) : null; + const now = DateTime.toEpochMillis(yield* DateTime.now); const resolution = resolveAutoModelSelection({ selection, providers: Option.isSome(registry) ? yield* registry.value.getProviders : [], - now: DateTime.toEpochMillis(yield* DateTime.now), + now, current, + blocked: (instanceId) => isAutoCoolingDown(instanceId, now), }); if (resolution === null) { return yield* new OrchestratorCommandRejectedError({ diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 47c4a4c9a20e..a135dfc0ff17 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -214,6 +214,7 @@ import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts"; import * as IdleCompactionService from "./orchestration-v2/IdleCompactionService.ts"; +import * as AutoFailoverService from "./orchestration-v2/AutoFailoverService.ts"; import * as ThreadPullRequestService from "./orchestration-v2/ThreadPullRequestService.ts"; import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts"; import * as ProjectionMaintenance from "./orchestration-v2/ProjectionMaintenance.ts"; @@ -620,6 +621,10 @@ const layerThreadSettlementWorker = Layer.effectDiscard( ThreadSettlementService.make.pipe(Effect.flatMap((service) => service.start())), ).pipe(Layer.provide(layerPullRequestService), Layer.provide(ProjectionStoreV2.layer)); +const layerAutoFailoverWorker = Layer.effectDiscard( + AutoFailoverService.make.pipe(Effect.flatMap((service) => service.start())), +); + const layerIdleCompactionWorker = Layer.effectDiscard( IdleCompactionService.make.pipe(Effect.flatMap((service) => service.start())), ).pipe(Layer.provide(ProjectionStoreV2.layer)); @@ -679,6 +684,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( HeldHooksWaker.layer, layerThreadSettlementWorker, layerIdleCompactionWorker, + layerAutoFailoverWorker, StorageCleanup.layer.pipe(Layer.provide(ProjectionStoreV2.layer)), DatabaseStorage.layer.pipe( Layer.provide(ProjectionMaintenance.layer), diff --git a/docs/progress.md b/docs/progress.md index 1db4eaeb2169..236f4c4d9f34 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -74,3 +74,11 @@ - Numbers: autoModel 12/12, handoff + contextWindow 39/39 (a recursion the stamp caused was caught by the handoff test); shared, client-runtime, web, mobile and server typecheck clean. Checked in a clean incognito browser on a scratch copy of hub2's data: a thread started on Auto Low over the CLI shows Auto Low in the composer. - Deploy: service now runs from `~/.t3/fork-current` (a symlink to the deploy checkout), so a new build goes into a fresh checkout and the restart flips the link. - Next: hub (link it first) and a fork build of the PC desktop app; the stock app still shows the concrete model. + +## 2026-11-14: Auto fails over to the next subscription the moment one hits its limit + +- What: `AutoFailoverService` watches failed runs. When a run on an Auto thread fails with a usage limit (`usage_limit` class: Claude 429 / 5-hour / weekly, Codex `usageLimitExceeded`, Antigravity `RESOURCE_EXHAUSTED`) or no capacity (`UNAVAILABLE`, Claude 529), it benches that provider instance (`AutoCooldown`, until the reported reset, else 30 min; 5 min for no capacity) and sends the thread back through Auto with "Continue where you left off". Auto routing (`resolveAutoModelSelection`) skips benched instances, the sticky current one included. At most 6 failovers per thread per hour. +- Why: Auto routed only when a message was sent. A limit hit mid-work left the thread failed, and the upstream recovery worker resumed it on the same account hours later, at reset. Tomáš wants Auto to chain across all subscriptions as soon as one runs out. The PC's own DB showed 28 failed runs in two days, most of them limit errors (429, quota, capacity) that should have moved on. +- Numbers: autoModel 13/13 (new blocked case), AutoFailoverService 6/6; server typecheck clean. +- Limits: the bench is in memory, so a server restart forgets it (the usage report takes over). A failure whose session error differs from the run's error item has no error class and is not failed over. +- Next: build the PC desktop app from `tomas/pc-nightly`; deploy to hub/hub2. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index e3b6e708f89d..7391bb9fa06f 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -304,6 +304,24 @@ describe("resolveAutoModelSelection", () => { expect(autoLevelSelection(plain)).toBe(plain); }); + it("skips blocked instances, the thread's current one included", () => { + const current = { instanceId: ProviderInstanceId.make("claudeAuto"), model: "claude-opus-5-5" }; + const calm = [claude("claudeAuto", 20), claude("claudeAutoB", 5)]; + const blocked = (instanceId: string) => instanceId === "claudeAuto"; + expect( + resolveAutoModelSelection({ selection: auto(), providers: calm, now, current, blocked }), + ).toMatchObject({ sticky: false, selection: { instanceId: "claudeAutoB" } }); + expect( + resolveAutoModelSelection({ + selection: auto(), + providers: calm, + now, + current, + blocked: () => true, + }), + ).toBeNull(); + }); + it("returns null when nothing is usable", () => { const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; expect(resolveAutoModelSelection({ selection: auto(), providers, now })).toBeNull(); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 74519c6e38e5..d4eaee1d0dad 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -131,6 +131,11 @@ export function isAutoModelSelection(selection: ModelSelection | null | undefine } /** A routed thread's model as the Auto level it came from, for pickers; others unchanged. */ +/** The Auto level a routed thread runs at, or undefined for a thread not on Auto. */ +export function routedAutoLevel(selection: ModelSelection | null | undefined) { + return stampedLevel(selection); +} + export function autoLevelSelection( selection: T, ): T | ModelSelection { @@ -252,9 +257,16 @@ export function resolveAutoModelSelection(input: { readonly providers: ReadonlyArray; readonly now: number; readonly current?: ModelSelection | null; + /** + * Instances (and models) that just failed with a usage limit or no capacity, which the usage + * report may not show yet. Auto skips them, the thread's current model included. + */ + readonly blocked?: (instanceId: string, model: string) => boolean; }): AutoResolution | null { const level = autoLevelOf(input.selection); const candidates = AUTO_CANDIDATES[level]; + const open = (provider: ServerProvider, model: string) => + usable(provider, model, input.now) && !input.blocked?.(provider.instanceId, model); const current = input.current; if (current && !isAutoModelSlug(current.model)) { @@ -265,7 +277,7 @@ export function resolveAutoModelSelection(input: { if ( provider && candidate && - usable(provider, candidate.model, input.now) && + open(provider, candidate.model) && peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT ) { return { selection: toSelection(provider, candidate, level), level, sticky: true }; @@ -277,7 +289,7 @@ export function resolveAutoModelSelection(input: { .filter( (provider) => provider.driver === (candidate.driver as ProviderDriverKind) && - usable(provider, candidate.model, input.now), + open(provider, candidate.model), ) // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. .sort(compareInstances); From 5427187a63e0405cb633ac912f1ec5c6f6465f59 Mon Sep 17 00:00:00 2001 From: radys-s Date: Sun, 15 Nov 2026 14:59:37 +0100 Subject: [PATCH 034/230] fix(auto): return to the better model after a reset; failover follows auto-resume Review of the failover commit before it went on the PC: - A thread that failed over to a weaker model stayed there while that account was under 90% used, even after the better account reset. The sticky rule now gives way when a better candidate has room. - Failover follows the autoResumeLimitedThreads setting: off still benches the failed instance, but sends nothing on its own. - Failover skips a provider's own subagent threads, which cannot receive messages. --- .../AutoFailoverService.test.ts | 17 +++++++++++++ .../orchestration-v2/AutoFailoverService.ts | 10 +++++++- docs/progress.md | 9 +++++++ packages/shared/src/autoModel.test.ts | 22 ++++++++++++++++ packages/shared/src/autoModel.ts | 25 ++++++++++++++----- 5 files changed, 76 insertions(+), 7 deletions(-) diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts index e037eb675462..078076aca8a2 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts @@ -25,6 +25,12 @@ function shell(overrides: Partial> = {}): OrchestrationV ], }, latestRunId: runId, + lineage: { + rootThreadId: ThreadId.make("t1"), + parentThreadId: null, + relationshipToParent: null, + }, + creationSource: "user", status: "failed", lastErrorClass: "usage_limit", lastErrorCode: "api_error_429", @@ -86,6 +92,17 @@ describe("autoFailoverPlan", () => { }); describe("admitFailover", () => { + it("leaves a provider's own subagent alone, which cannot receive messages", () => { + const lineage = { + rootThreadId: ThreadId.make("t0"), + parentThreadId: ThreadId.make("t0"), + relationshipToParent: "subagent", + }; + expect(plan(shell({ lineage, creationSource: "provider" }))).toBeNull(); + // A delegate_task child takes messages like any thread. + expect(plan(shell({ lineage, creationSource: "agent" }))).not.toBeNull(); + }); + it("caps failovers per thread per hour", () => { const history: Array = []; for (let i = 0; i < MAX_FAILOVERS_PER_HOUR; i++) diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.ts b/apps/server/src/orchestration-v2/AutoFailoverService.ts index e5185172de09..b91420a90553 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.ts @@ -1,5 +1,6 @@ import { CommandId, + isProviderNativeSubagentThread, MessageId, type OrchestrationV2ThreadShell, type RunId, @@ -13,6 +14,7 @@ import * as FiberMap from "effect/FiberMap"; import * as Stream from "effect/Stream"; import { forkParked } from "../serverActivation.ts"; +import * as ServerSettings from "../serverSettings.ts"; import { markAutoCooldown } from "./AutoCooldown.ts"; import * as Orchestrator from "./Orchestrator.ts"; @@ -64,7 +66,9 @@ export function autoFailoverPlan(input: { shell.status !== "failed" || shell.archivedAt !== null || shell.settledOverride === "settled" || - shell.pendingRuntimeRequest !== null + shell.pendingRuntimeRequest !== null || + // A provider's own subagent cannot receive messages; its parent sees the failure. + isProviderNativeSubagentThread(shell) ) return null; const level = routedAutoLevel(shell.modelSelection); @@ -114,6 +118,7 @@ export function admitFailover(history: Array, nowMs: number): boolean { */ export const make = Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; + const settings = yield* ServerSettings.ServerSettingsService; const history = new Map>(); const failOver = Effect.fn("AutoFailoverService.failOver")( @@ -124,7 +129,10 @@ export const make = Effect.gen(function* () { const nowMs = DateTime.toEpochMillis(yield* DateTime.now); const plan = autoFailoverPlan({ shell, runId, failedInstanceId, nowMs }); if (plan === null) return; + // Bench the instance either way, so the next message the user sends routes around it. markAutoCooldown(plan.failedInstanceId, plan.cooldownUntilMs); + // The same switch as resuming at reset: off means T3 sends nothing on its own. + if (!(yield* settings.getSettings).autoResumeLimitedThreads) return; const threadHistory = history.get(threadId) ?? []; history.set(threadId, threadHistory); if (!admitFailover(threadHistory, nowMs)) { diff --git a/docs/progress.md b/docs/progress.md index 236f4c4d9f34..3b15d3cdc7c9 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -82,3 +82,12 @@ - Numbers: autoModel 13/13 (new blocked case), AutoFailoverService 6/6; server typecheck clean. - Limits: the bench is in memory, so a server restart forgets it (the usage report takes over). A failure whose session error differs from the run's error item has no error class and is not failed over. - Next: build the PC desktop app from `tomas/pc-nightly`; deploy to hub/hub2. + +## 2026-11-15: Auto failover review fixes, and a way back to the better model + +- What: (1) Auto's sticky rule now gives way when a better candidate for the level has room again. Before, a thread that failed over to a weaker model (say Grok) stayed there for good while that account was under 90% used, even after Claude reset. (2) Failover follows the `autoResumeLimitedThreads` setting: off means the failed instance is still benched (the next message the user sends routes around it), but T3 sends nothing on its own. (3) Failover skips a provider's own subagent threads, which cannot receive messages. +- Why: review of `d25e0609c7` before it went on the PC. The failover sends turns by itself, so a mistake there spends every subscription. The one-way downgrade contradicted the Auto skill, which says a provider re-enters the chain when its window resets. +- Checked and left alone: the domain event stream starts at the latest sequence, so a server restart does not replay old failed runs into failovers. A failover and the upstream reset-resume cannot both fire: the resume needs the thread's latest run to be the failed one. The return to a better model needs that account under 90%, so a thread does not hop back onto an account about to run out. +- Numbers: autoModel 14/14, AutoFailoverService 7/7, server typecheck 0 errors. +- Cost: moving back up is one more provider handoff (a thread summary). It happens once per reset, on the next message. +- Next: build the PC desktop app from `tomas/pc-nightly` and install it. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index 7391bb9fa06f..d179263a94a5 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -322,6 +322,28 @@ describe("resolveAutoModelSelection", () => { ).toBeNull(); }); + it("returns from a weaker fallback once a better model has room again", () => { + const grok = { + ...claude("grok", 0, false), + driver: ProviderDriverKind.make("grok"), + models: [{ slug: "grok-4.7", name: "Grok 4.7", isCustom: false, capabilities: null }], + usageLimits: undefined, + } as unknown as ServerProvider; + const current = { instanceId: ProviderInstanceId.make("grok"), model: "grok-4.7" }; + const resolve = (claudeUsed: number) => + resolveAutoModelSelection({ + selection: auto(), + providers: [claude("claudeAuto", claudeUsed), grok], + now, + current, + }); + // Claude is back: the thread leaves Grok. + expect(resolve(10)).toMatchObject({ sticky: false, selection: { instanceId: "claudeAuto" } }); + // Claude is nearly out or exhausted: no hop back that would fail again at once. + expect(resolve(95)).toMatchObject({ sticky: true, selection: { instanceId: "grok" } }); + expect(resolve(100)).toMatchObject({ sticky: true, selection: { instanceId: "grok" } }); + }); + it("returns null when nothing is usable", () => { const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; expect(resolveAutoModelSelection({ selection: auto(), providers, now })).toBeNull(); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index d4eaee1d0dad..2ee6fa04460e 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -130,12 +130,12 @@ export function isAutoModelSelection(selection: ModelSelection | null | undefine return isAutoModelSlug(selection?.model) || stampedLevel(selection) !== undefined; } -/** A routed thread's model as the Auto level it came from, for pickers; others unchanged. */ /** The Auto level a routed thread runs at, or undefined for a thread not on Auto. */ export function routedAutoLevel(selection: ModelSelection | null | undefined) { return stampedLevel(selection); } +/** A routed thread's model as the Auto level it came from, for pickers; others unchanged. */ export function autoLevelSelection( selection: T, ): T | ModelSelection { @@ -248,9 +248,9 @@ interface AutoResolution { } /** - * Keeps the thread's model while it fits this level and is under 90% used (no account hop, no - * lost prompt cache); otherwise the first usable candidate on the best instance (see - * `compareInstances`). Null when nothing is usable. + * Keeps the thread's model while it fits this level, is under 90% used and no better candidate + * has room (no account hop, no lost prompt cache); otherwise the first usable candidate on the + * best instance (see `compareInstances`). Null when nothing is usable. */ export function resolveAutoModelSelection(input: { readonly selection: ModelSelection; @@ -271,14 +271,27 @@ export function resolveAutoModelSelection(input: { const current = input.current; if (current && !isAutoModelSlug(current.model)) { const provider = input.providers.find((entry) => entry.instanceId === current.instanceId); - const candidate = candidates.find( + const rank = candidates.findIndex( (entry) => entry.driver === provider?.driver && entry.model === current.model, ); + const candidate = candidates[rank]; + // A thread that fell back to a weaker model returns once a better one has room again. + const betterHasRoom = candidates + .slice(0, Math.max(rank, 0)) + .some((better) => + input.providers.some( + (entry) => + entry.driver === (better.driver as ProviderDriverKind) && + open(entry, better.model) && + hasRoom(entry), + ), + ); if ( provider && candidate && open(provider, candidate.model) && - peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT + hasRoom(provider) && + !betterHasRoom ) { return { selection: toSelection(provider, candidate, level), level, sticky: true }; } From e57c85c3e3a65916f44ecd6b7ec518c05051bb91 Mon Sep 17 00:00:00 2001 From: radys-s Date: Sun, 15 Nov 2026 21:12:52 +0100 Subject: [PATCH 035/230] fix: Resume works on providers without native resume; limited threads move to Auto On the PC a thread stuck on Grok after Claude hit its limit: every Resume failed with "Native resume is unavailable" and the thread never moved on. - Resume on a provider without native resume starts an ordinary turn that asks the agent to continue, instead of failing. - A thread not on Auto that hits a usage limit fails over through Auto at the level its model implies. Delegated threads keep their model. --- .../AutoFailoverService.test.ts | 30 +++++++++++------- .../orchestration-v2/AutoFailoverService.ts | 20 +++++++++--- .../ProviderTurnStartService.test.ts | 22 +++++-------- .../ProviderTurnStartService.ts | 31 +++++++++---------- docs/progress.md | 8 +++++ 5 files changed, 65 insertions(+), 46 deletions(-) diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts index 078076aca8a2..f35ce55d2995 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts @@ -71,20 +71,28 @@ describe("autoFailoverPlan", () => { expect(result?.cooldownUntilMs).toBe(now + 5 * 60_000); }); - it("leaves other failures, non-Auto threads and stale runs alone", () => { + it("moves a hand-picked thread to Auto at the level its model implies", () => { + const picked = (model: string) => + shell({ modelSelection: { instanceId: ProviderInstanceId.make("grok"), model } }); + expect(plan(picked("grok-4.7"))?.command.modelSelection).toEqual({ + instanceId: "grok", + model: "auto-medium", + }); + expect(plan(picked("claude-fable-5-2"))?.command.modelSelection?.model).toBe("auto-high"); + expect(plan(picked("claude-haiku-5-5"))?.command.modelSelection?.model).toBe("auto-low"); + // A delegated thread keeps the model its parent chose. + const delegated = { + rootThreadId: ThreadId.make("t0"), + parentThreadId: ThreadId.make("t0"), + relationshipToParent: "subagent", + }; + expect(plan(shell({ ...picked("grok-4.7"), lineage: delegated }))).toBeNull(); + }); + + it("leaves other failures and stale runs alone", () => { expect( plan(shell({ lastErrorClass: "provider_error", lastErrorCode: "api_error_404" })), ).toBeNull(); - expect( - plan( - shell({ - modelSelection: { - instanceId: ProviderInstanceId.make("claudeAgent"), - model: "claude-opus-5-5", - }, - }), - ), - ).toBeNull(); expect(plan(shell({ latestRunId: RunId.make("run:newer") }))).toBeNull(); expect(plan(shell({ status: "idle" }))).toBeNull(); expect(plan(shell({ settledOverride: "settled" }))).toBeNull(); diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.ts b/apps/server/src/orchestration-v2/AutoFailoverService.ts index b91420a90553..0b491a57b9c2 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.ts @@ -1,5 +1,6 @@ import { CommandId, + isDelegatedAppThread, isProviderNativeSubagentThread, MessageId, type OrchestrationV2ThreadShell, @@ -51,8 +52,8 @@ export interface AutoFailoverPlan { /** * What to do when a run on an Auto thread fails: bench the instance that failed and send the * thread back through Auto, which then picks the next subscription in the chain. Null when the - * run did not fail for lack of room, or the thread is not on Auto, or is no longer the - * thread's latest run. + * run did not fail for lack of room, or the thread is a delegated one not on Auto, or the run is + * no longer the thread's latest. */ export function autoFailoverPlan(input: { readonly shell: OrchestrationV2ThreadShell; @@ -71,8 +72,12 @@ export function autoFailoverPlan(input: { isProviderNativeSubagentThread(shell) ) return null; - const level = routedAutoLevel(shell.modelSelection); - if (level === undefined) return null; + // A thread not on Auto (an older thread, or one where a model was picked by hand) moves to + // Auto at the level its model implies: a limit there means the picked model is out anyway. + // Delegated threads keep the model their parent chose; their parent sees the failure. + const routed = routedAutoLevel(shell.modelSelection); + if (routed === undefined && isDelegatedAppThread(shell)) return null; + const level = routed ?? impliedAutoLevel(shell.modelSelection.model); const limited = shell.lastErrorClass === "usage_limit"; const noCapacity = !limited && CAPACITY_CODES.has(shell.lastErrorCode ?? ""); if (!limited && !noCapacity) return null; @@ -102,6 +107,13 @@ export function autoFailoverPlan(input: { }; } +/** The Auto level whose orchestrator is closest to a hand-picked model. */ +function impliedAutoLevel(model: string): "low" | "medium" | "high" { + if (/fable|gpt-6\.1-sol|astra/i.test(model)) return "high"; + if (/sonnet|haiku|flash|opencode\/|luna/i.test(model)) return "low"; + return "medium"; +} + /** Keeps the timestamps of recent failovers under the hourly cap; true when one more fits. */ export function admitFailover(history: Array, nowMs: number): boolean { const recent = history.filter((at) => nowMs - at < 60 * 60_000); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 7b0759ae99b0..85aad4d28117 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -2112,7 +2112,9 @@ effectIt.effect("sends new steering text when restarting a manual continuation", }), ); -effectIt.effect("refuses unsupported resume instead of manufacturing a user prompt", () => +// Fork: upstream failed here with "Native resume is unavailable", which left Grok, OpenCode and +// Antigravity threads stuck on Resume. The fork starts an ordinary turn that asks to continue. +effectIt.effect("asks to continue when the provider cannot resume natively", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "", @@ -2121,20 +2123,10 @@ effectIt.effect("refuses unsupported resume instead of manufacturing a user prom sideChat: { contextRun: "delivered" }, }); yield* harness.start; - expect(harness.startTurn).not.toHaveBeenCalled(); - expect(harness.startRootRun).not.toHaveBeenCalled(); - expect(harness.settledRuns).toEqual(["failed"]); - expect(harness.projection().turnItems).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - type: "error", - failure: expect.objectContaining({ - message: - "This provider cannot resume without a new message. Send a message to continue.", - }), - }), - ]), - ); + expect(harness.startTurn.mock.calls.map(([turn]) => turn.message.text)).toEqual([ + "Continue where you left off.", + ]); + expect(harness.settledRuns).not.toContain("failed"); }), ); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 5996a090bf4b..d53e923355fb 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -97,6 +97,9 @@ const isProviderAdapterOpenSessionError = Schema.is( ProviderAdapter.ProviderAdapterOpenSessionError, ); +/** Sent in place of a native resume the provider does not support. */ +const MANUAL_RESUME_CONTINUE_TEXT = "Continue where you left off."; + /** * Claude refuses these before it reads the prompt: replacing a process running background work, * launch arguments whose appended system prompt or settings cannot be read, or MCP registration @@ -844,10 +847,17 @@ export const layer: Layer.Layer< }); let effectiveHandoffs = handoffs; let resumeFellBack = false; - const userText = projectComposerContextForProvider({ - text: providerMessage.text, - records: providerMessage.context?.records ?? [], - }); + // Fork: Resume on a provider with no native resume (Grok, OpenCode, Antigravity, or a run + // that moved to another provider) used to fail with "Native resume is unavailable". It now + // starts an ordinary turn that asks the agent to continue. + const continueInstead = + manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined; + const userText = continueInstead + ? MANUAL_RESUME_CONTINUE_TEXT + : projectComposerContextForProvider({ + text: providerMessage.text, + records: providerMessage.context?.records ?? [], + }); // Native goal commands go verbatim; handoff history waits a turn. const goalDriver = session.driver === "codex" || @@ -1538,17 +1548,6 @@ export const layer: Layer.Layer< legacyInputRunIds, budget, } = handoffContext; - if (manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined) { - yield* settleStartFailure({ - signal: "resume-unsupported", - title: "Native resume is unavailable", - error: new ProviderAdapter.ProviderResumeUnsupportedError({ - driver: session.driver, - providerThreadId: providerThread.id, - }), - }); - return; - } const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, @@ -1853,7 +1852,7 @@ export const layer: Layer.Layer< .filter((turn) => turn.providerThreadId === providerThread.id) .map((turn) => turn.ordinal), ) + 1, - resume: manualResume && unsentResumeMessage === undefined, + resume: manualResume && unsentResumeMessage === undefined && !continueInstead, nativeThreadHasTurns: nativeInputRunIds.size > 0 || (legacyInputRunIds.size > 0 && diff --git a/docs/progress.md b/docs/progress.md index 3b15d3cdc7c9..069401bf3429 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -91,3 +91,11 @@ - Numbers: autoModel 14/14, AutoFailoverService 7/7, server typecheck 0 errors. - Cost: moving back up is one more provider handoff (a thread summary). It happens once per reset, on the next message. - Next: build the PC desktop app from `tomas/pc-nightly` and install it. + +## 2026-11-15: Resume works on every provider; limited hand-picked threads move to Auto + +- What happened (PC, thread "Port Hub T3 App Improvements to PC"): Claude hit its 5-hour limit. The thread was not on Auto (it started on the Auto instance before Auto existed, with a plain Opus model), so no failover ran. The composer was switched to Grok and Resume pressed. Grok has no native resume, so each Resume failed at once with "Native resume is unavailable". The one "continue" that reached Grok ran a few tool calls, then hit Grok's free limit, which T3 cannot see in usage windows. Every later "continue" went to Grok again and failed. Result: about ten turns with no answer. +- Fix 1 (`ProviderTurnStartService`): Resume on a provider without native resume now starts an ordinary turn with "Continue where you left off." (plus the handoff context when the provider changed) instead of failing. Upstream's test "refuses unsupported resume" was rewritten to the new behavior. +- Fix 2 (`AutoFailoverService`): a thread not on Auto that hits a usage limit now fails over through Auto at the level its model implies (Fable/Sol/Astra high; Sonnet/Haiku/Flash/OpenCode/Luna low; else medium). Delegated threads not on Auto are left alone: their parent chose the model. +- Setup repo: `fallbackModelSelection` (Grok) is cleared by `apply-auto-settings.py`; the health check warns while it is set. +- Numbers: AutoFailoverService 8/8; ProviderTurnStartService 65/69, the same 4 failures as before the change (Windows-only git/startup tests); server typecheck 0 errors. From bd33ae897c631b07adb391b55ca9db208536ef27 Mon Sep 17 00:00:00 2001 From: radys-s Date: Mon, 16 Nov 2026 08:32:10 +0100 Subject: [PATCH 036/230] fix: let a thread switch providers after a failed failover turn MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When Auto failover moved a thread to Grok and Grok hit its limit on the first turn, the thread kept Grok as its selection with no provider thread for that instance. The client only allowed a handoff from a provider thread matching the current selection, so the picker locked every other provider ("Claude is unavailable in this thread"). The server hands off from the app's own run history, so any provider thread of this app thread is enough. The empty case stays locked as before. Origin: Tomáš's screenshot in thread 'Agent Skills and Design Guide Overhaul' (2026-11-16). --- .../src/state/threadWorkflows.test.ts | 16 +++++++++++++++- .../client-runtime/src/state/threadWorkflows.ts | 12 ++++-------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts index 3fe571e84b5b..cace83a3ab3b 100644 --- a/packages/client-runtime/src/state/threadWorkflows.test.ts +++ b/packages/client-runtime/src/state/threadWorkflows.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vite-plus/test"; -import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import { ProviderInstanceId, type OrchestrationV2ThreadProjection } from "@t3tools/contracts"; import { canForkProjectedAssistantItem, @@ -64,6 +64,20 @@ describe("thread workflows", () => { }), ).toBe(true); expect(threadSupportsProviderHandoff({ ...projection, providerThreads: [] })).toBe(false); + // Failover moved the selection to Grok, whose first turn failed on its limit. + expect( + threadSupportsProviderHandoff({ + ...projection, + thread: { + ...projection.thread, + modelSelection: { + instanceId: ProviderInstanceId.make("grok"), + model: "grok-4.7", + }, + }, + runs: [{ ...projection.runs[0]!, status: "failed" }], + }), + ).toBe(true); }); it("sorts queued messages and gates promotion from capabilities", () => { diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts index 1f50bff8e246..2c85a2fb2acd 100644 --- a/packages/client-runtime/src/state/threadWorkflows.ts +++ b/packages/client-runtime/src/state/threadWorkflows.ts @@ -110,14 +110,10 @@ export function threadSupportsProviderHandoff(projection: Projection | null | un if (projection.thread.historyOrigin === "v1_import" || projection.runs.length === 0) return true; // Detaching a stopped session removes it from the projection. The server still - // hands off from saved app history, which needs the source provider thread but - // not its native ref. - return projection.providerThreads.some( - (thread) => - thread.id === projection.thread.activeProviderThreadId && - thread.appThreadId === projection.thread.id && - thread.providerInstanceId === projection.thread.modelSelection.instanceId, - ); + // hands off from saved app history. A switch whose first turn failed (a limit hit + // right away) leaves the selection on an instance with no matching provider + // thread; any provider thread of this app thread is enough to hand off from. + return projection.providerThreads.some((thread) => thread.appThreadId === projection.thread.id); } export function getUserQueuedThreadRuns( From af6613d8803543504a4f1b6f845a955e0364849f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 12 Nov 2026 18:22:12 +0100 Subject: [PATCH 037/230] feat: Auto model routes across subscriptions by level and live usage limits --- .../src/orchestration-v2/Orchestrator.ts | 67 +++++- docs/progress.md | 10 + packages/shared/package.json | 4 + packages/shared/src/autoModel.test.ts | 132 ++++++++++++ packages/shared/src/autoModel.ts | 202 ++++++++++++++++++ 5 files changed, 412 insertions(+), 3 deletions(-) create mode 100644 docs/progress.md create mode 100644 packages/shared/src/autoModel.test.ts create mode 100644 packages/shared/src/autoModel.ts diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 819aa90c03b9..11b59f3b2669 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -82,6 +82,8 @@ import { } from "@t3tools/contracts"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { modelSelectionsEqual } from "@t3tools/shared/model"; +import { isAutoModelSelection, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import { modelSwitchSince } from "./modelSwitch.ts"; import { contextBoundaryOrdinal, isScheduledFreshRun } from "./contextBoundary.ts"; import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts"; @@ -16560,6 +16562,65 @@ export const layer: Layer.Layer< | RuntimePolicyV2 | ServerSettings.ServerSettingsService | ThreadForkServiceV2 -> = Layer.effect(OrchestratorV2, makeOrchestrator()).pipe( - Layer.provide(ThreadCommandExecutor.layer), -); +> = Layer.effect( + OrchestratorV2, + makeOrchestrator().pipe(Effect.flatMap((orchestrator) => withAutoModelRouting(orchestrator))), +).pipe(Layer.provide(ThreadCommandExecutor.layer)); + +/** Commands whose `auto` model keeps the thread's current model while it still fits. */ +const AUTO_STICKY_COMMANDS: ReadonlySet = new Set([ + "message.dispatch", + "thread.model-selection.set", + "provider.switch", +]); + +/** + * Replaces the `auto` model in any command with the concrete model Auto picks from live usage + * limits, so every surface (web, mobile, MCP, scheduled tasks) gets the same routing. + */ +const withAutoModelRouting = Effect.fn("OrchestratorV2.withAutoModelRouting")(function* ( + orchestrator: OrchestratorV2Shape, +) { + // Optional so layers without provider snapshots (tests, CLI tools) still build; there, Auto + // is rejected instead of routed. + const registry = yield* Effect.serviceOption(ProviderRegistry.ProviderRegistry); + const resolve = Effect.fn("OrchestratorV2.resolveAutoModel")(function* ( + command: OrchestrationV2ServerCommand, + ) { + const selection = (command as { readonly modelSelection?: ModelSelection }).modelSelection; + if (!isAutoModelSelection(selection) || selection === undefined) return command; + const threadId = (command as { readonly threadId?: ThreadId }).threadId; + const current = + threadId !== undefined && AUTO_STICKY_COMMANDS.has(command.type) + ? ((yield* orchestrator.getThreadShell(threadId).pipe(Effect.orElseSucceed(() => null))) + ?.modelSelection ?? null) + : null; + const resolution = resolveAutoModelSelection({ + selection, + providers: Option.isSome(registry) ? yield* registry.value.getProviders : [], + now: DateTime.toEpochMillis(yield* DateTime.now), + current, + }); + if (resolution === null) { + return yield* new OrchestratorCommandRejectedError({ + commandId: command.commandId, + commandType: command.type, + cause: new Error( + "Auto found no usable model: every candidate is disabled, signed out, or at its usage limit.", + ), + }); + } + yield* Effect.logInfo("auto model routing", { + commandType: command.type, + level: resolution.level, + sticky: resolution.sticky, + instanceId: resolution.selection.instanceId, + model: resolution.selection.model, + }); + return { ...command, modelSelection: resolution.selection } as OrchestrationV2ServerCommand; + }); + return { + ...orchestrator, + dispatch: (command) => resolve(command).pipe(Effect.flatMap(orchestrator.dispatch)), + } satisfies OrchestratorV2Shape; +}); diff --git a/docs/progress.md b/docs/progress.md new file mode 100644 index 000000000000..dfb3c4eafab5 --- /dev/null +++ b/docs/progress.md @@ -0,0 +1,10 @@ +# Progress (radys-s fork) + +## 2026-11-12: Auto model + +- What: an "Auto" model with its own Low/Medium/High level. Picking it never reaches a provider; the server replaces it in every command (`OrchestratorV2.dispatch`) with a concrete model chosen from live usage limits: Fable (high), Opus (medium) or Sonnet (low) on whichever Claude account has more room, then Codex, Grok and OpenCode when Claude is out. +- Why: Tomáš wanted one Auto entry in the model picker that routes across all his subscriptions, including Claude A vs B. +- How it shows up: a custom model `auto` (with an `effort` select of low/medium/high) on the Auto Claude instances in settings. No web change was needed; the picker already renders custom models and their options. +- Numbers: resolver 5/5 tests; shared and server typecheck clean (server took 22 min on the first, cold run, ~6 min warm). +- Worked: one wrapper around `dispatch` covers web, mobile, MCP and scheduled tasks. Stickiness keeps a thread on its model until it passes 90% used, so threads do not hop accounts on each message. +- Next: after the first message the composer shows the concrete model, not "Auto"; keeping Auto selected mid-thread needs a client change. diff --git a/packages/shared/package.json b/packages/shared/package.json index 781d1a4e125e..9a8adb9c5bda 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -407,6 +407,10 @@ "types": "./src/usageFormat.ts", "import": "./src/usageFormat.ts" }, + "./autoModel": { + "types": "./src/autoModel.ts", + "import": "./src/autoModel.ts" + }, "./usageLimits": { "types": "./src/usageLimits.ts", "import": "./src/usageLimits.ts" diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts new file mode 100644 index 000000000000..e7846c214e74 --- /dev/null +++ b/packages/shared/src/autoModel.test.ts @@ -0,0 +1,132 @@ +import { + ProviderDriverKind, + ProviderInstanceId, + type ModelSelection, + type ServerProvider, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { AUTO_LEVEL_DESCRIPTOR, resolveAutoModelSelection } from "./autoModel.ts"; + +const now = Date.parse("2026-11-12T12:00:00.000Z"); +const resetsAt = "2026-11-12T15:00:00.000Z"; + +const effortCapabilities = { + optionDescriptors: [ + { + id: "effort", + label: "Effort", + type: "select" as const, + options: ["low", "medium", "high"].map((id) => ({ id, label: id })), + }, + ], +}; + +function claude(id: string, usedPercent: number, autoAware = true): ServerProvider { + return { + instanceId: ProviderInstanceId.make(id), + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-11-12T11:00:00.000Z", + models: [ + ...["claude-fable-5-2", "claude-opus-5-5", "claude-sonnet-5-5"].map((slug) => ({ + slug, + name: slug, + isCustom: false, + capabilities: effortCapabilities, + })), + ...(autoAware + ? [ + { + slug: "auto", + name: "Auto", + isCustom: true, + capabilities: { optionDescriptors: [AUTO_LEVEL_DESCRIPTOR] }, + }, + ] + : []), + ], + slashCommands: [], + skills: [], + usageLimits: { + windows: [{ id: "five_hour", kind: "session", label: "Session", usedPercent, resetsAt }], + }, + } as unknown as ServerProvider; +} + +const auto = (level?: string): ModelSelection => ({ + instanceId: ProviderInstanceId.make("claudeAuto"), + model: "auto", + ...(level ? { options: [{ id: "effort", value: level }] } : {}), +}); + +describe("resolveAutoModelSelection", () => { + it("maps each level to its orchestrator model and effort, medium by default", () => { + const providers = [claude("claudeAuto", 10)]; + expect( + resolveAutoModelSelection({ selection: auto("high"), providers, now })?.selection, + ).toEqual({ + instanceId: "claudeAuto", + model: "claude-fable-5-2", + options: [{ id: "effort", value: "high" }], + }); + expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.model).toBe( + "claude-opus-5-5", + ); + expect( + resolveAutoModelSelection({ selection: auto("low"), providers, now })?.selection, + ).toEqual({ + instanceId: "claudeAuto", + model: "claude-sonnet-5-5", + options: [{ id: "effort", value: "low" }], + }); + }); + + it("picks the Claude account with more room, preferring Auto-aware instances", () => { + const providers = [ + claude("claudeAgent", 0, false), + claude("claudeAuto", 70), + claude("claudeAutoB", 20), + ]; + expect( + resolveAutoModelSelection({ selection: auto("medium"), providers, now })?.selection + .instanceId, + ).toBe("claudeAutoB"); + }); + + it("keeps the thread's current model until it passes 90% used", () => { + const current = { instanceId: ProviderInstanceId.make("claudeAuto"), model: "claude-opus-5-5" }; + const calm = [claude("claudeAuto", 60), claude("claudeAutoB", 5)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: calm, now, current }), + ).toMatchObject({ sticky: true, selection: { instanceId: "claudeAuto" } }); + + const busy = [claude("claudeAuto", 95), claude("claudeAutoB", 5)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: busy, now, current }), + ).toMatchObject({ sticky: false, selection: { instanceId: "claudeAutoB" } }); + }); + + it("steps down to other subscriptions when both Claude accounts are exhausted", () => { + const grok = { + ...claude("grok", 0, false), + driver: ProviderDriverKind.make("grok"), + models: [{ slug: "grok-4.7", name: "Grok 4.7", isCustom: false, capabilities: null }], + usageLimits: undefined, + } as unknown as ServerProvider; + const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100), grok]; + expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection).toEqual({ + instanceId: "grok", + model: "grok-4.7", + }); + }); + + it("returns null when nothing is usable", () => { + const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; + expect(resolveAutoModelSelection({ selection: auto(), providers, now })).toBeNull(); + }); +}); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts new file mode 100644 index 000000000000..87f997204b42 --- /dev/null +++ b/packages/shared/src/autoModel.ts @@ -0,0 +1,202 @@ +import { + isProviderAvailable, + type ModelSelection, + type ProviderDriverKind, + type ProviderOptionDescriptor, + type ServerProvider, +} from "@t3tools/contracts"; + +import { exhaustedUsageWindow } from "./usageLimits.ts"; + +/** + * "Auto" is a custom model (slug `auto`) on any provider instance. Picking it never reaches + * a provider: the server replaces it with a concrete model chosen here, from the providers' + * live usage limits. The level (`low` | `medium` | `high`) rides in the `effort` option. + */ +const AUTO_MODEL_SLUG = "auto"; +const AUTO_LEVELS = ["low", "medium", "high"] as const; +type AutoLevel = (typeof AUTO_LEVELS)[number]; +const DEFAULT_LEVEL: AutoLevel = "medium"; +/** Above this peak usage, a sticky model gives way when another candidate has more room. */ +const STICKY_MAX_USED_PERCENT = 90; + +interface AutoCandidate { + readonly driver: string; + readonly model: string; + /** The candidate's own reasoning effort for this level. */ + readonly effort: string; +} + +const claude = (model: string, effort: string): AutoCandidate => ({ + driver: "claudeAgent", + model, + effort, +}); +const codex = (model: string, effort: string): AutoCandidate => ({ + driver: "codex", + model, + effort, +}); +const grok = (effort: string): AutoCandidate => ({ driver: "grok", model: "grok-4.7", effort }); +const opencode = (model: string, effort: string): AutoCandidate => ({ + driver: "opencode", + model, + effort, +}); + +/** + * Orchestrator candidates per level, best first. Each level starts on its Claude model and + * steps down through the other subscriptions as limits run out. + */ +const AUTO_CANDIDATES: Readonly>> = { + high: [ + claude("claude-fable-5-2", "high"), + claude("claude-opus-5-5", "high"), + codex("gpt-6.1-sol", "high"), + codex("gpt-6-astra", "high"), + grok("high"), + codex("gpt-6-luna", "high"), + ], + medium: [ + claude("claude-opus-5-5", "medium"), + claude("claude-fable-5-2", "medium"), + codex("gpt-6.1-sol", "medium"), + codex("gpt-6-astra", "medium"), + claude("claude-sonnet-5-5", "medium"), + grok("medium"), + codex("gpt-6-luna", "medium"), + ], + low: [ + claude("claude-sonnet-5-5", "low"), + claude("claude-haiku-5-5", "low"), + opencode("opencode/big-pickle", "medium"), + opencode("opencode/deepseek-v4.1-flash-free", "medium"), + codex("gpt-6-luna", "low"), + grok("low"), + ], +}; + +/** The option each driver uses for reasoning effort. */ +const EFFORT_OPTION_ID: Readonly> = { + claudeAgent: "effort", + codex: "reasoningEffort", + grok: "reasoningEffort", + opencode: "variant", +}; + +export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { + return selection?.model === AUTO_MODEL_SLUG; +} + +function autoLevelOf(selection: ModelSelection): AutoLevel { + const value = selection.options?.find((option) => option.id === "effort")?.value; + return AUTO_LEVELS.find((level) => level === value) ?? DEFAULT_LEVEL; +} + +/** The `effort` descriptor an `auto` custom model declares, so pickers show Low/Medium/High. */ +export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { + id: "effort", + label: "Auto level", + type: "select", + options: [ + { id: "low", label: "Low", description: "Sonnet orchestrates; cheaper models do more" }, + { id: "medium", label: "Medium", description: "Opus orchestrates", isDefault: true }, + { id: "high", label: "High", description: "Fable orchestrates" }, + ], +}; + +function peakUsedPercent(provider: ServerProvider): number { + return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); +} + +/** Instances that list the `auto` model carry the Auto-mode prompt, so they win ties. */ +function isAutoAware(provider: ServerProvider): boolean { + return provider.models.some((model) => model.slug === AUTO_MODEL_SLUG); +} + +function usable(provider: ServerProvider, model: string, now: number): boolean { + return ( + provider.enabled && + provider.installed && + provider.auth.status !== "unauthenticated" && + isProviderAvailable(provider) && + provider.models.some((entry) => entry.slug === model) && + exhaustedUsageWindow(provider, now, model) === undefined + ); +} + +function effortOptions(provider: ServerProvider, candidate: AutoCandidate) { + const id = EFFORT_OPTION_ID[candidate.driver]; + const descriptor = provider.models + .find((entry) => entry.slug === candidate.model) + ?.capabilities?.optionDescriptors?.find((entry) => entry.id === id); + if (!id || descriptor?.type !== "select") return undefined; + return descriptor.options.some((choice) => choice.id === candidate.effort) + ? [{ id, value: candidate.effort }] + : undefined; +} + +function toSelection(provider: ServerProvider, candidate: AutoCandidate): ModelSelection { + const options = effortOptions(provider, candidate); + return { + instanceId: provider.instanceId, + model: candidate.model, + ...(options ? { options } : {}), + }; +} + +interface AutoResolution { + readonly selection: ModelSelection; + readonly level: AutoLevel; + /** True when the thread's current model was kept. */ + readonly sticky: boolean; +} + +/** + * Keeps the thread's model while it fits this level and is under 90% used (no account hop, no + * lost prompt cache); otherwise the first usable candidate, Auto-aware and least-used instance + * first. Null when nothing is usable. + */ +export function resolveAutoModelSelection(input: { + readonly selection: ModelSelection; + readonly providers: ReadonlyArray; + readonly now: number; + readonly current?: ModelSelection | null; +}): AutoResolution | null { + const level = autoLevelOf(input.selection); + const candidates = AUTO_CANDIDATES[level]; + + const current = input.current; + if (current && !isAutoModelSelection(current)) { + const provider = input.providers.find((entry) => entry.instanceId === current.instanceId); + const candidate = candidates.find( + (entry) => entry.driver === provider?.driver && entry.model === current.model, + ); + if ( + provider && + candidate && + usable(provider, candidate.model, input.now) && + peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT + ) { + return { selection: toSelection(provider, candidate), level, sticky: true }; + } + } + + for (const candidate of candidates) { + const instances = input.providers + .filter( + (provider) => + provider.driver === (candidate.driver as ProviderDriverKind) && + usable(provider, candidate.model, input.now), + ) + // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. + .sort( + (a, b) => + Number(isAutoAware(b)) - Number(isAutoAware(a)) || + peakUsedPercent(a) - peakUsedPercent(b), + ); + const provider = instances[0]; + if (provider) return { selection: toSelection(provider, candidate), level, sticky: false }; + } + return null; +} From 2d129358315efc4f235bf22e403c9066d27c3a5d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 09:45:23 +0100 Subject: [PATCH 038/230] Give the Auto model its own icon in the model picker --- apps/web/src/components/chat/ModelListRow.tsx | 1 + apps/web/src/components/chat/ProviderInstanceIcon.tsx | 9 +++++++-- apps/web/src/components/chat/ProviderModelPicker.tsx | 2 ++ docs/progress.md | 8 ++++++++ 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/ModelListRow.tsx b/apps/web/src/components/chat/ModelListRow.tsx index 74dae2dc2358..a483f93f417a 100644 --- a/apps/web/src/components/chat/ModelListRow.tsx +++ b/apps/web/src/components/chat/ModelListRow.tsx @@ -59,6 +59,7 @@ export const ModelListRow = memo(function ModelListRow(props: { - {isAcpRegistry ? ( + {props.modelSlug === "auto" ? ( + + ) : isAcpRegistry ? ( )} - {isCustomEndpoint ? null : props.showBadge ? ( + {isCustomEndpoint || props.modelSlug === "auto" ? null : props.showBadge ? ( Date: Thu, 12 Nov 2026 17:51:46 +0100 Subject: [PATCH 039/230] feat(web): pooled quota view with burn projection on Usage limits Every account of a provider adds into one pool (two Claude accounts = 200%). Each limits card now shows the summed headline, when the pool and the first account run out, the next reset, the burn rate, and a recorded and projected chart. Readings are kept in this browser to draw history and measure burn. --- .../usage/UsageLimitsPooled.browser.test.tsx | 52 ++++ .../components/usage/UsageLimitsPooled.tsx | 138 ++++++++-- .../src/components/usage/UsagePoolChart.tsx | 255 ++++++++++++++++++ .../src/components/usage/usagePoolHistory.ts | 64 +++++ packages/shared/package.json | 4 + .../shared/src/usagePoolProjection.test.ts | 144 ++++++++++ packages/shared/src/usagePoolProjection.ts | 179 ++++++++++++ 7 files changed, 813 insertions(+), 23 deletions(-) create mode 100644 apps/web/src/components/usage/UsagePoolChart.tsx create mode 100644 apps/web/src/components/usage/usagePoolHistory.ts create mode 100644 packages/shared/src/usagePoolProjection.test.ts create mode 100644 packages/shared/src/usagePoolProjection.ts diff --git a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx index ab114fbbd6f2..dc806b1341b2 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx @@ -63,3 +63,55 @@ describe("UsageLimitsPooled ChatGPT usage card", () => { .toBeVisible(); }); }); + +function claude(instanceId: string, displayName: string, weeklyUsed: number, resetsAt: string) { + return { + ...managedChatGpt(instanceId, displayName), + driver: ProviderDriverKind.make("claudeAgent"), + usageLimits: { + checkedAt, + windows: [ + { + id: "seven_day", + kind: "weekly" as const, + label: "Weekly", + usedPercent: weeklyUsed, + resetsAt, + windowDurationMins: 7 * 24 * 60, + }, + ], + }, + } satisfies ServerProvider; +} + +describe("UsageLimitsPooled pooled quota", () => { + it("adds the accounts into one pool and projects when it runs out", async () => { + const presentations = new Map([ + [ + EnvironmentId.make("desk"), + { + entry: { target: { label: "Desk" } }, + serverConfig: { + providers: [ + claude("claude_a", "Auto", 68, "2026-10-27T12:00:00.000Z"), + claude("claude_b", "Auto B", 27, "2026-10-31T13:00:00.000Z"), + ], + }, + }, + ], + ]); + await using screen = await render( + , + ); + + await expect.element(screen.getByText("105%", { exact: true })).toBeVisible(); + await expect.element(screen.getByText("of 200%")).toBeVisible(); + await expect.element(screen.getByText("Pool empty")).toBeVisible(); + await expect.element(screen.getByText("Burn, window avg")).toBeVisible(); + await expect + .element( + screen.getByRole("img", { name: "Weekly: pooled quota left, recorded and projected" }), + ) + .toBeVisible(); + }); +}); diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index 245b3021e4cd..6cce3e77e62f 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -12,6 +12,12 @@ import { type ResetCreditChoice, } from "@t3tools/shared/usageLimits"; import { T, useGT, useMessages } from "gt-react"; +import { + poolBurn, + projectionHorizon, + projectPool, + recordedPool, +} from "@t3tools/shared/usagePoolProjection"; import type { Popover as PopoverPrimitive } from "@base-ui/react/popover"; import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; import { AlertTriangleIcon, ExternalLinkIcon, TicketIcon } from "lucide-react"; @@ -21,6 +27,7 @@ import { type ReactNode, type RefObject, use, + useEffect, useLayoutEffect, useRef, useState, @@ -42,9 +49,14 @@ import { collectExternalUsageLinks, collectLimitNotices, cursorUsageWindowDetails, + formatDuration, formatResetsIn, resetCreditChoices, } from "@t3tools/shared/usageLimitsCopy"; +import { UsagePoolChart } from "./UsagePoolChart"; +import { poolHistoryKey, readPoolHistory, recordPoolReadings } from "./usagePoolHistory"; + +const BURN_LOOKBACK_MS = 3 * 3_600_000; function accountInitials(email: string): string { const [local = "", domain = ""] = email.split("@"); @@ -589,47 +601,120 @@ function PoolBar({ ); } +function PoolStat({ label, children }: { readonly label: string; readonly children: ReactNode }) { + return ( +
+ {label} + {children} +
+ ); +} + function PoolWindowCard({ pool, + historyKey, color, now, label, description, }: { readonly pool: LimitPoolWindow; + readonly historyKey: string; readonly color: string; readonly now: number; readonly label?: string | null | undefined; readonly description?: string | undefined; }) { - const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0); + const gt = useGT(); + const m = useMessages(); + const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat); + const samples = readPoolHistory(historyKey); + const horizon = projectionHorizon(pool); + const burn = poolBurn(pool, samples, now, BURN_LOOKBACK_MS); + const projection = projectPool(pool, now, { burnPerHour: burn.perHour, horizonMs: horizon }); + const from = now - horizon * 0.3; + const formatTime = (at: number) => + formatUpcomingTimestamp(new Date(at).toISOString(), timestampFormat, now, undefined, m); + const nextRefill = projection.refills[0]; + const firstEmpty = projection.firstEmpty + ? pool.members.find((member) => member.account.key === projection.firstEmpty?.accountKey) + : undefined; + const burnText = `${burn.perHour >= 10 ? Math.round(burn.perHour) : burn.perHour.toFixed(1)}%/h`; return ( -
-
- {label !== null ? ( - {label ?? pool.label} - ) : null} - - - {pool.remainingPercent}% - - - - left +
+
+
+ {label !== null ? ( + {label ?? pool.label} + ) : null} + + + {Math.round(projection.remaining)}% + + + + {gt("of {capacity}%", { + capacity: projection.capacity, + $context: "share of the pooled usage capacity", + })} + + {pool.pace ? : null} - {pool.pace ? : null} - - - {nextRefill && pool.columns.length > 1 ? ( - - ↻ +{nextRefill.restoresPercent}% - ) : null} +
+
+ + {projection.poolEmpty === null + ? gt("Not by {date}", { + date: new Date(now + horizon).toLocaleDateString([], { + month: "short", + day: "numeric", + }), + }) + : projection.poolEmpty <= now + ? gt("Empty now") + : formatTime(projection.poolEmpty)} + + + {firstEmpty && projection.firstEmpty ? ( + + {pool.members.length > 1 ? ( + + ) : null} + + {projection.firstEmpty.at <= now + ? gt("now", { $context: "an account is already empty" }) + : gt("in {duration}", { + duration: formatDuration(projection.firstEmpty.at - now, m), + })} + + + ) : ( + gt("None", { $context: "no account runs out" }) + )} + + + {nextRefill ? `+${Math.round(nextRefill.restores)}% ${formatTime(nextRefill.at)}` : "–"} + + + {burnText} + +
+ - {description ? ( -

{description}

- ) : null} + {description ?

{description}

: null}
); } @@ -658,6 +743,7 @@ function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: nu PopoverCreateHandle()); const segmentPopoverActions = useRef(null); const pools = collectLimitPools(collectLimitAccounts(presentations), now); + // Readings are stamped with each provider's checkedAt, so re-renders of the same data store + // nothing new. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps this browser's localStorage reading history in step with the limits it has been shown + useEffect(() => { + recordPoolReadings(pools, now); + }, [pools, now]); const notices = collectLimitNotices(presentations, m); const externalLinks = collectExternalUsageLinks(presentations, m); return ( diff --git a/apps/web/src/components/usage/UsagePoolChart.tsx b/apps/web/src/components/usage/UsagePoolChart.tsx new file mode 100644 index 000000000000..9e753375a44c --- /dev/null +++ b/apps/web/src/components/usage/UsagePoolChart.tsx @@ -0,0 +1,255 @@ +import type { PoolProjection } from "@t3tools/shared/usagePoolProjection"; +import { T, useGT } from "gt-react"; +import { useId, useLayoutEffect, useRef, useState } from "react"; + +import { observeResize } from "../../lib/observeResize"; + +const HEIGHT = 190; +const PAD = { left: 44, right: 8, top: 22, bottom: 22 }; +const DAY = 86_400_000; +const HOUR = 3_600_000; + +type Point = { readonly at: number; readonly remaining: number }; + +function percent(value: number) { + return `${Math.round(value)}%`; +} + +function timeTicks(from: number, to: number): ReadonlyArray<{ at: number; label: string }> { + const span = to - from; + if (span > 2 * DAY) { + const every = Math.max(1, Math.ceil(span / DAY / 10)); + const start = new Date(from); + start.setHours(24, 0, 0, 0); + const ticks = []; + for (let at = start.getTime(); at < to; at += every * DAY) { + ticks.push({ + at: at + DAY / 2, + label: new Date(at).toLocaleDateString([], { weekday: "short", day: "numeric" }), + }); + } + return ticks; + } + const start = new Date(from); + start.setMinutes(60, 0, 0); + while (start.getHours() % 3 !== 0) start.setHours(start.getHours() + 1); + const ticks = []; + for (let at = start.getTime(); at < to; at += 3 * HOUR) { + ticks.push({ + at, + label: new Date(at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }), + }); + } + return ticks; +} + +/** Drops a label that would overlap the one before it. */ +function spacedLabels(labels: readonly T[]): T[] { + const shown: T[] = []; + for (const label of labels) { + if (label.x - (shown.at(-1)?.x ?? -Infinity) >= 34) shown.push(label); + } + return shown; +} + +/** Pooled remaining quota: readings so far as a solid line, the projection dashed. */ +export function UsagePoolChart({ + color, + label, + recorded, + projection, + from, + to, + now, + formatTime, +}: { + readonly color: string; + readonly label: string; + readonly recorded: readonly Point[]; + readonly projection: PoolProjection; + readonly from: number; + readonly to: number; + readonly now: number; + readonly formatTime: (at: number) => string; +}) { + const gt = useGT(); + const box = useRef(null); + const [width, setWidth] = useState(0); + const [hover, setHover] = useState(null); + const gradient = useId(); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the container DOM width before paint and remeasures through a ResizeObserver + useLayoutEffect(() => { + const element = box.current; + if (!element) return; + const measure = () => setWidth(element.getBoundingClientRect().width); + measure(); + return observeResize(element, measure); + }, []); + + const cap = Math.max(100, projection.capacity); + const x = (at: number) => + PAD.left + ((at - from) / (to - from)) * Math.max(0, width - PAD.left - PAD.right); + const y = (value: number) => PAD.top + (HEIGHT - PAD.top - PAD.bottom) * (1 - value / cap); + const line = (points: readonly Point[]) => + points + .map((p, i) => `${i === 0 ? "M" : "L"}${x(p.at).toFixed(1)},${y(p.remaining).toFixed(1)}`) + .join(""); + const all = [...recorded, ...projection.points]; + const first = all[0]; + const last = all.at(-1); + const area = first && last ? `${line(all)}L${x(last.at)},${y(0)}L${x(first.at)},${y(0)}Z` : ""; + const start = projection.points[0]; + + const refillLabels = spacedLabels( + projection.refills.map((refill) => ({ ...refill, x: x(refill.at) })), + ); + + const pick = (clientX: number) => { + const rect = box.current?.getBoundingClientRect(); + if (!rect || all.length === 0) return; + const at = + from + ((clientX - rect.left - PAD.left) / (width - PAD.left - PAD.right)) * (to - from); + setHover( + all.reduce((best, p) => (Math.abs(p.at - at) < Math.abs(best.at - at) ? p : best), all[0]!), + ); + }; + + return ( +
+ {width > 0 ? ( + pick(event.clientX)} + onPointerLeave={() => setHover(null)} + > + + + + + + + {[0, cap / 2, cap].map((value) => ( + + + + {percent(value)} + + + ))} + {timeTicks(from, to).map((tick) => ( + + {tick.label} + + ))} + + {recorded.length > 0 && start ? ( + + ) : null} + + {refillLabels.map((refill) => ( + + +{percent(refill.restores)} + + ))} + + + Now + + {start ? ( + + ) : null} + {projection.poolEmpty !== null && projection.poolEmpty > now ? ( + + + + {gt("Empty {time}", { + time: formatTime(projection.poolEmpty), + $context: "when the usage pool runs out", + })} + + + ) : null} + {hover ? : null} + + ) : null} + {hover ? ( +
+
+ {formatTime(hover.at)} + {hover.at > now ? ` · ${gt("projected", { $context: "a forecast value" })}` : ""} +
+
+ {percent(hover.remaining)} of {percent(projection.capacity)} +
+
+ ) : null} +
+ ); +} diff --git a/apps/web/src/components/usage/usagePoolHistory.ts b/apps/web/src/components/usage/usagePoolHistory.ts new file mode 100644 index 000000000000..3780d4e6af53 --- /dev/null +++ b/apps/web/src/components/usage/usagePoolHistory.ts @@ -0,0 +1,64 @@ +import type { LimitPool, LimitPoolWindow } from "@t3tools/shared/usageLimits"; +import type { PoolSample } from "@t3tools/shared/usagePoolProjection"; +import * as Schema from "effect/Schema"; + +import { getLocalStorageItem, setLocalStorageItem } from "../../hooks/useLocalStorage"; + +// Providers report limits only as a current percentage, so this browser keeps the readings it +// has seen to draw the recorded line and measure burn. +const STORAGE_KEY = "t3code:usage-pool-history:v1"; +const KEEP_MS = 14 * 24 * 3_600_000; +const MIN_GAP_MS = 4 * 60_000; + +const Sample = Schema.Struct({ + at: Schema.Number, + used: Schema.Record(Schema.String, Schema.Number), +}); +const History = Schema.Record(Schema.String, Schema.Array(Sample)); +type History = typeof History.Type; + +export function poolHistoryKey(pool: LimitPool, window: LimitPoolWindow): string { + return `${pool.driver}:${window.kind}:${window.id}`; +} + +function read(): History { + try { + return getLocalStorageItem(STORAGE_KEY, History) ?? {}; + } catch { + return {}; + } +} + +export function readPoolHistory(key: string): readonly PoolSample[] { + return read()[key] ?? []; +} + +/** Stores one reading per window, stamped with when the provider was checked. */ +export function recordPoolReadings(pools: readonly LimitPool[], now: number): void { + const history: Record = { ...read() }; + let changed = false; + for (const pool of pools) { + for (const window of pool.windows) { + const checked = window.members + .map((member) => Date.parse(member.account.limits.checkedAt)) + .filter(Number.isFinite); + if (checked.length === 0) continue; + const at = Math.min(now, Math.max(...checked)); + const key = poolHistoryKey(pool, window); + const samples = (history[key] ?? []).filter((sample) => sample.at >= now - KEEP_MS); + const last = samples.at(-1); + if (last && at - last.at < MIN_GAP_MS) continue; + const used = Object.fromEntries( + window.members.map((member) => [member.account.key, member.window.usedPercent]), + ); + history[key] = [...samples, { at, used }]; + changed = true; + } + } + if (!changed) return; + try { + setLocalStorageItem(STORAGE_KEY, history, History); + } catch (error) { + console.error("Could not save usage limit readings.", error); + } +} diff --git a/packages/shared/package.json b/packages/shared/package.json index 9a8adb9c5bda..dc3a7c54a892 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -415,6 +415,10 @@ "types": "./src/usageLimits.ts", "import": "./src/usageLimits.ts" }, + "./usagePoolProjection": { + "types": "./src/usagePoolProjection.ts", + "import": "./src/usagePoolProjection.ts" + }, "./desktopAppControl": { "types": "./src/desktopAppControl.ts", "import": "./src/desktopAppControl.ts" diff --git a/packages/shared/src/usagePoolProjection.test.ts b/packages/shared/src/usagePoolProjection.test.ts new file mode 100644 index 000000000000..79ccd0905a18 --- /dev/null +++ b/packages/shared/src/usagePoolProjection.test.ts @@ -0,0 +1,144 @@ +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; + +import type { LimitPoolWindow } from "./usageLimits.ts"; +import { poolBurn, projectionHorizon, projectPool, recordedPool } from "./usagePoolProjection.ts"; + +const HOUR = 3_600_000; +const now = Date.parse("2026-11-12T12:00:00.000Z"); +const iso = (at: number) => DateTime.formatIso(DateTime.makeUnsafe(at)); + +function pool( + members: ReadonlyArray<{ key: string; used: number; resetsIn?: number; mins?: number }>, + kind: LimitPoolWindow["kind"] = "weekly", +): LimitPoolWindow { + const list = members.map((m) => ({ + account: { key: m.key } as LimitPoolWindow["members"][number]["account"], + window: { + id: "seven_day", + kind, + label: "Weekly", + usedPercent: m.used, + ...(m.resetsIn === undefined ? {} : { resetsAt: iso(now + m.resetsIn) }), + windowDurationMins: m.mins ?? 7 * 24 * 60, + }, + refillPercent: m.used, + })); + return { + id: "seven_day", + kind, + label: "Weekly", + members: list, + columns: list, + remainingPercent: 0, + usedPercent: 0, + pace: null, + resets: [], + }; +} + +describe("projectPool", () => { + it("sums every account into one pool", () => { + const projection = projectPool( + pool([ + { key: "a", used: 60, resetsIn: 48 * HOUR }, + { key: "b", used: 30, resetsIn: 120 * HOUR }, + ]), + now, + { burnPerHour: 0, horizonMs: 7 * 24 * HOUR }, + ); + expect(projection.capacity).toBe(200); + expect(projection.remaining).toBe(110); + expect(projection.poolEmpty).toBeNull(); + // With no spend, each reset gives back what that account had used. + expect(projection.refills.map((r) => [r.accountKey, r.restores, r.remainingAfter])).toEqual([ + ["a", 60, 170], + ["b", 30, 200], + ]); + expect(projection.points.at(-1)?.remaining).toBe(200); + }); + + it("spends the account that resets first and finds when the pool runs dry", () => { + const projection = projectPool( + pool([ + { key: "late", used: 0, resetsIn: 150 * HOUR }, + { key: "soon", used: 50, resetsIn: 140 * HOUR }, + ]), + now, + { burnPerHour: 10, horizonMs: 24 * HOUR, steps: 240 }, + ); + // 50 points left on "soon" at 10/h: empty after 5 h; then 100 on "late": pool dry at 15 h. + expect(projection.firstEmpty).toEqual({ at: now + 5 * HOUR, accountKey: "soon" }); + expect(projection.poolEmpty).toBe(now + 15 * HOUR); + }); + + it("reports an exhausted account as empty now", () => { + const projection = projectPool( + pool([ + { key: "a", used: 100, resetsIn: HOUR }, + { key: "b", used: 0, resetsIn: 5 * HOUR }, + ]), + now, + { burnPerHour: 0, horizonMs: 24 * HOUR }, + ); + expect(projection.firstEmpty).toEqual({ at: now, accountKey: "a" }); + expect(projection.poolEmpty).toBeNull(); + }); +}); + +describe("poolBurn", () => { + const twoAccounts = pool([ + { key: "a", used: 35, resetsIn: 100 * HOUR }, + { key: "b", used: 5, resetsIn: 100 * HOUR }, + ]); + + it("measures spend from stored readings and counts a drop as a reset", () => { + const burn = poolBurn( + twoAccounts, + [ + { at: now - 2 * HOUR, used: { a: 10, b: 90 } }, + { at: now - HOUR, used: { a: 20, b: 100 } }, + { at: now, used: { a: 35, b: 5 } }, + ], + now, + 3 * HOUR, + ); + // a: +10 +15, b: +10 then a reset worth 5 → 40 points over 2 h. + expect(burn).toEqual({ perHour: 20, source: "measured" }); + }); + + it("falls back to the average since each window opened", () => { + // Weekly windows with 100 h left have run 68 h: 35/68 + 5/68 points per hour. + const burn = poolBurn(twoAccounts, [{ at: now, used: { a: 35, b: 5 } }], now, 3 * HOUR); + expect(burn.source).toBe("window"); + expect(burn.perHour).toBeCloseTo(40 / 68, 6); + }); +}); + +describe("recordedPool", () => { + it("carries an account's last reading forward", () => { + const series = recordedPool( + pool([ + { key: "a", used: 0 }, + { key: "b", used: 0 }, + ]), + [ + { at: now - 3 * HOUR, used: { a: 10 } }, + { at: now - 2 * HOUR, used: { a: 20, b: 50 } }, + { at: now - HOUR, used: { b: 60 } }, + ], + now - 24 * HOUR, + ); + expect(series).toEqual([ + { at: now - 2 * HOUR, remaining: 130 }, + { at: now - HOUR, remaining: 120 }, + ]); + }); +}); + +describe("projectionHorizon", () => { + it("looks a day ahead for session windows and a week for weekly ones", () => { + expect(projectionHorizon(pool([{ key: "a", used: 0, mins: 300 }], "session"))).toBe(24 * HOUR); + expect(projectionHorizon(pool([{ key: "a", used: 0 }]))).toBe(7 * 24 * HOUR); + }); +}); diff --git a/packages/shared/src/usagePoolProjection.ts b/packages/shared/src/usagePoolProjection.ts new file mode 100644 index 000000000000..b157ac57fac5 --- /dev/null +++ b/packages/shared/src/usagePoolProjection.ts @@ -0,0 +1,179 @@ +/** + * Pooled quota projection: every account of a provider counts toward one pool (two Claude + * subscriptions = 200%). The pool drains at the current burn rate, spending the account that + * resets first, and each account refills when its window resets. + */ +import type { LimitPoolWindow } from "./usageLimits.ts"; + +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; +/** Measured burn needs at least this much history; shorter spans are mostly noise. */ +const MIN_MEASURED_SPAN = 15 * MINUTE; + +/** One reading of a pool: used percent per account key. */ +export interface PoolSample { + readonly at: number; + readonly used: Readonly>; +} + +interface PoolBurn { + /** Percentage points of the pool spent per hour. */ + readonly perHour: number; + /** "measured" comes from stored readings, "window" from the average since each window opened. */ + readonly source: "measured" | "window"; +} + +export interface PoolProjection { + readonly capacity: number; + readonly remaining: number; + readonly points: ReadonlyArray<{ readonly at: number; readonly remaining: number }>; + readonly refills: ReadonlyArray<{ + readonly at: number; + readonly accountKey: string; + /** Percentage points this reset gives back. */ + readonly restores: number; + /** Pool remaining right after the reset. */ + readonly remainingAfter: number; + }>; + readonly firstEmpty: { readonly at: number; readonly accountKey: string } | null; + readonly poolEmpty: number | null; +} + +const clampUsed = (value: number) => Math.max(0, Math.min(100, value)); + +function resetAt(resetsAt: string | undefined): number | null { + if (resetsAt === undefined) return null; + const at = Date.parse(resetsAt); + return Number.isFinite(at) ? at : null; +} + +/** How far ahead to project: a day for session windows, otherwise one full window. */ +export function projectionHorizon(pool: LimitPoolWindow): number { + const longest = Math.max(0, ...pool.members.map((m) => m.window.windowDurationMins ?? 0)); + if (pool.kind === "session" || (longest > 0 && longest <= 12 * 60)) return DAY; + if (pool.kind === "monthly" || longest >= 28 * 24 * 60) return 31 * DAY; + return 7 * DAY; +} + +function windowAverageBurn(pool: LimitPoolWindow, now: number): number { + let perHour = 0; + for (const { window } of pool.members) { + const at = resetAt(window.resetsAt); + if (at === null || !window.windowDurationMins) continue; + const elapsed = window.windowDurationMins * MINUTE - (at - now); + if (elapsed >= MIN_MEASURED_SPAN) perHour += clampUsed(window.usedPercent) / (elapsed / HOUR); + } + return perHour; +} + +/** + * Burn over the last `lookbackMs` from stored readings. A drop between readings means the + * window reset, so the new value counts as fresh spend. Falls back to the window average while + * the readings span less than 15 minutes. + */ +export function poolBurn( + pool: LimitPoolWindow, + samples: readonly PoolSample[], + now: number, + lookbackMs: number, +): PoolBurn { + const recent = samples.filter((sample) => sample.at >= now - lookbackMs && sample.at <= now); + const first = recent[0]; + const last = recent.at(-1); + if (!first || !last || last.at - first.at < MIN_MEASURED_SPAN) { + return { perHour: windowAverageBurn(pool, now), source: "window" }; + } + let spent = 0; + for (const { account } of pool.members) { + let previous: number | undefined; + for (const sample of recent) { + const used = sample.used[account.key]; + if (used === undefined) continue; + if (previous !== undefined) spent += used >= previous ? used - previous : used; + previous = used; + } + } + return { perHour: spent / ((last.at - first.at) / HOUR), source: "measured" }; +} + +export function projectPool( + pool: LimitPoolWindow, + now: number, + options: { readonly burnPerHour: number; readonly horizonMs: number; readonly steps?: number }, +): PoolProjection { + const accounts = pool.members.map((member) => ({ + key: member.account.key, + used: clampUsed(member.window.usedPercent), + reset: resetAt(member.window.resetsAt), + length: (member.window.windowDurationMins ?? 0) * MINUTE, + })); + const remainingNow = () => accounts.reduce((sum, account) => sum + 100 - account.used, 0); + const capacity = accounts.length * 100; + const remaining = remainingNow(); + const points = [{ at: now, remaining }]; + const refills: Array = []; + const exhausted = accounts.find((account) => account.used >= 100); + let firstEmpty = exhausted ? { at: now, accountKey: exhausted.key } : null; + let poolEmpty = accounts.length > 0 && remaining <= 0 ? now : null; + const steps = options.steps ?? 480; + const step = options.horizonMs / steps; + + for (let index = 1; index <= steps; index += 1) { + const at = now + index * step; + for (const account of accounts) { + while (account.reset !== null && account.reset <= at) { + const restores = account.used; + account.used = 0; + if (restores > 0.5) { + refills.push({ + at: account.reset, + accountKey: account.key, + restores, + remainingAfter: remainingNow(), + }); + } + account.reset = account.length > 0 ? account.reset + account.length : null; + } + } + let drain = (options.burnPerHour * step) / HOUR; + const spendable = accounts + .filter((account) => account.used < 100) + .sort((left, right) => (left.reset ?? Infinity) - (right.reset ?? Infinity)); + for (const account of spendable) { + if (drain <= 0) break; + // An unused window opens on first spend. + if (account.reset === null && account.used === 0 && account.length > 0) { + account.reset = at + account.length; + } + const take = Math.min(drain, 100 - account.used); + account.used += take; + drain -= take; + if (account.used >= 100 && firstEmpty === null) firstEmpty = { at, accountKey: account.key }; + } + const left = remainingNow(); + if (left <= 1e-6 && poolEmpty === null) poolEmpty = at; + points.push({ at, remaining: left }); + } + return { capacity, remaining, points, refills, firstEmpty, poolEmpty }; +} + +/** Pool remaining at each stored reading since `from`, carrying an account's last value forward. */ +export function recordedPool( + pool: LimitPoolWindow, + samples: readonly PoolSample[], + from: number, +): ReadonlyArray<{ readonly at: number; readonly remaining: number }> { + const keys = pool.members.map((member) => member.account.key); + const last: Record = {}; + const series: Array<{ at: number; remaining: number }> = []; + for (const sample of samples) { + for (const key of keys) { + const used = sample.used[key]; + if (used !== undefined) last[key] = clampUsed(used); + } + if (sample.at < from || keys.some((key) => last[key] === undefined)) continue; + series.push({ at: sample.at, remaining: keys.reduce((sum, key) => sum + 100 - last[key]!, 0) }); + } + return series; +} From 1bc8f2f8697f4b8ba12f9f71da090247a111032f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 12:44:18 +0100 Subject: [PATCH 040/230] Show the model and account Auto routes to in the model picker --- .../chat/ComposerFooterControls.tsx | 3 + .../components/chat/ModelPickerContent.tsx | 9 ++- .../components/chat/ProviderInstanceIcon.tsx | 21 ++++-- .../components/chat/ProviderModelPicker.tsx | 38 +++++++--- .../web/src/components/chat/autoRoute.test.ts | 75 +++++++++++++++++++ apps/web/src/components/chat/autoRoute.ts | 54 +++++++++++++ docs/progress.md | 7 ++ 7 files changed, 191 insertions(+), 16 deletions(-) create mode 100644 apps/web/src/components/chat/autoRoute.test.ts create mode 100644 apps/web/src/components/chat/autoRoute.ts diff --git a/apps/web/src/components/chat/ComposerFooterControls.tsx b/apps/web/src/components/chat/ComposerFooterControls.tsx index 1df9cdbd3233..e3c829c98942 100644 --- a/apps/web/src/components/chat/ComposerFooterControls.tsx +++ b/apps/web/src/components/chat/ComposerFooterControls.tsx @@ -320,6 +320,9 @@ export function ComposerModelPicker({ return ( ; onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; lockedProvider: ProviderDriverKind | null; @@ -793,6 +796,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { modelJumpLabelByKey, activeModelKey, selectedModelKeySet, + autoRouteLabel: props.autoRoute?.label, }; const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { @@ -1057,15 +1061,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { } const disabledReason = getModelDisabledReason?.(model.instanceId, model.slug) ?? null; + const autoRoute = model.slug === "auto" ? props.autoRoute : null; return ( - {props.modelSlug === "auto" ? ( - - ) : isAcpRegistry ? ( + {isAcpRegistry ? ( )} - {isCustomEndpoint || props.modelSlug === "auto" ? null : props.showBadge ? ( + {isCustomEndpoint ? null : props.modelSlug === "auto" ? ( + // Auto keeps the logo of the provider it routes to and marks it with a route badge. + + + + ) : props.showBadge ? ( ; onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; lockedProvider: ProviderDriverKind | null; @@ -130,6 +135,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { footer?: ReactNode; }) { const composerFloatingLayerProps = useComposerMenuProps(); + const nowMinute = useNowMinute(); const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false); const isMenuOpen = props.open ?? uncontrolledIsMenuOpen; const registry = useContext(RegistryContext); @@ -172,16 +178,29 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { (activeEntry?.driverKind === "opencode" || activeEntry?.driverKind === "antigravity" ? undefined : selectedInstanceOptions[0]); - const triggerTitle = selectedModel - ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) - : props.model === ANTIGRAVITY_DEFAULT_MODEL - ? gt("Choose model") - : props.model || gt("Choose model"); + const isAuto = props.model === "auto"; + // Names the model Auto would pick now, at this selection's level (default level elsewhere). + const autoRoute = describeAutoRoute({ + entries: props.instanceEntries, + ...(isAuto && props.modelSelectionOptions ? { options: props.modelSelectionOptions } : {}), + now: Date.parse(nowMinute), + }); + const triggerTitle = + isAuto && autoRoute + ? `Auto · ${autoRoute.label}` + : selectedModel + ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) + : props.model === ANTIGRAVITY_DEFAULT_MODEL + ? gt("Choose model") + : props.model || gt("Choose model"); const withUnavailable = (model: string, isUnavailable: boolean | undefined) => isUnavailable ? gt("{model} (Unavailable)", { model }) : model; - const triggerLabel = selectedModel - ? withUnavailable(getDisplayModelName(selectedModel), selectedModel.isUnavailable) - : triggerTitle; + const triggerLabel = + isAuto && autoRoute + ? triggerTitle + : selectedModel + ? withUnavailable(getDisplayModelName(selectedModel), selectedModel.isUnavailable) + : triggerTitle; const showInstanceBadge = activeEntry !== null && shouldShowInstanceBadge(activeEntry, props.instanceEntries); @@ -297,6 +316,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { workspaceCwd={props.workspaceCwd ?? null} activeInstanceId={activeInstanceId} model={props.model} + autoRoute={autoRoute} {...(props.selectedModels !== undefined ? { selectedModels: props.selectedModels } : {})} {...(props.onToggleModel ? { @@ -417,7 +437,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { // Narrow compacted composers hide the provider icon before truncating the name. , + usedPercent: number, +): ServerProvider { + return { + instanceId: ProviderInstanceId.make(id), + driver: ProviderDriverKind.make(driver), + displayName, + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-11-13T11:00:00.000Z", + models: models.map((model) => ({ ...model, isCustom: false, capabilities: null })), + slashCommands: [], + skills: [], + usageLimits: { + windows: [ + { + id: "five_hour", + kind: "session", + label: "Session", + usedPercent, + resetsAt: "2026-11-13T15:00:00.000Z", + }, + ], + }, + } as unknown as ServerProvider; +} + +const claudeModels = [ + { slug: "claude-fable-5-2", name: "Claude Fable 5.2" }, + { slug: "claude-opus-5-5", name: "Claude Opus 5.5" }, + { slug: "claude-sonnet-5-5", name: "Claude Sonnet 5.5" }, + { slug: "auto", name: "Auto" }, +]; + +describe("describeAutoRoute", () => { + it("names the Claude model and account Auto would use", () => { + const entries = deriveProviderInstanceEntries([ + provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 70), + provider("claudeAutoB", "Auto B", "claudeAgent", claudeModels, 10), + ]); + const medium = describeAutoRoute({ entries, now }); + expect(medium?.driverKind).toBe("claudeAgent"); + expect(medium?.label).toMatch(/^.*Opus 5\.5 \(B\)$/); + + const high = describeAutoRoute({ entries, options: [{ id: "effort", value: "high" }], now }); + expect(high?.label).toMatch(/Fable 5\.2 \(B\)$/); + }); + + it("names another provider when both Claude accounts are used up", () => { + const entries = deriveProviderInstanceEntries([ + provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 100), + provider("claudeAutoB", "Auto B", "claudeAgent", claudeModels, 100), + provider("grok", "Grok Build", "grok", [{ slug: "grok-4.7", name: "Grok 4.7" }], 0), + ]); + expect(describeAutoRoute({ entries, now })).toMatchObject({ + driverKind: "grok", + label: expect.stringMatching(/Grok 4\.7 \(Grok Build\)$/), + }); + }); +}); diff --git a/apps/web/src/components/chat/autoRoute.ts b/apps/web/src/components/chat/autoRoute.ts new file mode 100644 index 000000000000..d1a89457bf7f --- /dev/null +++ b/apps/web/src/components/chat/autoRoute.ts @@ -0,0 +1,54 @@ +import { + ProviderInstanceId, + type ModelSelection, + type ProviderDriverKind, +} from "@t3tools/contracts"; +import { resolveAutoModelSelection } from "@t3tools/shared/autoModel"; + +import type { ProviderInstanceEntry } from "../../providerInstances"; +import { getTriggerDisplayModelName } from "./providerIconUtils"; + +/** What the `auto` model would run as right now, for labels such as "Auto · Opus 5.5 (B)". */ +export interface AutoRoute { + readonly driverKind: ProviderDriverKind; + /** The concrete model and its account, such as "Opus 5.5 (B)". */ + readonly label: string; +} + +/** + * Mirrors the server's routing (same resolver, same live usage snapshots), so the picker shows + * the model a new message would get. The server still decides per message; a thread already on + * a model may stay on it. + */ +export function describeAutoRoute(input: { + readonly entries: ReadonlyArray; + readonly options?: ModelSelection["options"]; + readonly now: number; +}): AutoRoute | null { + const resolution = resolveAutoModelSelection({ + selection: { + instanceId: ProviderInstanceId.make("auto"), + model: "auto", + ...(input.options ? { options: input.options } : {}), + }, + providers: input.entries.map((entry) => entry.snapshot), + now: input.now, + }); + if (!resolution) return null; + const entry = input.entries.find( + (candidate) => candidate.instanceId === resolution.selection.instanceId, + ); + const model = entry?.models.find((candidate) => candidate.slug === resolution.selection.model); + if (!entry || !model) return null; + // Claude instances are named "Auto" (account A) and "Auto B"; other providers keep their name. + const account = + entry.driverKind === "claudeAgent" + ? /\bB$/.test(entry.displayName) + ? "B" + : "A" + : entry.displayName; + return { + driverKind: entry.driverKind, + label: `${getTriggerDisplayModelName(model, entry.driverKind)} (${account})`, + }; +} diff --git a/docs/progress.md b/docs/progress.md index 46c2223b1d5c..3ba9579db6ab 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -16,3 +16,10 @@ - How: `ProviderInstanceIcon` takes an optional `modelSlug`; `ModelListRow` and `ProviderModelPicker` pass it. Lint rules ruled out Sparkles and raw palette colors. - Deploy: web-only, so the new `apps/web/dist` was copied into `apps/server/dist/client`; no service restart. The web build took ~45 min on the hub (disk-bound). - Next: keep "Auto" shown in the composer after the first message (needs the thread to remember the Auto selection). + +## 2026-11-13 — Auto shows the model it routes to + +- What: the `auto` entry keeps the logo of the provider it routes to (the Claude logo while Claude has room) with a small route badge, and its label names the model and account, e.g. "Auto · Opus 5.5 (B)", in the picker rows and on the composer button. +- Why: Tomáš wanted to see which Claude model Auto uses; the plain route icon hid it. +- How: `describeAutoRoute` (web) runs the server's `resolveAutoModelSelection` on the client's provider snapshots, at the composer's Auto level, on a minute clock. The server still decides per message (a thread may stay on its current model until 90% used). +- Tests: `autoRoute.test.ts` (2 tests: A/B pick per level, fallback to Grok). The test run alone took ~14 min on the hub. From 9cdd0ec00e06367be1e657b7731f2b5e3e814b27 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 13:03:44 +0100 Subject: [PATCH 041/230] Auto routes Claude A/B by 5-hour use and weekly reset, adds Antigravity, lists levels as picker rows Between Claude accounts, Auto takes the freer 5-hour window; within 10 points it spends the account whose weekly quota resets first. Antigravity's Claude models follow the Claude subscriptions at every level. auto-low/auto-medium/auto-high fix the level in the slug so the Auto picker tab lists one row per level. Usage limits open with a per-subscription overview. --- .../components/chat/ModelPickerContent.tsx | 13 ++- .../components/chat/ProviderInstanceIcon.tsx | 3 +- .../components/chat/ProviderModelPicker.tsx | 12 ++- apps/web/src/components/chat/autoRoute.ts | 4 +- .../components/usage/UsageLimitsPooled.tsx | 55 +++++++++++++ docs/progress.md | 8 ++ packages/shared/src/autoModel.test.ts | 79 ++++++++++++++++++- packages/shared/src/autoModel.ts | 68 +++++++++++++--- 8 files changed, 223 insertions(+), 19 deletions(-) diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index 4c0375a98574..ee8aae2da6d3 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -42,6 +42,7 @@ import { ComboboxListVirtualized, } from "../ui/combobox"; import { ModelEsque } from "./providerIconUtils"; +import { isAutoModelSlug } from "@t3tools/shared/autoModel"; import type { AutoRoute } from "./autoRoute"; import { isCommandPaletteOpen } from "../../commandPaletteBus"; import { registerModelPickerContent } from "../../modelPickerVisibility"; @@ -335,8 +336,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { workspaceCwd?: string | null; activeInstanceId: ProviderInstanceId; model: string; - /** What the `auto` model routes to right now; its rows show it. */ - autoRoute?: AutoRoute | null; + /** What an Auto model row (`auto`, `auto-low`, ...) routes to right now; its row shows it. */ + autoRouteFor?: (slug: string) => AutoRoute | null; selectedModels?: ReadonlyArray<{ instanceId: ProviderInstanceId; model: string }>; onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; lockedProvider: ProviderDriverKind | null; @@ -796,7 +797,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { modelJumpLabelByKey, activeModelKey, selectedModelKeySet, - autoRouteLabel: props.autoRoute?.label, + autoRouteLabels: ["auto", "auto-low", "auto-medium", "auto-high"] + .map((slug) => props.autoRouteFor?.(slug)?.label ?? "") + .join("|"), }; const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { @@ -1061,7 +1064,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { } const disabledReason = getModelDisabledReason?.(model.instanceId, model.slug) ?? null; - const autoRoute = model.slug === "auto" ? props.autoRoute : null; + const autoRoute = isAutoModelSlug(model.slug) + ? (props.autoRouteFor?.(model.slug) ?? null) + : null; return ( )} - {isCustomEndpoint ? null : props.modelSlug === "auto" ? ( + {isCustomEndpoint ? null : isAutoModelSlug(props.modelSlug) ? ( // Auto keeps the logo of the provider it routes to and marks it with a route badge. + describeAutoRoute({ entries: props.instanceEntries, model: slug, now }); const triggerTitle = isAuto && autoRoute ? `Auto · ${autoRoute.label}` @@ -316,7 +322,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { workspaceCwd={props.workspaceCwd ?? null} activeInstanceId={activeInstanceId} model={props.model} - autoRoute={autoRoute} + autoRouteFor={autoRouteFor} {...(props.selectedModels !== undefined ? { selectedModels: props.selectedModels } : {})} {...(props.onToggleModel ? { diff --git a/apps/web/src/components/chat/autoRoute.ts b/apps/web/src/components/chat/autoRoute.ts index d1a89457bf7f..eff72e2a9e71 100644 --- a/apps/web/src/components/chat/autoRoute.ts +++ b/apps/web/src/components/chat/autoRoute.ts @@ -22,13 +22,15 @@ export interface AutoRoute { */ export function describeAutoRoute(input: { readonly entries: ReadonlyArray; + /** `auto`, or a fixed-level `auto-low` / `auto-medium` / `auto-high`. */ + readonly model?: string; readonly options?: ModelSelection["options"]; readonly now: number; }): AutoRoute | null { const resolution = resolveAutoModelSelection({ selection: { instanceId: ProviderInstanceId.make("auto"), - model: "auto", + model: input.model ?? "auto", ...(input.options ? { options: input.options } : {}), }, providers: input.entries.map((entry) => entry.snapshot), diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index 6cce3e77e62f..d0c3e5f43f99 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -755,6 +755,60 @@ function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: nu ); } +/** One row per subscription: every window it reports, so no account hides inside a pool. */ +function SubscriptionsOverview({ + pools, + now, +}: { + readonly pools: readonly LimitPool[]; + readonly now: number; +}) { + const rows = pools.flatMap((pool) => pool.accounts.map((account) => ({ pool, account }))); + if (rows.length === 0) return null; + return ( +
+

+ Subscriptions +

+
+ {rows.map(({ pool, account }) => ( +
+ + + + + {account.limits.windows.map((window) => { + const resetsIn = formatResetsIn(window, now); + return ( + + {window.label} + {remainingPercent(window)}% + {resetsIn ? {resetsIn.replace("resets in ", "↻ ")} : null} + + ); + })} +
+ ))} +
+
+ ); +} + export function UsageLimitsPooled({ presentations, now, @@ -782,6 +836,7 @@ export function UsageLimitsPooled({ No provider on the selected environments reports subscription limits.

) : null} + {pools.map((pool) => ( diff --git a/docs/progress.md b/docs/progress.md index 3ba9579db6ab..1a91af83a5bb 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -23,3 +23,11 @@ - Why: Tomáš wanted to see which Claude model Auto uses; the plain route icon hid it. - How: `describeAutoRoute` (web) runs the server's `resolveAutoModelSelection` on the client's provider snapshots, at the composer's Auto level, on a minute clock. The server still decides per message (a thread may stay on its current model until 90% used). - Tests: `autoRoute.test.ts` (2 tests: A/B pick per level, fallback to Grok). The test run alone took ~14 min on the hub. + +## 2026-11-13: Auto routes by 5-hour use and weekly reset; Auto levels as picker rows; subscriptions overview + +- What: Auto now picks between Claude accounts by the freer 5-hour window; when two accounts are within 10 points, it spends the one whose weekly quota resets first (unused quota is lost at reset). Antigravity's Claude models (Opus 4.6 Thinking, Sonnet 4.6) sit right after the Claude subscriptions in every level. `auto-low` / `auto-medium` / `auto-high` fix the level in the model slug, so the Auto tab in the picker lists one row per level, each naming its current route. Usage → Limits opens with a Subscriptions table: one row per account with every window's remaining % and reset. +- Why: Tomáš wants Auto to always use Claude A/B first and route by 5-hour room and weekly expiry, use the Antigravity subscription too, show its levels like other models, and see each subscription next to the pooled view. +- Numbers: autoModel tests 9/9 (3 new routing cases failed before the change, plus a level-slug test). Web typecheck clean in 47 s warm. +- What worked: the Limits page showed Claude and distinct A/B numbers once the hub was quiet. The missing Claude section and copied numbers came from limit probes timing out while the hub was overloaded (load 11, IO pressure ~90). +- Next: one combined web + server build, deployed with a stop/start of t3code.service, then settings switch the Auto tab to the three level rows. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index e7846c214e74..eda559c93c55 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { AUTO_LEVEL_DESCRIPTOR, resolveAutoModelSelection } from "./autoModel.ts"; +import { AUTO_LEVEL_DESCRIPTOR, isAutoModelSlug, resolveAutoModelSelection } from "./autoModel.ts"; const now = Date.parse("2026-11-12T12:00:00.000Z"); const resetsAt = "2026-11-12T15:00:00.000Z"; @@ -58,6 +58,18 @@ function claude(id: string, usedPercent: number, autoAware = true): ServerProvid } as unknown as ServerProvider; } +function withWeekly(provider: ServerProvider, usedPercent: number, weeklyResetsAt: string) { + return { + ...provider, + usageLimits: { + windows: [ + ...(provider.usageLimits?.windows ?? []), + { id: "seven_day", kind: "weekly", label: "Weekly", usedPercent, resetsAt: weeklyResetsAt }, + ], + }, + } as unknown as ServerProvider; +} + const auto = (level?: string): ModelSelection => ({ instanceId: ProviderInstanceId.make("claudeAuto"), model: "auto", @@ -125,6 +137,71 @@ describe("resolveAutoModelSelection", () => { }); }); + it("routes to the account with less of its 5-hour window used", () => { + // A has the busier week but a nearly unused 5-hour window, so it can take work right now. + const providers = [ + withWeekly(claude("claudeAutoB", 50), 20, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 10), 60, "2026-11-18T12:00:00.000Z"), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, + ).toBe("claudeAuto"); + }); + + it("with similar 5-hour use, spends the account whose weekly limit resets first", () => { + // B has slightly less 5-hour use, but A's unused weekly quota is gone tomorrow. + const providers = [ + withWeekly(claude("claudeAutoB", 25), 40, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 30), 40, "2026-11-13T12:00:00.000Z"), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, + ).toBe("claudeAuto"); + }); + + it("falls back to Claude on the Antigravity subscription before other providers", () => { + const antigravity = { + ...claude("antigravity", 0, false), + driver: ProviderDriverKind.make("antigravity"), + models: ["claude-opus-4-6-thinking", "claude-sonnet-4-6"].map((slug) => ({ + slug, + name: slug, + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "thinking_level", + label: "Thinking", + type: "select" as const, + options: ["low", "medium", "high"].map((id) => ({ id, label: id })), + }, + ], + }, + })), + } as unknown as ServerProvider; + const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100), antigravity]; + expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection).toEqual({ + instanceId: "antigravity", + model: "claude-opus-4-6-thinking", + options: [{ id: "thinking_level", value: "medium" }], + }); + }); + + it("reads the level from auto-low / auto-medium / auto-high", () => { + const providers = [claude("claudeAuto", 10)]; + const pick = (model: string) => + resolveAutoModelSelection({ + selection: { instanceId: ProviderInstanceId.make("claudeAuto"), model }, + providers, + now, + })?.selection.model; + expect(pick("auto-high")).toBe("claude-fable-5-2"); + expect(pick("auto-medium")).toBe("claude-opus-5-5"); + expect(pick("auto-low")).toBe("claude-sonnet-5-5"); + expect(isAutoModelSlug("auto-low")).toBe(true); + expect(isAutoModelSlug("auto-max")).toBe(false); + }); + it("returns null when nothing is usable", () => { const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; expect(resolveAutoModelSelection({ selection: auto(), providers, now })).toBeNull(); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 87f997204b42..d76eda593edb 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -38,6 +38,12 @@ const codex = (model: string, effort: string): AutoCandidate => ({ effort, }); const grok = (effort: string): AutoCandidate => ({ driver: "grok", model: "grok-4.7", effort }); +/** Claude models on the Antigravity (Google) subscription: a third Claude pool. */ +const antigravity = (model: string, effort: string): AutoCandidate => ({ + driver: "antigravity", + model, + effort, +}); const opencode = (model: string, effort: string): AutoCandidate => ({ driver: "opencode", model, @@ -52,6 +58,7 @@ const AUTO_CANDIDATES: Readonly>> high: [ claude("claude-fable-5-2", "high"), claude("claude-opus-5-5", "high"), + antigravity("claude-opus-4-6-thinking", "high"), codex("gpt-6.1-sol", "high"), codex("gpt-6-astra", "high"), grok("high"), @@ -60,6 +67,7 @@ const AUTO_CANDIDATES: Readonly>> medium: [ claude("claude-opus-5-5", "medium"), claude("claude-fable-5-2", "medium"), + antigravity("claude-opus-4-6-thinking", "medium"), codex("gpt-6.1-sol", "medium"), codex("gpt-6-astra", "medium"), claude("claude-sonnet-5-5", "medium"), @@ -69,6 +77,7 @@ const AUTO_CANDIDATES: Readonly>> low: [ claude("claude-sonnet-5-5", "low"), claude("claude-haiku-5-5", "low"), + antigravity("claude-sonnet-4-6", "low"), opencode("opencode/big-pickle", "medium"), opencode("opencode/deepseek-v4.1-flash-free", "medium"), codex("gpt-6-luna", "low"), @@ -82,13 +91,26 @@ const EFFORT_OPTION_ID: Readonly> = { codex: "reasoningEffort", grok: "reasoningEffort", opencode: "variant", + antigravity: "thinking_level", }; +/** + * `auto` takes its level from the `effort` option; `auto-low`, `auto-medium` and `auto-high` + * fix it in the slug, so a picker can list one row per level. + */ +export function isAutoModelSlug(slug: string | null | undefined): boolean { + return ( + slug === AUTO_MODEL_SLUG || AUTO_LEVELS.some((level) => slug === `${AUTO_MODEL_SLUG}-${level}`) + ); +} + export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { - return selection?.model === AUTO_MODEL_SLUG; + return isAutoModelSlug(selection?.model); } function autoLevelOf(selection: ModelSelection): AutoLevel { + const fixed = AUTO_LEVELS.find((level) => selection.model === `${AUTO_MODEL_SLUG}-${level}`); + if (fixed) return fixed; const value = selection.options?.find((option) => option.id === "effort")?.value; return AUTO_LEVELS.find((level) => level === value) ?? DEFAULT_LEVEL; } @@ -105,13 +127,45 @@ export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { ], }; +/** Accounts whose 5-hour use differs by less than this many points count as equally free. */ +const SESSION_BAND_PERCENT = 10; + +function sessionUsedPercent(provider: ServerProvider): number { + const windows = (provider.usageLimits?.windows ?? []).filter((w) => w.kind === "session"); + return Math.max(0, ...windows.map((w) => w.usedPercent ?? 0)); +} + +/** When the soonest weekly window resets; unused weekly quota is lost then. */ +function weeklyResetAt(provider: ServerProvider): number { + const resets = (provider.usageLimits?.windows ?? []) + .filter((w) => w.kind === "weekly" && w.resetsAt !== undefined) + .map((w) => Date.parse(w.resetsAt!)) + .filter(Number.isFinite); + return resets.length > 0 ? Math.min(...resets) : Infinity; +} + +/** + * Best instance first: Auto-aware (carries the Auto prompt), then the freer 5-hour window, + * then, between accounts with similar 5-hour use, the one whose weekly quota resets first. + */ +function compareInstances(a: ServerProvider, b: ServerProvider): number { + const aware = Number(isAutoAware(b)) - Number(isAutoAware(a)); + if (aware !== 0) return aware; + const session = sessionUsedPercent(a) - sessionUsedPercent(b); + if (Math.abs(session) >= SESSION_BAND_PERCENT) return session; + const weekly = weeklyResetAt(a) - weeklyResetAt(b); + if (Number.isFinite(weekly) && weekly !== 0) return weekly; + if (weekly === Infinity || weekly === -Infinity) return weekly > 0 ? 1 : -1; + return session || peakUsedPercent(a) - peakUsedPercent(b); +} + function peakUsedPercent(provider: ServerProvider): number { return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); } /** Instances that list the `auto` model carry the Auto-mode prompt, so they win ties. */ function isAutoAware(provider: ServerProvider): boolean { - return provider.models.some((model) => model.slug === AUTO_MODEL_SLUG); + return provider.models.some((model) => isAutoModelSlug(model.slug)); } function usable(provider: ServerProvider, model: string, now: number): boolean { @@ -154,8 +208,8 @@ interface AutoResolution { /** * Keeps the thread's model while it fits this level and is under 90% used (no account hop, no - * lost prompt cache); otherwise the first usable candidate, Auto-aware and least-used instance - * first. Null when nothing is usable. + * lost prompt cache); otherwise the first usable candidate on the best instance (see + * `compareInstances`). Null when nothing is usable. */ export function resolveAutoModelSelection(input: { readonly selection: ModelSelection; @@ -190,11 +244,7 @@ export function resolveAutoModelSelection(input: { usable(provider, candidate.model, input.now), ) // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. - .sort( - (a, b) => - Number(isAutoAware(b)) - Number(isAutoAware(a)) || - peakUsedPercent(a) - peakUsedPercent(b), - ); + .sort(compareInstances); const provider = instances[0]; if (provider) return { selection: toSelection(provider, candidate), level, sticky: false }; } From 46c8001d0bb3f4c58d7b713a7845ac42e29715e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 14:24:07 +0100 Subject: [PATCH 042/230] Name the chosen Auto level on the model picker button MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The button showed the model Auto routes to ("Auto · Opus 5.5 (A)"), which read as if Auto Medium were Opus. It now shows the level, such as "Auto Medium", and the tooltip names the current route. --- .../components/chat/ProviderModelPicker.tsx | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 30c9512c7e0f..078433557f9b 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -191,22 +191,24 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { // Each Auto level row in the list names its own route. const autoRouteFor = (slug: string) => describeAutoRoute({ entries: props.instanceEntries, model: slug, now }); - const triggerTitle = - isAuto && autoRoute - ? `Auto · ${autoRoute.label}` - : selectedModel - ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) - : props.model === ANTIGRAVITY_DEFAULT_MODEL - ? gt("Choose model") - : props.model || gt("Choose model"); + // The button names the chosen Auto level; the model it routes to now goes in the tooltip. + const autoName = selectedModel ? getDisplayModelName(selectedModel) : "Auto"; + const triggerTitle = isAuto + ? autoName + : selectedModel + ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) + : props.model === ANTIGRAVITY_DEFAULT_MODEL + ? gt("Choose model") + : props.model || gt("Choose model"); const withUnavailable = (model: string, isUnavailable: boolean | undefined) => isUnavailable ? gt("{model} (Unavailable)", { model }) : model; - const triggerLabel = - isAuto && autoRoute - ? triggerTitle - : selectedModel - ? withUnavailable(getDisplayModelName(selectedModel), selectedModel.isUnavailable) - : triggerTitle; + const triggerLabel = isAuto + ? autoRoute + ? `${autoName} · now ${autoRoute.label}` + : autoName + : selectedModel + ? withUnavailable(getDisplayModelName(selectedModel), selectedModel.isUnavailable) + : triggerTitle; const showInstanceBadge = activeEntry !== null && shouldShowInstanceBadge(activeEntry, props.instanceEntries); From 6dbd06f1284164d0feebb48f6ed251bc73c5a811 Mon Sep 17 00:00:00 2001 From: radys-s Date: Fri, 13 Nov 2026 14:24:39 +0100 Subject: [PATCH 043/230] docs: tell agents to commit each medium step with its origin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agents batched a whole task into one commit at the end, so history could not show which request or review finding produced which change. AGENTS.md gains a Commits section: commit and push each finished, verified step of medium size or larger, one idea per commit, with a body that states why and where the change came from (issue, PR, review finding, thread link, or the request in one line). Origin: Tomáš asked for more frequent, traceable orchestrator commits. --- .github/pull_request_template.md | 1 + AGENTS.md | 9 +++++++++ docs/progress.md | 7 +++++++ 3 files changed, 17 insertions(+) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 94157c4135fa..5325e46142f4 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -3,6 +3,7 @@ Read CONTRIBUTING.md before opening a PR. Review capacity is limited, and meetin the requirements does not guarantee review or merging. Solve one underlying problem. The same requirements apply to drafts. Draft status does not defer triage or closure. Use a conventional commit title in plain language, such as "fix(web): new threads no longer spike CPU". +Keep one step per commit, and say in each commit body why it exists and where it came from. --> ## Problem diff --git a/AGENTS.md b/AGENTS.md index 12f6c581956c..e3780df12af0 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -148,6 +148,14 @@ For mobile verification, a missing or outdated native client is an install step, `evals/` checks how real models behave with T3 Code's model-facing text: agent instructions, MCP tool descriptions and schemas, and generated titles. Before you change that text, read [evals/README.md](evals/README.md) and run the evals it names. When you fix a model behavior bug, add a case that fails before the fix. +## Commits + +- Commit as you go, not once at the end. Each finished, verified step of medium size or larger gets its own commit right away: a bug fix, a feature slice, a refactor, a test suite, a doc update. Fold small edits (a typo, a rename, a review nit) into the step they belong to. +- One commit is one idea. If the title needs "and", split it. Every commit should build and pass the checks for the files it touches, so `git bisect` and `git revert` work on it alone. +- Title: conventional commit, as for PRs. Body: why the change exists, what it changes, and its origin, the issue, PR, review finding, or thread link that asked for it, or the user's request in one line. A reader of `git log` or `git blame` should reach the reason without the chat. +- Commit worker or delegate output only after you review and check it. Push after each commit on a task branch so the work is never only local. +- Never commit to `main` directly. Never rewrite commits that are already pushed unless the developer asks. + ## Pull requests - Never make a PR unless the developer explicitly asks you to do so. @@ -157,6 +165,7 @@ For mobile verification, a missing or outdated native client is an install step, - UI changes need before/after images. Motion or timing needs a short video. - Upload PR evidence to GitHub. Never commit PR-only screenshots or assets such as `.github/pr-assets/`. - One request is one PR. Split it only when the maintainer asks. Outside contributions follow the stricter [one problem per PR](CONTRIBUTING.md#one-problem) rule. +- Merge with a merge commit (`gh pr merge --merge`) so the per-step commits stay in `main`'s history. Squash only when the maintainer asks. - When babysitting: call `watch_pull_request` and end your turn. T3 Code wakes you on checks, comments, or conflicts. Do not poll or sleep. Verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit. ## Documentation diff --git a/docs/progress.md b/docs/progress.md index 1a91af83a5bb..821d5452b229 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -31,3 +31,10 @@ - Numbers: autoModel tests 9/9 (3 new routing cases failed before the change, plus a level-slug test). Web typecheck clean in 47 s warm. - What worked: the Limits page showed Claude and distinct A/B numbers once the hub was quiet. The missing Claude section and copied numbers came from limit probes timing out while the hub was overloaded (load 11, IO pressure ~90). - Next: one combined web + server build, deployed with a stop/start of t3code.service, then settings switch the Auto tab to the three level rows. + +## 2026-11-13: Agents commit each step with its origin + +- What: `AGENTS.md` gets a Commits section. Agents commit and push each finished, checked step of medium size or larger, one idea per commit, with a body that says why and where the change came from (issue, PR, review finding, thread link, or the request). PRs merge with a merge commit so those steps stay in `main`. The PR template repeats the rule in one line. Outside the repo, `~/.agents/T3-CODE.md` and the `auto` and `swarm` skills got the same rule. +- Why: Tomáš wants to trace a problem back to the step and request that caused it. One big commit per task, or a squash merge, hides that. +- Numbers: docs only, 4 commits in PR #4. The fork runs no CI checks on PRs. +- Next: watch whether agents keep the cadence. If they do not, add the rule to the built-in orchestration instructions (`orchestrationInstructions.ts`, needs evals). From 508e3c0372fdbdda7638c1ebf448cc201e48b89c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 15:34:22 +0100 Subject: [PATCH 044/230] feat(shared): stagger Claude A/B 5-hour windows in Auto routing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auto sent work to the account with less 5-hour use, so both windows started together and ran out together. It now keeps using the account whose window is already running until any of its windows reaches 90%, then moves to the other, so one refreshes while the other works. Within 10 points of 5-hour use, the sooner weekly reset still goes first. Origin: Tomáš asked that Auto pick the plan closer to running out and offset the 5-hour windows so one refreshes while the other is nearly used up. GPT review loop: 2 rounds, approved. --- .../web/src/components/chat/autoRoute.test.ts | 2 +- docs/progress.md | 7 ++ packages/shared/src/autoModel.test.ts | 90 ++++++++++++++++--- packages/shared/src/autoModel.ts | 35 ++++++-- 4 files changed, 111 insertions(+), 23 deletions(-) diff --git a/apps/web/src/components/chat/autoRoute.test.ts b/apps/web/src/components/chat/autoRoute.test.ts index fae0bdef7887..85ae44be3be8 100644 --- a/apps/web/src/components/chat/autoRoute.test.ts +++ b/apps/web/src/components/chat/autoRoute.test.ts @@ -50,7 +50,7 @@ const claudeModels = [ describe("describeAutoRoute", () => { it("names the Claude model and account Auto would use", () => { const entries = deriveProviderInstanceEntries([ - provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 70), + provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 95), provider("claudeAutoB", "Auto B", "claudeAgent", claudeModels, 10), ]); const medium = describeAutoRoute({ entries, now }); diff --git a/docs/progress.md b/docs/progress.md index 821d5452b229..22b8a6855e87 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -38,3 +38,10 @@ - Why: Tomáš wants to trace a problem back to the step and request that caused it. One big commit per task, or a squash merge, hides that. - Numbers: docs only, 4 commits in PR #4. The fork runs no CI checks on PRs. - Next: watch whether agents keep the cadence. If they do not, add the rule to the built-in orchestration instructions (`orchestrationInstructions.ts`, needs evals). + +## 2026-11-13: Auto staggers Claude A/B 5-hour windows + +- What: Auto now keeps sending work to the account whose 5-hour window is already running, until any of its windows reaches 90%, then moves to the other account. Within 10 points of 5-hour use, the sooner weekly reset wins. Past 90% everywhere, the account with the most left wins. +- Why: preferring the emptier account started both 5-hour windows at the same time, so both ran out together. Staggered windows let one refresh while the other is in use. +- Numbers: 11 routing tests (3 new), a mutation check (dropping the 90% rule fails 3 tests). +- Next: watch real routing on the hub for a day of use. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index eda559c93c55..ecd8389c4ba3 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -98,12 +98,8 @@ describe("resolveAutoModelSelection", () => { }); }); - it("picks the Claude account with more room, preferring Auto-aware instances", () => { - const providers = [ - claude("claudeAgent", 0, false), - claude("claudeAuto", 70), - claude("claudeAutoB", 20), - ]; + it("prefers Auto-aware instances", () => { + const providers = [claude("claudeAgent", 0, false), claude("claudeAutoB", 20)]; expect( resolveAutoModelSelection({ selection: auto("medium"), providers, now })?.selection .instanceId, @@ -137,22 +133,46 @@ describe("resolveAutoModelSelection", () => { }); }); - it("routes to the account with less of its 5-hour window used", () => { - // A has the busier week but a nearly unused 5-hour window, so it can take work right now. + it("drains the account whose 5-hour window is already running, so the windows stagger", () => { + // A's window is half spent; B stays untouched and its window starts only when A is nearly + // out, so A refreshes while B is in use. const providers = [ - withWeekly(claude("claudeAutoB", 50), 20, "2026-11-18T12:00:00.000Z"), - withWeekly(claude("claudeAuto", 10), 60, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAutoB", 0), 20, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 50), 20, "2026-11-18T12:00:00.000Z"), ]; expect( resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, ).toBe("claudeAuto"); }); + it("switches to the other account once a 5-hour or weekly window is 90% used", () => { + const sessionFull = [claude("claudeAuto", 92), claude("claudeAutoB", 0)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: sessionFull, now })?.selection + .instanceId, + ).toBe("claudeAutoB"); + const weeklyFull = [ + withWeekly(claude("claudeAuto", 50), 95, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAutoB", 0), 20, "2026-11-18T12:00:00.000Z"), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: weeklyFull, now })?.selection + .instanceId, + ).toBe("claudeAutoB"); + }); + + it("when every account is past 90%, uses the one with the most left", () => { + const providers = [claude("claudeAuto", 92), claude("claudeAutoB", 97)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, + ).toBe("claudeAuto"); + }); + it("with similar 5-hour use, spends the account whose weekly limit resets first", () => { - // B has slightly less 5-hour use, but A's unused weekly quota is gone tomorrow. + // B's window is slightly further along, but A's unused weekly quota is gone tomorrow. const providers = [ - withWeekly(claude("claudeAutoB", 25), 40, "2026-11-18T12:00:00.000Z"), - withWeekly(claude("claudeAuto", 30), 40, "2026-11-13T12:00:00.000Z"), + withWeekly(claude("claudeAutoB", 30), 40, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 25), 40, "2026-11-13T12:00:00.000Z"), ]; expect( resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, @@ -187,6 +207,50 @@ describe("resolveAutoModelSelection", () => { }); }); + it("after every Claude subscription, uses ChatGPT, then Grok, then Gemini", () => { + const other = (id: string, driver: string, slug: string, optionId: string) => + ({ + ...claude(id, 0, false), + driver: ProviderDriverKind.make(driver), + models: [ + { + slug, + name: slug, + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: optionId, + label: "Effort", + type: "select" as const, + options: ["low", "medium", "high"].map((value) => ({ id: value, label: value })), + }, + ], + }, + }, + ], + usageLimits: undefined, + }) as unknown as ServerProvider; + const claudeOut = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; + const codex = other("codex", "codex", "gpt-6-luna", "reasoningEffort"); + const grok = other("grok", "grok", "grok-4.7", "reasoningEffort"); + const gemini = other("antigravity", "antigravity", "gemini-3.8-flash", "thinking_level"); + const route = (providers: ServerProvider[]) => + resolveAutoModelSelection({ selection: auto("high"), providers, now })?.selection; + + expect(route([...claudeOut, gemini, grok, codex])).toEqual({ + instanceId: "codex", + model: "gpt-6-luna", + options: [{ id: "reasoningEffort", value: "high" }], + }); + expect(route([...claudeOut, gemini, grok])?.instanceId).toBe("grok"); + expect(route([...claudeOut, gemini])).toEqual({ + instanceId: "antigravity", + model: "gemini-3.8-flash", + options: [{ id: "thinking_level", value: "high" }], + }); + }); + it("reads the level from auto-low / auto-medium / auto-high", () => { const providers = [claude("claudeAuto", 10)]; const pick = (model: string) => diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index d76eda593edb..db3e53c713da 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -17,7 +17,8 @@ const AUTO_MODEL_SLUG = "auto"; const AUTO_LEVELS = ["low", "medium", "high"] as const; type AutoLevel = (typeof AUTO_LEVELS)[number]; const DEFAULT_LEVEL: AutoLevel = "medium"; -/** Above this peak usage, a sticky model gives way when another candidate has more room. */ +/** At this peak usage an account counts as nearly out: a sticky model gives way and routing + * moves to an account with room. */ const STICKY_MAX_USED_PERCENT = 90; interface AutoCandidate { @@ -51,8 +52,9 @@ const opencode = (model: string, effort: string): AutoCandidate => ({ }); /** - * Orchestrator candidates per level, best first. Each level starts on its Claude model and - * steps down through the other subscriptions as limits run out. + * Orchestrator candidates per level, best first: Claude A/B, Claude on Antigravity A/B, ChatGPT + * (Codex), Grok, Gemini, then free OpenCode models. Models a provider does not list are skipped, + * so paid-plan models (Sol, Astra) wait until the plan has them. */ const AUTO_CANDIDATES: Readonly>> = { high: [ @@ -61,8 +63,9 @@ const AUTO_CANDIDATES: Readonly>> antigravity("claude-opus-4-6-thinking", "high"), codex("gpt-6.1-sol", "high"), codex("gpt-6-astra", "high"), - grok("high"), codex("gpt-6-luna", "high"), + grok("high"), + antigravity("gemini-3.8-flash", "high"), ], medium: [ claude("claude-opus-5-5", "medium"), @@ -71,15 +74,21 @@ const AUTO_CANDIDATES: Readonly>> codex("gpt-6.1-sol", "medium"), codex("gpt-6-astra", "medium"), claude("claude-sonnet-5-5", "medium"), - grok("medium"), + antigravity("claude-sonnet-4-6", "medium"), codex("gpt-6-luna", "medium"), + grok("medium"), + antigravity("gemini-3.8-flash", "medium"), + opencode("opencode/big-pickle", "medium"), ], low: [ claude("claude-sonnet-5-5", "low"), claude("claude-haiku-5-5", "low"), antigravity("claude-sonnet-4-6", "low"), + antigravity("gemini-3.8-flash", "low"), opencode("opencode/big-pickle", "medium"), + opencode("opencode/beam-free", "medium"), opencode("opencode/deepseek-v4.1-flash-free", "medium"), + opencode("opencode/glm-5.3-flash-free", "medium"), codex("gpt-6-luna", "low"), grok("low"), ], @@ -127,7 +136,7 @@ export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { ], }; -/** Accounts whose 5-hour use differs by less than this many points count as equally free. */ +/** Accounts whose 5-hour use differs by less than this many points count as equally far along. */ const SESSION_BAND_PERCENT = 10; function sessionUsedPercent(provider: ServerProvider): number { @@ -145,13 +154,17 @@ function weeklyResetAt(provider: ServerProvider): number { } /** - * Best instance first: Auto-aware (carries the Auto prompt), then the freer 5-hour window, - * then, between accounts with similar 5-hour use, the one whose weekly quota resets first. + * Best instance first: Auto-aware, then accounts under 90% everywhere. Among those, the further + * along 5-hour window, so windows stagger (one refreshes while the other runs); within 10 + * points, the sooner weekly reset. Past 90% everywhere, the most left. */ function compareInstances(a: ServerProvider, b: ServerProvider): number { const aware = Number(isAutoAware(b)) - Number(isAutoAware(a)); if (aware !== 0) return aware; - const session = sessionUsedPercent(a) - sessionUsedPercent(b); + const room = Number(hasRoom(b)) - Number(hasRoom(a)); + if (room !== 0) return room; + if (!hasRoom(a)) return peakUsedPercent(a) - peakUsedPercent(b); + const session = sessionUsedPercent(b) - sessionUsedPercent(a); if (Math.abs(session) >= SESSION_BAND_PERCENT) return session; const weekly = weeklyResetAt(a) - weeklyResetAt(b); if (Number.isFinite(weekly) && weekly !== 0) return weekly; @@ -159,6 +172,10 @@ function compareInstances(a: ServerProvider, b: ServerProvider): number { return session || peakUsedPercent(a) - peakUsedPercent(b); } +function hasRoom(provider: ServerProvider): boolean { + return peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT; +} + function peakUsedPercent(provider: ServerProvider): number { return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); } From cb1b3cc20199ee726c4c6bf5a87e517f10b8b6b8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 16:51:15 +0100 Subject: [PATCH 045/230] feat(server): list Auto levels on every Claude provider MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auto Low, Medium and High existed only as custom models in the hub's settings, so a fork server on another machine (Tomáš's PC) showed no Auto at all. Every Claude provider now lists them as built-in models; a custom model with the same slug still works because built-ins win. Origin: Tomáš asked that Auto work in threads that run only on his own device. --- .../src/provider/ClaudeProvider.test.ts | 22 +++++++++++++++++++ apps/server/src/provider/ClaudeProvider.ts | 10 ++++++++- .../src/provider/ProviderRegistry.test.ts | 5 ++++- packages/shared/src/autoModel.ts | 7 ++++++ 4 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 apps/server/src/provider/ClaudeProvider.test.ts diff --git a/apps/server/src/provider/ClaudeProvider.test.ts b/apps/server/src/provider/ClaudeProvider.test.ts new file mode 100644 index 000000000000..0acb897d044b --- /dev/null +++ b/apps/server/src/provider/ClaudeProvider.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "@effect/vitest"; +import { ClaudeSettings } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { makePendingClaudeProvider } from "./ClaudeProvider.ts"; + +const defaultSettings = Schema.decodeSync(ClaudeSettings)({}); + +describe("makePendingClaudeProvider", () => { + it.effect("lists Auto Low, Medium and High after the real models, with no settings", () => + Effect.gen(function* () { + const provider = yield* makePendingClaudeProvider(defaultSettings); + expect(provider.models[0]?.slug).toMatch(/^claude-/); + expect(provider.models.slice(-3).map((model) => [model.slug, model.name])).toEqual([ + ["auto-low", "Auto Low"], + ["auto-medium", "Auto Medium"], + ["auto-high", "Auto High"], + ]); + }), + ); +}); diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.ts index b657a2b813fe..082a34c4ad02 100644 --- a/apps/server/src/provider/ClaudeProvider.ts +++ b/apps/server/src/provider/ClaudeProvider.ts @@ -20,6 +20,7 @@ import * as Ref from "effect/Ref"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { AUTO_LEVEL_MODELS } from "@t3tools/shared/autoModel"; import { createModelCapabilities } from "@t3tools/shared/model"; import { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -83,12 +84,19 @@ const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabili optionDescriptors: [], }); +const AUTO_MODELS: ReadonlyArray = AUTO_LEVEL_MODELS.map((model) => ({ + ...model, + isCustom: false, + capabilities: DEFAULT_CLAUDE_MODEL_CAPABILITIES, +})); + function claudeProviderModels( builtInModels: ReadonlyArray, customModels: ClaudeSettings["customModels"], ): ReadonlyArray { return providerModelsFromSettings( - builtInModels, + // After the real models: callers that default to a provider's first model keep a real one. + [...builtInModels, ...AUTO_MODELS], customModels, DEFAULT_CLAUDE_MODEL_CAPABILITIES, ).map((model) => diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 021c3ddb5703..b419a6a775ee 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -45,6 +45,7 @@ import { ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { WindowsShellEnvironment } from "@t3tools/shared/shell"; import { deepMerge } from "@t3tools/shared/Struct"; +import { isAutoModelSlug } from "@t3tools/shared/autoModel"; import { createModelCapabilities } from "@t3tools/shared/model"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; @@ -4307,7 +4308,9 @@ it.layer( }), ); const catalogSlugs = new Set(BUNDLED_CLAUDE_MODEL_CATALOG.models.map((m) => m.model.slug)); - const added = status.models.filter((model) => !catalogSlugs.has(model.slug)); + const added = status.models.filter( + (model) => !catalogSlugs.has(model.slug) && !isAutoModelSlug(model.slug), + ); assert.deepStrictEqual( added.map((model) => [model.slug, model.name, model.isCustom]), diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index db3e53c713da..312468f38d01 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -113,6 +113,13 @@ export function isAutoModelSlug(slug: string | null | undefined): boolean { ); } +/** One picker row per level; every Claude provider lists them, so Auto needs no settings. */ +export const AUTO_LEVEL_MODELS: ReadonlyArray<{ readonly slug: string; readonly name: string }> = + AUTO_LEVELS.map((level) => ({ + slug: `${AUTO_MODEL_SLUG}-${level}`, + name: `Auto ${level[0]!.toUpperCase()}${level.slice(1)}`, + })); + export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { return isAutoModelSlug(selection?.model); } From f4b216d5cc5c0265d6ecb2d93ebad9784395e19c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 16:51:16 +0100 Subject: [PATCH 046/230] feat(web): pin Auto levels at the top of Favorites MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Favorites live in each server's settings, so a machine without the hub's settings had no Auto pinned. The picker now puts Auto High, Medium and Low from the first Claude instance that lists them at the top of Favorites, until the user stars an Auto level themselves. Origin: Tomáš asked for the Auto levels to be the main pinned models in every thread. --- .../components/chat/ModelPickerContent.tsx | 7 ++- .../chat/ProviderModelPicker.logic.test.ts | 59 ++++++++++++++++++- .../chat/ProviderModelPicker.logic.ts | 37 +++++++++++- docs/progress.md | 7 +++ 4 files changed, 105 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index ee8aae2da6d3..474b23777c7e 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -41,6 +41,7 @@ import { ComboboxItem, ComboboxListVirtualized, } from "../ui/combobox"; +import { autoLevelsFirst, withPinnedAutoLevels } from "./ProviderModelPicker.logic"; import { ModelEsque } from "./providerIconUtils"; import { isAutoModelSlug } from "@t3tools/shared/autoModel"; import type { AutoRoute } from "./autoRoute"; @@ -379,7 +380,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes this picker's mount to global keydown handlers useLayoutEffect(() => registerModelPickerContent(), []); const highlightedModelKeyRef = useRef(null); - const { favorites } = useEnvironmentModelPreferences(props.environmentId); + const { favorites: savedFavorites } = useEnvironmentModelPreferences(props.environmentId); + const favorites = withPinnedAutoLevels(savedFavorites, instanceEntries, modelOptionsByInstance); const activeEntry = props.instanceEntries.find( (entry) => entry.instanceId === props.activeInstanceId, ); @@ -689,11 +691,12 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { result = result.filter((m) => m.instanceId === selectedInstanceId); } - return sortProviderModelItems(result, { + const sorted = sortProviderModelItems(result, { favoriteModelKeys: favoritesSet, groupFavorites: selectedInstanceId !== "favorites", instanceOrder: selectedInstanceId === "favorites" ? instanceOrder : [], }); + return selectedInstanceId === "favorites" ? autoLevelsFirst(sorted) : sorted; })(); const legacySection = (() => { diff --git a/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts b/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts index 7602a362d30c..988c683990f0 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts +++ b/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts @@ -1,7 +1,11 @@ -import { ProviderDriverKind } from "@t3tools/contracts"; +import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { retainedModelWhileProviderLocked } from "./ProviderModelPicker.logic"; +import { + autoLevelsFirst, + retainedModelWhileProviderLocked, + withPinnedAutoLevels, +} from "./ProviderModelPicker.logic"; const claude = ProviderDriverKind.make("claudeAgent"); const opus = { slug: "claude-opus-5-5", name: "Claude Opus 5.5", shortName: "Opus 5.5" }; @@ -18,3 +22,54 @@ describe("retainedModelWhileProviderLocked", () => { expect(retainedModelWhileProviderLocked(null, opus.slug)).toBeUndefined(); }); }); + +describe("withPinnedAutoLevels", () => { + const id = (value: string) => ProviderInstanceId.make(value); + const autoRows = ["auto-low", "auto-medium", "auto-high"].map((slug) => ({ slug })); + const entries = [ + { instanceId: id("codex"), driverKind: ProviderDriverKind.make("codex") }, + { instanceId: id("claudeAgent"), driverKind: claude }, + { instanceId: id("claudeAgent_2"), driverKind: claude }, + ]; + const options = new Map([ + [id("codex"), [{ slug: "gpt-6-luna" }]], + [id("claudeAgent"), [...autoRows, opus]], + [id("claudeAgent_2"), [...autoRows, opus]], + ]); + const saved = [{ provider: id("codex"), model: "gpt-6-luna" }]; + + it("pins the first Claude instance's Auto levels above saved favorites", () => { + expect(withPinnedAutoLevels(saved, entries, options)).toEqual([ + { provider: "claudeAgent", model: "auto-high" }, + { provider: "claudeAgent", model: "auto-medium" }, + { provider: "claudeAgent", model: "auto-low" }, + ...saved, + ]); + }); + + it("keeps the user's own choice once any Auto level is starred", () => { + const own = [{ provider: id("claudeAgent_2"), model: "auto-low" }, ...saved]; + expect(withPinnedAutoLevels(own, entries, options)).toBe(own); + }); + + it("changes nothing when no Claude instance lists the Auto levels", () => { + expect(withPinnedAutoLevels(saved, entries.slice(0, 1), options)).toBe(saved); + }); +}); + +describe("autoLevelsFirst", () => { + it("puts Auto High, Medium and Low ahead of other favorites, keeping the rest in order", () => { + const items = ["gpt-6-luna", "auto-low", "grok-4.7", "auto-high", "auto-medium"].map( + (slug) => ({ + slug, + }), + ); + expect(autoLevelsFirst(items).map((item) => item.slug)).toEqual([ + "auto-high", + "auto-medium", + "auto-low", + "gpt-6-luna", + "grok-4.7", + ]); + }); +}); diff --git a/apps/web/src/components/chat/ProviderModelPicker.logic.ts b/apps/web/src/components/chat/ProviderModelPicker.logic.ts index dd3d6871e7c2..f33cbae9e006 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.logic.ts +++ b/apps/web/src/components/chat/ProviderModelPicker.logic.ts @@ -1,7 +1,10 @@ -import type { ProviderDriverKind } from "@t3tools/contracts"; +import type { ModelFavorite, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; +import { AUTO_LEVEL_MODELS, isAutoModelSlug } from "@t3tools/shared/autoModel"; import type { ModelEsque } from "./providerIconUtils"; +type Favorite = typeof ModelFavorite.Type; + /** Keeps a hidden model visible while its provider is locked or turned off. */ export function retainedModelWhileProviderLocked( entry: { @@ -16,3 +19,35 @@ export function retainedModelWhileProviderLocked( if (entry.driverKind === "opencode" || entry.driverKind === "antigravity") return undefined; return entry.models.find((candidate) => candidate.slug === model) ?? { slug: model, name: model }; } + +/** + * Auto High, Medium and Low lead Favorites on every machine, from the first Claude instance that + * lists them, until the user stars an Auto level themselves. + */ +export function withPinnedAutoLevels( + favorites: ReadonlyArray, + entries: ReadonlyArray<{ + readonly instanceId: ProviderInstanceId; + readonly driverKind: ProviderDriverKind; + }>, + optionsByInstance: ReadonlyMap>, +): ReadonlyArray { + if (favorites.some((favorite) => isAutoModelSlug(favorite.model))) return favorites; + const levels = AUTO_LEVEL_MODELS.map((model) => model.slug).reverse(); + const host = entries.find( + (entry) => + entry.driverKind === "claudeAgent" && + levels.every((slug) => + (optionsByInstance.get(entry.instanceId) ?? []).some((option) => option.slug === slug), + ), + ); + if (!host) return favorites; + return [...levels.map((model) => ({ provider: host.instanceId, model })), ...favorites]; +} + +/** Favorites view order: Auto High, Medium, Low first, then the rest as sorted. */ +export function autoLevelsFirst(items: ReadonlyArray): T[] { + const levels = AUTO_LEVEL_MODELS.map((model) => model.slug).reverse(); + const auto = levels.flatMap((slug) => items.filter((item) => item.slug === slug)); + return [...auto, ...items.filter((item) => !levels.includes(item.slug))]; +} diff --git a/docs/progress.md b/docs/progress.md index 22b8a6855e87..a7a0b2a2b48b 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -45,3 +45,10 @@ - Why: preferring the emptier account started both 5-hour windows at the same time, so both ran out together. Staggered windows let one refresh while the other is in use. - Numbers: 11 routing tests (3 new), a mutation check (dropping the 90% rule fails 3 tests). - Next: watch real routing on the hub for a day of use. + +## 2026-11-13: Auto levels on every machine + +- What: every Claude provider on a fork server lists Auto Low, Medium and High as built-in models, so Auto needs no settings. The model picker pins the three levels at the top of Favorites, from the first Claude instance that lists them, until the user stars an Auto level themselves. +- Why: Tomáš wants Auto in every thread, including threads that run on his PC's own T3 server, which has none of the hub's settings. +- Numbers: 1 new server test, 3 new picker tests; server and web typecheck clean (6 min and 62 s on the hub). +- Next: Tomáš builds the fork desktop app on his PC; Auto there routes only to the providers logged in on that PC. From 1d85cb2873052d5c4e020b5c31342bde24ada0c8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 14 Nov 2026 11:32:21 +0100 Subject: [PATCH 047/230] fix(shared): Auto routes to the instances that carry the Auto prompt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since every Claude provider lists the Auto levels (#6), "lists an Auto model" no longer marks the instances launched with the Auto-mode prompt (Auto, Auto B). The plain Claude instance shares their account and usage and comes first in the registry, so Auto routed turns to it and the orchestrator never got the routing instructions. Instances whose display name starts with "Auto" now win the tie. The unused `auto` custom-model descriptor goes with the old check. Origin: Tomáš reported that Auto model routing does not work. --- docs/progress.md | 7 +++++++ packages/shared/src/autoModel.test.ts | 21 ++++++++++----------- packages/shared/src/autoModel.ts | 20 +++++--------------- 3 files changed, 22 insertions(+), 26 deletions(-) diff --git a/docs/progress.md b/docs/progress.md index a7a0b2a2b48b..3aa0ddb5c309 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -52,3 +52,10 @@ - Why: Tomáš wants Auto in every thread, including threads that run on his PC's own T3 server, which has none of the hub's settings. - Numbers: 1 new server test, 3 new picker tests; server and web typecheck clean (6 min and 62 s on the hub). - Next: Tomáš builds the fork desktop app on his PC; Auto there routes only to the providers logged in on that PC. + +## 2026-11-14: Auto routes to the Auto instances again; fork synced with upstream for hub2 + +- What: Auto prefers instances named "Auto…" (the ones launched with `auto-mode.md`) when accounts tie. The fork merged upstream main (653 commits, no conflicts) and runs on hub2 from `~/projects/t3code-auto`. +- Why: since every Claude provider lists the Auto levels (#6), the old "lists an Auto model" check matched every Claude instance. Plain `claudeAgent` shares account A's usage with `claudeAuto` and comes first in the registry, so Auto sent turns to it and the orchestrator never got the routing prompt. hub2 ran upstream nightly (DB schema 89); the fork stopped at 85, so it could not run there. +- Numbers: autoModel 12/12 (the same-account case failed before the fix), ClaudeProvider + ProviderRegistry 80/80, web Auto tests 7/7; typecheck of contracts, shared, server and web clean (21 s server on hub2). Fork build 59 s on hub2. +- Next: link hub and deploy the same branch there; rebuild the desktop app on the PC. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index ecd8389c4ba3..d18bef35e2f7 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { AUTO_LEVEL_DESCRIPTOR, isAutoModelSlug, resolveAutoModelSelection } from "./autoModel.ts"; +import { AUTO_LEVEL_MODELS, isAutoModelSlug, resolveAutoModelSelection } from "./autoModel.ts"; const now = Date.parse("2026-11-12T12:00:00.000Z"); const resetsAt = "2026-11-12T15:00:00.000Z"; @@ -26,6 +26,7 @@ function claude(id: string, usedPercent: number, autoAware = true): ServerProvid return { instanceId: ProviderInstanceId.make(id), driver: ProviderDriverKind.make("claudeAgent"), + ...(autoAware ? { displayName: id.endsWith("B") ? "Auto B" : "Auto" } : {}), enabled: true, installed: true, version: null, @@ -39,16 +40,8 @@ function claude(id: string, usedPercent: number, autoAware = true): ServerProvid isCustom: false, capabilities: effortCapabilities, })), - ...(autoAware - ? [ - { - slug: "auto", - name: "Auto", - isCustom: true, - capabilities: { optionDescriptors: [AUTO_LEVEL_DESCRIPTOR] }, - }, - ] - : []), + // Every Claude provider lists the Auto levels; only "Auto" instances carry the Auto prompt. + ...AUTO_LEVEL_MODELS.map((model) => ({ ...model, isCustom: false, capabilities: {} })), ], slashCommands: [], skills: [], @@ -104,6 +97,12 @@ describe("resolveAutoModelSelection", () => { resolveAutoModelSelection({ selection: auto("medium"), providers, now })?.selection .instanceId, ).toBe("claudeAutoB"); + // Same account, so same usage: the plain instance comes first in the registry. + const sameAccount = [claude("claudeAgent", 20, false), claude("claudeAuto", 20)]; + expect( + resolveAutoModelSelection({ selection: auto("medium"), providers: sameAccount, now }) + ?.selection.instanceId, + ).toBe("claudeAuto"); }); it("keeps the thread's current model until it passes 90% used", () => { diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 312468f38d01..87278cc6c7c9 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -2,7 +2,6 @@ import { isProviderAvailable, type ModelSelection, type ProviderDriverKind, - type ProviderOptionDescriptor, type ServerProvider, } from "@t3tools/contracts"; @@ -131,18 +130,6 @@ function autoLevelOf(selection: ModelSelection): AutoLevel { return AUTO_LEVELS.find((level) => level === value) ?? DEFAULT_LEVEL; } -/** The `effort` descriptor an `auto` custom model declares, so pickers show Low/Medium/High. */ -export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { - id: "effort", - label: "Auto level", - type: "select", - options: [ - { id: "low", label: "Low", description: "Sonnet orchestrates; cheaper models do more" }, - { id: "medium", label: "Medium", description: "Opus orchestrates", isDefault: true }, - { id: "high", label: "High", description: "Fable orchestrates" }, - ], -}; - /** Accounts whose 5-hour use differs by less than this many points count as equally far along. */ const SESSION_BAND_PERCENT = 10; @@ -187,9 +174,12 @@ function peakUsedPercent(provider: ServerProvider): number { return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); } -/** Instances that list the `auto` model carry the Auto-mode prompt, so they win ties. */ +/** + * Instances named "Auto…" carry the Auto-mode prompt (their launch args), so they win ties. Every + * Claude provider lists the Auto levels, so listing them says nothing about the prompt. + */ function isAutoAware(provider: ServerProvider): boolean { - return provider.models.some((model) => isAutoModelSlug(model.slug)); + return /^auto\b/i.test(provider.displayName ?? ""); } function usable(provider: ServerProvider, model: string, now: number): boolean { From 1161763fac648509d19fdfc57df72ea2b2562d23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 14 Nov 2026 11:55:50 +0100 Subject: [PATCH 048/230] fix(client): an Auto thread no longer shows a pending context handoff MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After the first message on Auto, the thread runs on the model Auto chose (for example Auto B / Sonnet), while the composer still holds the Auto selection on the instance it was picked from. The pending-handoff check compared the two and showed "Context handoff pending" after every turn, although the server keeps the thread's model while it fits. The check now resolves an Auto selection the way the server does, so it only shows a handoff when Auto would really move the thread to another account. Web and mobile share the check; callers pass the current minute. Origin: found while checking Auto in the real hub2 web UI for Tomáš. --- .../src/state/use-thread-composer-state.ts | 3 +- apps/web/src/components/ChatView.tsx | 1 + docs/progress.md | 7 +++ packages/client-runtime/src/handoff.test.ts | 55 +++++++++++++++---- packages/client-runtime/src/handoff.ts | 14 +++++ .../client-runtime/src/state/contextWindow.ts | 3 +- 6 files changed, 70 insertions(+), 13 deletions(-) diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 97b463e9b6a4..d2b6156a1811 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -343,12 +343,14 @@ export function useThreadComposerState(input: { const selectedThread = selectedThreadShell; const modelSelection = selectedDraft.modelSelection ?? selectedThread?.modelSelection ?? null; const serverConfig = selectedEnvironmentRuntime?.serverConfig; + const nowMinuteMs = useNowMinuteMs(); const pendingHandoff = resolvePendingHandoff( selectedThreadProjection?.projection, isModelSelectionUnavailable(serverConfig, modelSelection, selectedThread?.projectId ?? null) ? null : modelSelection, serverConfig?.providers ?? [], + nowMinuteMs, ); const runtimeMode = selectedDraft.runtimeMode ?? selectedThread?.runtimeMode ?? null; // Plan mode is not offered to users; every send runs in build mode. @@ -469,7 +471,6 @@ export function useThreadComposerState(input: { now, }) : null; - const nowMinuteMs = useNowMinuteMs(); const compactTokens = selectedDraft.freshContext === true ? null diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index e69de418cd3e..22c35c6ed510 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2520,6 +2520,7 @@ export default function ChatView(props: ChatViewProps) { serverProjection, pendingHandoffSelectionUsable ? pendingHandoffSelection : null, providerStatuses, + Date.parse(`${nowMinute}:00Z`), ); const compactThreadUnavailable = !canOperateThread || diff --git a/docs/progress.md b/docs/progress.md index 3aa0ddb5c309..b084970a4e8a 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -59,3 +59,10 @@ - Why: since every Claude provider lists the Auto levels (#6), the old "lists an Auto model" check matched every Claude instance. Plain `claudeAgent` shares account A's usage with `claudeAuto` and comes first in the registry, so Auto sent turns to it and the orchestrator never got the routing prompt. hub2 ran upstream nightly (DB schema 89); the fork stopped at 85, so it could not run there. - Numbers: autoModel 12/12 (the same-account case failed before the fix), ClaudeProvider + ProviderRegistry 80/80, web Auto tests 7/7; typecheck of contracts, shared, server and web clean (21 s server on hub2). Fork build 59 s on hub2. - Next: link hub and deploy the same branch there; rebuild the desktop app on the PC. + +## 2026-11-14: Auto threads stop showing a false "Context handoff pending" + +- What: the shared pending-handoff check (web and mobile) resolves an Auto selection the way the server does, keeping the thread's current model while it fits, before deciding a handoff is coming. +- Why: in the real hub2 UI, every Auto thread showed "Context handoff pending: Sonnet 5.5 (AB) → Auto Low (CL)" after each turn, while the server log showed the next message stay on `claudeAutoB` (sticky). +- Numbers: handoff + contextWindow tests 39/39 (the new case failed before); client-runtime, web and mobile typecheck clean. Deployed on hub2 as a web-only build (51 s), no restart. +- Next: link hub and run the same checks there; rebuild the PC desktop app. diff --git a/packages/client-runtime/src/handoff.test.ts b/packages/client-runtime/src/handoff.test.ts index d2f5fb4e7890..071aa10fccd1 100644 --- a/packages/client-runtime/src/handoff.test.ts +++ b/packages/client-runtime/src/handoff.test.ts @@ -87,6 +87,8 @@ const projection = { visibleTurnItems: [{ item: { type: "user_message" } }], } as unknown as OrchestrationV2ThreadProjection; +const now = Date.parse("2026-11-14T12:00:00.000Z"); + describe("pending context handoff", () => { it("removes the preview while the handoff starts", () => { const selection = { instanceId: to, model: "destination" }; @@ -105,10 +107,10 @@ describe("pending context handoff", () => { ], }; - expect(resolvePendingHandoff(projection, selection, providers)).not.toBeNull(); - expect(resolvePendingHandoff(starting, selection, providers)).toBeNull(); + expect(resolvePendingHandoff(projection, selection, providers, now)).not.toBeNull(); + expect(resolvePendingHandoff(starting, selection, providers, now)).toBeNull(); expect( - resolvePendingHandoff(starting, { instanceId: from, model: "source" }, providers), + resolvePendingHandoff(starting, { instanceId: from, model: "source" }, providers, now), ).toEqual({ from: [selection], to: { instanceId: from, model: "source" }, @@ -133,7 +135,7 @@ describe("pending context handoff", () => { ], }; - expect(resolvePendingHandoff(unstarted, selection, [])).toEqual({ + expect(resolvePendingHandoff(unstarted, selection, [], now)).toEqual({ from: [{ instanceId: from, model: "source" }], to: selection, }); @@ -141,28 +143,59 @@ describe("pending context handoff", () => { ); it("appears on selection, updates the destination, and disappears on returning", () => { - expect(resolvePendingHandoff(projection, { instanceId: to, model: "first" }, [])).toEqual({ + expect(resolvePendingHandoff(projection, { instanceId: to, model: "first" }, [], now)).toEqual({ from: [{ instanceId: from, model: "source" }], to: { instanceId: to, model: "first" }, }); expect( - resolvePendingHandoff(projection, { instanceId: to, model: "second" }, [])?.to.model, + resolvePendingHandoff(projection, { instanceId: to, model: "second" }, [], now)?.to.model, ).toBe("second"); - expect(resolvePendingHandoff(projection, { instanceId: from, model: "source" }, [])).toBeNull(); - expect(resolvePendingHandoff(projection, { instanceId: from, model: "other" }, [])).toBeNull(); + expect( + resolvePendingHandoff(projection, { instanceId: from, model: "source" }, [], now), + ).toBeNull(); + expect( + resolvePendingHandoff(projection, { instanceId: from, model: "other" }, [], now), + ).toBeNull(); }); it("stays hidden while the thread's timeline is empty", () => { const empty = { ...projection, visibleTurnItems: [] }; - expect(resolvePendingHandoff(empty, { instanceId: to, model: "first" }, [])).toBeNull(); + expect(resolvePendingHandoff(empty, { instanceId: to, model: "first" }, [], now)).toBeNull(); // Paging can leave a window of only tool rows after the prompt. const toolRowsOnly = { ...projection, visibleTurnItems: [{ item: { type: "command_execution" } }], } as unknown as OrchestrationV2ThreadProjection; expect( - resolvePendingHandoff(toolRowsOnly, { instanceId: to, model: "first" }, [])?.to.model, + resolvePendingHandoff(toolRowsOnly, { instanceId: to, model: "first" }, [], now)?.to.model, ).toBe("first"); }); + it("previews an Auto selection as the model Auto keeps, not as a handoff", () => { + const autoB = ProviderInstanceId.make("claudeAutoB"); + const onAutoB = { + ...projection, + runs: [{ ...projection.runs[0]!, ...run("source", 1, autoB, "claude-sonnet-5-5") }], + } as unknown as OrchestrationV2ThreadProjection; + const claude = (instanceId: ProviderInstanceId, usedPercent: number) => + ({ + instanceId, + driver: "claudeAgent", + enabled: true, + installed: true, + status: "ready", + auth: { status: "authenticated" }, + models: [{ slug: "claude-sonnet-5-5", capabilities: { optionDescriptors: [] } }], + usageLimits: { windows: [{ kind: "session", usedPercent }] }, + }) as unknown as ServerProvider; + const autoLow = { instanceId: to, model: "auto-low" }; + + expect( + resolvePendingHandoff(onAutoB, autoLow, [claude(to, 0), claude(autoB, 20)], now), + ).toBeNull(); + // Past 90% Auto moves the thread to the other account, so the handoff is real. + expect( + resolvePendingHandoff(onAutoB, autoLow, [claude(to, 0), claude(autoB, 95)], now)?.to, + ).toMatchObject({ instanceId: to, model: "claude-sonnet-5-5" }); + }); it("resumes compatible account overlays without showing a handoff", () => { const providers = [from, to].map((instanceId) => ({ instanceId, @@ -170,7 +203,7 @@ describe("pending context handoff", () => { continuation: { groupKey: "shared" }, })) as unknown as ServerProvider[]; expect( - resolvePendingHandoff(projection, { instanceId: to, model: "target" }, providers), + resolvePendingHandoff(projection, { instanceId: to, model: "target" }, providers, now), ).toBeNull(); }); }); diff --git a/packages/client-runtime/src/handoff.ts b/packages/client-runtime/src/handoff.ts index 48a122742931..d8057f946ece 100644 --- a/packages/client-runtime/src/handoff.ts +++ b/packages/client-runtime/src/handoff.ts @@ -11,6 +11,7 @@ import { getModelSelectionStringOptionValue, getProviderOptionCurrentValue, } from "@t3tools/shared/model"; +import { isAutoModelSelection, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; import { isReasoningSelect } from "./modelTraits.ts"; import type { ThreadStructure } from "./state/models.ts"; @@ -27,6 +28,7 @@ export function resolvePendingHandoff( projection: Pick | null | undefined, selection: ModelSelection | null | undefined, providers: ReadonlyArray, + now: number, ): HandoffEndpoints | null { // A thread with an empty timeline has nothing to hand off. Any loaded row // counts: paging can leave a window of only tool rows. @@ -39,6 +41,18 @@ export function resolvePendingHandoff( (run.startedAt !== null || (run.status === "starting" && run.contextHandoffId !== null)), )?.modelSelection; if (from === undefined || selection == null) return null; + // The server swaps Auto for a concrete model per message, keeping the current one while it fits. + if (isAutoModelSelection(selection)) { + const route = resolveAutoModelSelection({ + selection, + providers, + now, + current: from, + }); + return route === null + ? null + : resolvePendingHandoff(projection, route.selection, providers, now); + } const source = providers.find((provider) => provider.instanceId === from.instanceId); const target = providers.find((provider) => provider.instanceId === selection.instanceId); const needsHandoff = diff --git a/packages/client-runtime/src/state/contextWindow.ts b/packages/client-runtime/src/state/contextWindow.ts index a8f7e0f88c35..3a877ea87ba4 100644 --- a/packages/client-runtime/src/state/contextWindow.ts +++ b/packages/client-runtime/src/state/contextWindow.ts @@ -281,7 +281,8 @@ export function compactBeforeSendTokens(input: { COMPACT_COMMAND_PATTERN.test(input.text) || resolveIdleCompaction(input.settings, provider.instanceId) === "off" || !provider.slashCommands.some((command) => command.name === "compact") || - resolvePendingHandoff(projection, input.selection, input.providers) !== null || + resolvePendingHandoff(projection, input.selection, input.providers, Date.parse(input.now)) !== + null || projection.runtimeRequests.some((request) => request.status === "pending") || projection.runs.some((run) => run.status === "queued" && run.queueHeld === true) || (!input.visibleTurnItems.some( From 8aa5ddcd86dfe067b50a8d64475b0b810dd1700b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 14 Nov 2026 12:05:51 +0100 Subject: [PATCH 049/230] feat: threads routed by Auto stay on Auto MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The server replaces Auto with a concrete model per message and stored only that, so after the first message every client showed "Sonnet 5.5 Low" instead of "Auto Low", and a client without the fork's composer kept sending the concrete model, which ended Auto routing for the thread. The model Auto picks now carries an `auto` option with its level. The server treats such a selection as Auto again on the next command (sticky while it fits), and web and mobile show it in the composer as the Auto level it came from. The pending-handoff preview only re-resolves Auto level slugs, so a routed selection does not recurse. Origin: Tomáš saw "Sonnet 5.5 Low" instead of Auto in a thread started on Auto Low. --- .../src/state/use-thread-composer-state.ts | 4 +- apps/web/src/components/ChatView.tsx | 5 +- docs/progress.md | 8 +++ packages/client-runtime/src/handoff.ts | 4 +- packages/shared/src/autoModel.test.ts | 59 +++++++++++++++---- packages/shared/src/autoModel.ts | 38 +++++++++--- 6 files changed, 97 insertions(+), 21 deletions(-) diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index d2b6156a1811..bc862e8c5a61 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -10,6 +10,7 @@ import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell"; import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; import { threadSteersDuringCompaction } from "@t3tools/client-runtime/state/thread-workflows"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; +import { autoLevelSelection } from "@t3tools/shared/autoModel"; import { announcedRun, isDetailBehindShell, @@ -341,7 +342,8 @@ export function useThreadComposerState(input: { const selectedDraft = useComposerDraftSettings(selectedThreadKey); const selectedThreadQueueCount = selectedThreadQueuedMessages.length; const selectedThread = selectedThreadShell; - const modelSelection = selectedDraft.modelSelection ?? selectedThread?.modelSelection ?? null; + const modelSelection = + selectedDraft.modelSelection ?? autoLevelSelection(selectedThread?.modelSelection) ?? null; const serverConfig = selectedEnvironmentRuntime?.serverConfig; const nowMinuteMs = useNowMinuteMs(); const pendingHandoff = resolvePendingHandoff( diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 22c35c6ed510..9daf216167df 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -5,6 +5,7 @@ import { ChildThreadApprovals } from "./chat/ChildThreadApprovals"; import { workspaceAreaProps } from "../lib/workspaceFocus"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; +import { autoLevelSelection } from "@t3tools/shared/autoModel"; import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-edit"; import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOverlays"; import { usePasteToFocusComposer } from "./chat/usePasteToFocusComposer"; @@ -3760,7 +3761,9 @@ export default function ChatView(props: ChatViewProps) { activeProjectDefaultModelSelection={ activeProjectDefaultModelSelection } - activeThreadModelSelection={activeThread?.modelSelection} + activeThreadModelSelection={autoLevelSelection( + activeThread?.modelSelection, + )} activeProjectId={activeProject?.id ?? null} projectName={activeProject?.title} compactThreadUnavailable={compactThreadUnavailable} diff --git a/docs/progress.md b/docs/progress.md index b084970a4e8a..1db4eaeb2169 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -66,3 +66,11 @@ - Why: in the real hub2 UI, every Auto thread showed "Context handoff pending: Sonnet 5.5 (AB) → Auto Low (CL)" after each turn, while the server log showed the next message stay on `claudeAutoB` (sticky). - Numbers: handoff + contextWindow tests 39/39 (the new case failed before); client-runtime, web and mobile typecheck clean. Deployed on hub2 as a web-only build (51 s), no restart. - Next: link hub and run the same checks there; rebuild the PC desktop app. + +## 2026-11-14: Threads routed by Auto stay on Auto + +- What: the model Auto picks carries an `auto` option with its level. The server treats it as Auto on the next command (sticky while under 90%), and web and mobile show the thread's composer as "Auto Low · now Sonnet 5.5 (B)" instead of "Sonnet 5.5 Low". +- Why: Tomáš saw "Sonnet 5.5 Low" in a thread started on Auto Low. The server stored only the concrete model, so Auto showed only where a local draft remembered it, and clients without the fork's composer sent the concrete model, ending Auto for that thread. +- Numbers: autoModel 12/12, handoff + contextWindow 39/39 (a recursion the stamp caused was caught by the handoff test); shared, client-runtime, web, mobile and server typecheck clean. Checked in a clean incognito browser on a scratch copy of hub2's data: a thread started on Auto Low over the CLI shows Auto Low in the composer. +- Deploy: service now runs from `~/.t3/fork-current` (a symlink to the deploy checkout), so a new build goes into a fresh checkout and the restart flips the link. +- Next: hub (link it first) and a fork build of the PC desktop app; the stock app still shows the concrete model. diff --git a/packages/client-runtime/src/handoff.ts b/packages/client-runtime/src/handoff.ts index d8057f946ece..1ca0c09ed50e 100644 --- a/packages/client-runtime/src/handoff.ts +++ b/packages/client-runtime/src/handoff.ts @@ -11,7 +11,7 @@ import { getModelSelectionStringOptionValue, getProviderOptionCurrentValue, } from "@t3tools/shared/model"; -import { isAutoModelSelection, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; +import { isAutoModelSlug, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; import { isReasoningSelect } from "./modelTraits.ts"; import type { ThreadStructure } from "./state/models.ts"; @@ -42,7 +42,7 @@ export function resolvePendingHandoff( )?.modelSelection; if (from === undefined || selection == null) return null; // The server swaps Auto for a concrete model per message, keeping the current one while it fits. - if (isAutoModelSelection(selection)) { + if (isAutoModelSlug(selection.model)) { const route = resolveAutoModelSelection({ selection, providers, diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index d18bef35e2f7..e3b6e708f89d 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -6,7 +6,13 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { AUTO_LEVEL_MODELS, isAutoModelSlug, resolveAutoModelSelection } from "./autoModel.ts"; +import { + AUTO_LEVEL_MODELS, + autoLevelSelection, + isAutoModelSelection, + isAutoModelSlug, + resolveAutoModelSelection, +} from "./autoModel.ts"; const now = Date.parse("2026-11-12T12:00:00.000Z"); const resetsAt = "2026-11-12T15:00:00.000Z"; @@ -77,7 +83,10 @@ describe("resolveAutoModelSelection", () => { ).toEqual({ instanceId: "claudeAuto", model: "claude-fable-5-2", - options: [{ id: "effort", value: "high" }], + options: [ + { id: "effort", value: "high" }, + { id: "auto", value: "high" }, + ], }); expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.model).toBe( "claude-opus-5-5", @@ -87,7 +96,10 @@ describe("resolveAutoModelSelection", () => { ).toEqual({ instanceId: "claudeAuto", model: "claude-sonnet-5-5", - options: [{ id: "effort", value: "low" }], + options: [ + { id: "effort", value: "low" }, + { id: "auto", value: "low" }, + ], }); }); @@ -126,7 +138,9 @@ describe("resolveAutoModelSelection", () => { usageLimits: undefined, } as unknown as ServerProvider; const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100), grok]; - expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection).toEqual({ + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection, + ).toMatchObject({ instanceId: "grok", model: "grok-4.7", }); @@ -199,10 +213,15 @@ describe("resolveAutoModelSelection", () => { })), } as unknown as ServerProvider; const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100), antigravity]; - expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection).toEqual({ + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection, + ).toMatchObject({ instanceId: "antigravity", model: "claude-opus-4-6-thinking", - options: [{ id: "thinking_level", value: "medium" }], + options: [ + { id: "thinking_level", value: "medium" }, + { id: "auto", value: "medium" }, + ], }); }); @@ -237,16 +256,22 @@ describe("resolveAutoModelSelection", () => { const route = (providers: ServerProvider[]) => resolveAutoModelSelection({ selection: auto("high"), providers, now })?.selection; - expect(route([...claudeOut, gemini, grok, codex])).toEqual({ + expect(route([...claudeOut, gemini, grok, codex])).toMatchObject({ instanceId: "codex", model: "gpt-6-luna", - options: [{ id: "reasoningEffort", value: "high" }], + options: [ + { id: "reasoningEffort", value: "high" }, + { id: "auto", value: "high" }, + ], }); expect(route([...claudeOut, gemini, grok])?.instanceId).toBe("grok"); - expect(route([...claudeOut, gemini])).toEqual({ + expect(route([...claudeOut, gemini])).toMatchObject({ instanceId: "antigravity", model: "gemini-3.8-flash", - options: [{ id: "thinking_level", value: "high" }], + options: [ + { id: "thinking_level", value: "high" }, + { id: "auto", value: "high" }, + ], }); }); @@ -263,6 +288,20 @@ describe("resolveAutoModelSelection", () => { expect(pick("auto-low")).toBe("claude-sonnet-5-5"); expect(isAutoModelSlug("auto-low")).toBe(true); expect(isAutoModelSlug("auto-max")).toBe(false); + + // The routed model keeps its level, so the thread stays on Auto and clients show it. + const routed = resolveAutoModelSelection({ + selection: auto("low"), + providers, + now, + })!.selection; + expect(isAutoModelSelection(routed)).toBe(true); + expect(autoLevelSelection(routed)).toEqual({ instanceId: "claudeAuto", model: "auto-low" }); + expect( + resolveAutoModelSelection({ selection: routed, providers, now, current: routed }), + ).toMatchObject({ sticky: true, level: "low", selection: routed }); + const plain = { instanceId: ProviderInstanceId.make("claudeAuto"), model: "claude-opus-5-5" }; + expect(autoLevelSelection(plain)).toBe(plain); }); it("returns null when nothing is usable", () => { diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 87278cc6c7c9..74519c6e38e5 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -13,6 +13,8 @@ import { exhaustedUsageWindow } from "./usageLimits.ts"; * live usage limits. The level (`low` | `medium` | `high`) rides in the `effort` option. */ const AUTO_MODEL_SLUG = "auto"; +/** Stamped on the model Auto picks, holding the level, so the thread stays on Auto. */ +const AUTO_OPTION_ID = "auto"; const AUTO_LEVELS = ["low", "medium", "high"] as const; type AutoLevel = (typeof AUTO_LEVELS)[number]; const DEFAULT_LEVEL: AutoLevel = "medium"; @@ -119,11 +121,28 @@ export const AUTO_LEVEL_MODELS: ReadonlyArray<{ readonly slug: string; readonly name: `Auto ${level[0]!.toUpperCase()}${level.slice(1)}`, })); +function stampedLevel(selection: ModelSelection | null | undefined): AutoLevel | undefined { + const value = selection?.options?.find((option) => option.id === AUTO_OPTION_ID)?.value; + return AUTO_LEVELS.find((level) => level === value); +} + export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { - return isAutoModelSlug(selection?.model); + return isAutoModelSlug(selection?.model) || stampedLevel(selection) !== undefined; +} + +/** A routed thread's model as the Auto level it came from, for pickers; others unchanged. */ +export function autoLevelSelection( + selection: T, +): T | ModelSelection { + const level = stampedLevel(selection); + return selection && level + ? { instanceId: selection.instanceId, model: `${AUTO_MODEL_SLUG}-${level}` } + : selection; } function autoLevelOf(selection: ModelSelection): AutoLevel { + const stamped = stampedLevel(selection); + if (stamped) return stamped; const fixed = AUTO_LEVELS.find((level) => selection.model === `${AUTO_MODEL_SLUG}-${level}`); if (fixed) return fixed; const value = selection.options?.find((option) => option.id === "effort")?.value; @@ -204,12 +223,15 @@ function effortOptions(provider: ServerProvider, candidate: AutoCandidate) { : undefined; } -function toSelection(provider: ServerProvider, candidate: AutoCandidate): ModelSelection { - const options = effortOptions(provider, candidate); +function toSelection( + provider: ServerProvider, + candidate: AutoCandidate, + level: AutoLevel, +): ModelSelection { return { instanceId: provider.instanceId, model: candidate.model, - ...(options ? { options } : {}), + options: [...(effortOptions(provider, candidate) ?? []), { id: AUTO_OPTION_ID, value: level }], }; } @@ -235,7 +257,7 @@ export function resolveAutoModelSelection(input: { const candidates = AUTO_CANDIDATES[level]; const current = input.current; - if (current && !isAutoModelSelection(current)) { + if (current && !isAutoModelSlug(current.model)) { const provider = input.providers.find((entry) => entry.instanceId === current.instanceId); const candidate = candidates.find( (entry) => entry.driver === provider?.driver && entry.model === current.model, @@ -246,7 +268,7 @@ export function resolveAutoModelSelection(input: { usable(provider, candidate.model, input.now) && peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT ) { - return { selection: toSelection(provider, candidate), level, sticky: true }; + return { selection: toSelection(provider, candidate, level), level, sticky: true }; } } @@ -260,7 +282,9 @@ export function resolveAutoModelSelection(input: { // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. .sort(compareInstances); const provider = instances[0]; - if (provider) return { selection: toSelection(provider, candidate), level, sticky: false }; + if (provider) { + return { selection: toSelection(provider, candidate, level), level, sticky: false }; + } } return null; } From 545e30074ef86f1dac1f44beb17d102ab9c33982 Mon Sep 17 00:00:00 2001 From: radys-s Date: Sat, 14 Nov 2026 14:16:32 +0100 Subject: [PATCH 050/230] feat(usage): add smart reset credit advice to limits page --- .../components/usage/UsageLimitsPooled.tsx | 44 +++++++- packages/shared/src/usageLimits.test.ts | 104 +++++++++++++++++- packages/shared/src/usageLimits.ts | 2 +- packages/shared/src/usageLimitsCopy.ts | 84 ++++++++++++++ 4 files changed, 231 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index d0c3e5f43f99..ccf36e90e5c0 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -52,6 +52,7 @@ import { formatDuration, formatResetsIn, resetCreditChoices, + suggestResetCredit, } from "@t3tools/shared/usageLimitsCopy"; import { UsagePoolChart } from "./UsagePoolChart"; import { poolHistoryKey, readPoolHistory, recordPoolReadings } from "./usagePoolHistory"; @@ -148,6 +149,7 @@ function SegmentPopover({ account, window, reset, + poolMembers, now, redeem, onRedeem, @@ -155,6 +157,7 @@ function SegmentPopover({ readonly account: LimitAccount; readonly window: LimitPoolMember["window"]; readonly reset: LimitPoolWindow["resets"][number] | undefined; + readonly poolMembers?: readonly LimitPoolMember[] | undefined; readonly now: number; readonly redeem: ReturnType | null; readonly onRedeem: (choice: ResetCreditChoice) => void; @@ -169,6 +172,7 @@ function SegmentPopover({ account.environments.length > 0 ? account.environments.map((environment) => environment.label).join(", ") : account.sourceLabel; + const suggestion = suggestResetCredit(account, window, poolMembers ?? [{ account, window }], now); const choices = redeem && account.redeem && account.limits.resetCredits?.availableCount ? resetCreditChoices(account.limits.resetCredits, account.redeem.input, now, true, m) @@ -225,6 +229,28 @@ function SegmentPopover({ ) : null}
+ {suggestion ? ( +
+
+ + + Reset advice: + + + {suggestion.actionLabel} + +
+ {suggestion.reason} +
+ ) : null} {choices.length > 0 && redeem ? (
{choices.map((choice) => ( @@ -322,6 +348,7 @@ function PoolSegment({ readonly now: number; readonly index: number; readonly showAccountName: boolean; + readonly poolMembers?: readonly LimitPoolMember[] | undefined; }) { return account.redeem ? ( @@ -364,6 +391,7 @@ function SegmentTriggers({ window, reset, redeem, + poolMembers, refillPercent, color, now, @@ -377,7 +405,7 @@ function SegmentTriggers({ readonly showAccountName: boolean; }) { const popover = use(SegmentPopoverContext) ?? undefined; - const payload: SegmentPayload = { account, window, reset, redeem }; + const payload: SegmentPayload = { account, window, reset, redeem, poolMembers }; const remaining = remainingPercent(window); const timeLeft = paceRemainingPercent(window, now); const [segmentRef, paceMark] = usePaceMark(timeLeft); @@ -581,6 +609,7 @@ function PoolBar({ now={now} index={position + 1} showAccountName={pool.columns.length > 1} + poolMembers={pool.members} /> ) : pool.kind === "monthly" && member.account.limits.zeroSpendCap ? (
+ {(() => { + const advice = pool.members + .filter((m) => m.window && (m.account.limits.resetCredits?.availableCount ?? 0) > 0) + .map((m) => suggestResetCredit(m.account, m.window!, pool.members, now)) + .find(Boolean); + return advice ? ( +
+ + {advice.actionLabel}: + {advice.reason} +
+ ) : null; + })()} {description ?

{description}

: null}
); diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index 0078c21b566b..bd616cf5865d 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -25,7 +25,7 @@ import { usesChatGptSharing, resolveNewThreadModelSelection, } from "./usageLimits.ts"; -import { collectLimitNotices } from "./usageLimitsCopy.ts"; +import { collectLimitNotices, suggestResetCredit } from "./usageLimitsCopy.ts"; const now = Date.parse("2026-09-03T12:00:00.000Z"); @@ -1837,3 +1837,105 @@ describe("ChatGPT sharing presentation", () => { ).toBe(false); }); }); + +describe("suggestResetCredit advice", () => { + const baseAccount: LimitAccount = { + key: "claude_a", + driver: ProviderDriverKind.make("claudeAgent"), + displayName: "Claude A", + email: undefined, + plan: "Max", + accentColor: undefined, + sourceLabel: "Desk", + environments: [], + limits: { + checkedAt: "2026-09-03T11:00:00.000Z", + windows: [], + resetCredits: { + availableCount: 1, + }, + }, + redeem: null, + }; + + const depletedWindow = { + id: "five_hour", + kind: "session" as const, + label: "Session", + usedPercent: 100, + windowDurationMins: 300, + resetsAt: "2026-09-03T15:00:00.000Z", + }; + + it("returns null when no reset credits are available", () => { + const acc = { + ...baseAccount, + limits: { ...baseAccount.limits, resetCredits: { availableCount: 0 } }, + }; + expect(suggestResetCredit(acc, depletedWindow, [], now)).toBeNull(); + }); + + it("suggests waiting when natural reset is within 45 minutes", () => { + const imminentWindow = { ...depletedWindow, resetsAt: "2026-09-03T12:20:00.000Z" }; // 20 mins from now + const advice = suggestResetCredit(baseAccount, imminentWindow, [], now); + expect(advice?.recommendation).toBe("wait"); + expect(advice?.actionLabel).toBe("Wait for natural reset"); + expect(advice?.reason).toContain("20m"); + }); + + it("suggests saving when account still has >20% remaining", () => { + const healthyWindow = { ...depletedWindow, usedPercent: 40 }; // 60% remaining + const advice = suggestResetCredit(baseAccount, healthyWindow, [], now); + expect(advice?.recommendation).toBe("save"); + expect(advice?.actionLabel).toBe("Save for later"); + }); + + it("suggests holding when another account in pool has healthy quota", () => { + const otherAccount: LimitAccount = { + ...baseAccount, + key: "claude_b", + }; + const otherWindow = { ...depletedWindow, usedPercent: 30 }; // 70% remaining + const advice = suggestResetCredit( + baseAccount, + depletedWindow, + [ + { account: baseAccount, window: depletedWindow }, + { account: otherAccount, window: otherWindow }, + ], + now, + ); + expect(advice?.recommendation).toBe("hold"); + expect(advice?.actionLabel).toContain("Hold off"); + expect(advice?.reason).toContain("70%"); + }); + + it("recommends using reset when depleted and next reset is hours away", () => { + const advice = suggestResetCredit( + baseAccount, + depletedWindow, + [{ account: baseAccount, window: depletedWindow }], + now, + ); + expect(advice?.recommendation).toBe("recommended"); + expect(advice?.actionLabel).toBe("Recommended to use now"); + expect(advice?.reason).toContain("in 3h"); + }); + + it("warns when reset credit expires within 24h", () => { + const expiringAccount: LimitAccount = { + ...baseAccount, + limits: { + ...baseAccount.limits, + resetCredits: { + availableCount: 1, + nextExpiresAt: "2026-09-03T18:00:00.000Z", // 6h from now + }, + }, + }; + const advice = suggestResetCredit(expiringAccount, depletedWindow, [], now); + expect(advice?.recommendation).toBe("expiring_soon"); + expect(advice?.actionLabel).toBe("Use before expiry"); + expect(advice?.reason).toContain("6h"); + }); +}); diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 693d82b95697..c46c420a226e 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -701,7 +701,7 @@ export function remainingPercent(window: ServerProviderUsageWindow): number { return Math.round(100 - Math.max(0, Math.min(100, window.usedPercent))); } -function resetMillis(window: ServerProviderUsageWindow): number | null { +export function resetMillis(window: ServerProviderUsageWindow): number | null { if (window.resetsAt === undefined) return null; const at = Date.parse(window.resetsAt); return Number.isFinite(at) ? at : null; diff --git a/packages/shared/src/usageLimitsCopy.ts b/packages/shared/src/usageLimitsCopy.ts index d772c48b29aa..9186bc1ff08b 100644 --- a/packages/shared/src/usageLimitsCopy.ts +++ b/packages/shared/src/usageLimitsCopy.ts @@ -10,11 +10,14 @@ import type { MFunctionType } from "gt-i18n/types"; import { collectExternalUsageLinks as collectExternalUsageLinksWith, cursorUsageWindowDetails as cursorUsageWindowDetailsBase, + type LimitAccount, type LimitPool, type LimitPresentations, providersWithLimits, + remainingPercent, type ResetCreditChoice, resetCountdown, + resetMillis, } from "./usageLimits.ts"; const MINUTE = 60_000; @@ -213,3 +216,84 @@ export function formatResetsIn( if (style === "refill") return resolve(msg("↻ {duration}", { duration })); return resolve(msg("resets in {duration}", { duration })); } + +export interface ResetCreditSuggestion { + readonly recommendation: "recommended" | "wait" | "save" | "hold" | "expiring_soon"; + readonly actionLabel: string; + readonly reason: string; +} + +export function suggestResetCredit( + account: LimitAccount, + window: ServerProviderUsageWindow, + poolMembers: ReadonlyArray<{ + readonly account: LimitAccount; + readonly window?: ServerProviderUsageWindow | null; + }>, + now: number, +): ResetCreditSuggestion | null { + const credits = account.limits.resetCredits; + if (!credits || credits.availableCount <= 0) return null; + + const remaining = remainingPercent(window); + const resetsAt = resetMillis(window); + const resetsInMs = resetsAt !== null ? resetsAt - now : null; + + // 1. Expiring soon: credit expires within 24 hours + const optionExpiries = (credits.options ?? []) + .filter((opt) => opt.availableCount > 0 && opt.expiresAt) + .map((opt) => Date.parse(opt.expiresAt!)) + .filter(Number.isFinite); + const nextExpires = credits.nextExpiresAt ? Date.parse(credits.nextExpiresAt) : null; + if (nextExpires && Number.isFinite(nextExpires)) { + optionExpiries.push(nextExpires); + } + const soonestExpiry = optionExpiries.length > 0 ? Math.min(...optionExpiries) : null; + if (soonestExpiry !== null) { + const timeUntilExpiry = soonestExpiry - now; + if (timeUntilExpiry > 0 && timeUntilExpiry <= 24 * 3600 * 1000) { + return { + recommendation: "expiring_soon", + actionLabel: "Use before expiry", + reason: `Banked reset credit expires in ${formatDuration(timeUntilExpiry)}. Use it before it expires.`, + }; + } + } + + // 2. Natural reset is imminent (within 45 minutes) + if (resetsInMs !== null && resetsInMs > 0 && resetsInMs <= 45 * 60 * 1000) { + return { + recommendation: "wait", + actionLabel: "Wait for natural reset", + reason: `Window resets naturally in ${formatDuration(resetsInMs)}. Save your banked credit.`, + }; + } + + // 3. This account still has plenty of quota (> 20% remaining) + if (remaining > 20) { + return { + recommendation: "save", + actionLabel: "Save for later", + reason: `${remaining}% quota remaining. Reset only when depleted.`, + }; + } + + // 4. Other account in the same pool has plenty of quota (> 25% remaining) + const otherMembers = poolMembers.filter((m) => m.account.key !== account.key && m.window); + const otherMaxRemaining = + otherMembers.length > 0 ? Math.max(...otherMembers.map((m) => remainingPercent(m.window!))) : 0; + if (otherMaxRemaining > 25) { + return { + recommendation: "hold", + actionLabel: "Hold off (other account active)", + reason: `Auto mode has another account with ${otherMaxRemaining}% quota left. Save credit until both are depleted.`, + }; + } + + // 5. Recommended: Account is depleted and next reset is far away (or not soon) + return { + recommendation: "recommended", + actionLabel: "Recommended to use now", + reason: `Quota depleted and next natural reset is ${resetsInMs !== null && resetsInMs > 0 ? `in ${formatDuration(resetsInMs)}` : "hours away"}. Good time to reset.`, + }; +} From 5d946055f6a638f3237ef0c9be29bff4dd6206e4 Mon Sep 17 00:00:00 2001 From: radys-s Date: Sat, 14 Nov 2026 21:37:35 +0100 Subject: [PATCH 051/230] feat(auto): fail over to the next subscription when one hits its limit When a run on an Auto thread fails with a usage limit or no capacity, bench that provider instance and send the thread back through Auto, which skips benched instances, so work continues on the next subscription instead of waiting hours for the reset. --- .../src/orchestration-v2/AutoCooldown.ts | 25 +++ .../AutoFailoverService.test.ts | 107 +++++++++++ .../orchestration-v2/AutoFailoverService.ts | 168 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 5 +- apps/server/src/server.ts | 6 + docs/progress.md | 8 + packages/shared/src/autoModel.test.ts | 18 ++ packages/shared/src/autoModel.ts | 16 +- 8 files changed, 350 insertions(+), 3 deletions(-) create mode 100644 apps/server/src/orchestration-v2/AutoCooldown.ts create mode 100644 apps/server/src/orchestration-v2/AutoFailoverService.test.ts create mode 100644 apps/server/src/orchestration-v2/AutoFailoverService.ts diff --git a/apps/server/src/orchestration-v2/AutoCooldown.ts b/apps/server/src/orchestration-v2/AutoCooldown.ts new file mode 100644 index 000000000000..f4eddaf6738e --- /dev/null +++ b/apps/server/src/orchestration-v2/AutoCooldown.ts @@ -0,0 +1,25 @@ +/** + * Provider instances that just failed an Auto thread with a usage limit or no capacity. The + * usage report can lag behind (or never show a gateway's 429), so Auto routing skips these until + * the cooldown ends. Lives in memory: a server restart forgets it, and the usage report takes over. + */ +const cooldowns = new Map(); + +/** Per instance; a model-scoped limit (Antigravity pools) still benches the whole instance. */ +export function markAutoCooldown(instanceId: string, untilMs: number): void { + const current = cooldowns.get(instanceId) ?? 0; + if (untilMs > current) cooldowns.set(instanceId, untilMs); +} + +export function isAutoCoolingDown(instanceId: string, nowMs: number): boolean { + const until = cooldowns.get(instanceId); + if (until === undefined) return false; + if (until > nowMs) return true; + cooldowns.delete(instanceId); + return false; +} + +/** Tests only. */ +export function clearAutoCooldowns(): void { + cooldowns.clear(); +} diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts new file mode 100644 index 000000000000..e037eb675462 --- /dev/null +++ b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts @@ -0,0 +1,107 @@ +import { + ProviderInstanceId, + RunId, + ThreadId, + type OrchestrationV2ThreadShell, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { clearAutoCooldowns, isAutoCoolingDown, markAutoCooldown } from "./AutoCooldown.ts"; +import { admitFailover, autoFailoverPlan, MAX_FAILOVERS_PER_HOUR } from "./AutoFailoverService.ts"; + +const now = Date.parse("2026-11-14T20:00:00.000Z"); +const runId = RunId.make("run:thread:t1:ordinal:3"); + +function shell(overrides: Partial> = {}): OrchestrationV2ThreadShell { + return { + id: ThreadId.make("t1"), + providerInstanceId: ProviderInstanceId.make("claudeAuto"), + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAuto"), + model: "claude-opus-5-5", + options: [ + { id: "effort", value: "medium" }, + { id: "auto", value: "medium" }, + ], + }, + latestRunId: runId, + status: "failed", + lastErrorClass: "usage_limit", + lastErrorCode: "api_error_429", + usageLimitResetAt: null, + archivedAt: null, + settledOverride: null, + pendingRuntimeRequest: null, + ...overrides, + } as unknown as OrchestrationV2ThreadShell; +} + +const plan = (s: OrchestrationV2ThreadShell) => + autoFailoverPlan({ shell: s, runId, failedInstanceId: "claudeAuto", nowMs: now }); + +describe("autoFailoverPlan", () => { + it("sends a limited Auto thread back through Auto at its level", () => { + const result = plan(shell()); + expect(result?.command).toMatchObject({ + type: "message.dispatch", + threadId: "t1", + modelSelection: { instanceId: "claudeAuto", model: "auto-medium" }, + dispatchMode: { type: "start_immediately" }, + createdBy: "agent", + creationSource: "server", + }); + expect(result?.command.commandId).toBe(`server:auto-failover:t1:${runId}`); + // No reported reset: a 30 minute bench. + expect(result?.cooldownUntilMs).toBe(now + 30 * 60_000); + }); + + it("benches the instance until the reported reset", () => { + const resetAt = "2026-11-14T23:00:00.000Z"; + expect(plan(shell({ usageLimitResetAt: resetAt }))?.cooldownUntilMs).toBe(Date.parse(resetAt)); + }); + + it("fails over on no-capacity errors for a short bench", () => { + const result = plan(shell({ lastErrorClass: "provider_error", lastErrorCode: "UNAVAILABLE" })); + expect(result?.cooldownUntilMs).toBe(now + 5 * 60_000); + }); + + it("leaves other failures, non-Auto threads and stale runs alone", () => { + expect( + plan(shell({ lastErrorClass: "provider_error", lastErrorCode: "api_error_404" })), + ).toBeNull(); + expect( + plan( + shell({ + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-opus-5-5", + }, + }), + ), + ).toBeNull(); + expect(plan(shell({ latestRunId: RunId.make("run:newer") }))).toBeNull(); + expect(plan(shell({ status: "idle" }))).toBeNull(); + expect(plan(shell({ settledOverride: "settled" }))).toBeNull(); + }); +}); + +describe("admitFailover", () => { + it("caps failovers per thread per hour", () => { + const history: Array = []; + for (let i = 0; i < MAX_FAILOVERS_PER_HOUR; i++) + expect(admitFailover(history, now + i)).toBe(true); + expect(admitFailover(history, now + 10)).toBe(false); + expect(admitFailover(history, now + 61 * 60_000)).toBe(true); + }); +}); + +describe("AutoCooldown", () => { + it("benches an instance until the time passes", () => { + clearAutoCooldowns(); + markAutoCooldown("claudeAuto", now + 1000); + markAutoCooldown("claudeAuto", now + 500); + expect(isAutoCoolingDown("claudeAuto", now + 999)).toBe(true); + expect(isAutoCoolingDown("claudeAuto", now + 1000)).toBe(false); + expect(isAutoCoolingDown("claudeAutoB", now)).toBe(false); + }); +}); diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.ts b/apps/server/src/orchestration-v2/AutoFailoverService.ts new file mode 100644 index 000000000000..e5185172de09 --- /dev/null +++ b/apps/server/src/orchestration-v2/AutoFailoverService.ts @@ -0,0 +1,168 @@ +import { + CommandId, + MessageId, + type OrchestrationV2ThreadShell, + type RunId, + type ThreadId, +} from "@t3tools/contracts"; +import { routedAutoLevel } from "@t3tools/shared/autoModel"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FiberMap from "effect/FiberMap"; +import * as Stream from "effect/Stream"; + +import { forkParked } from "../serverActivation.ts"; +import { markAutoCooldown } from "./AutoCooldown.ts"; +import * as Orchestrator from "./Orchestrator.ts"; + +/** Failures that mean "this account has no room right now", besides the usage_limit class. */ +const CAPACITY_CODES: ReadonlySet = new Set([ + "UNAVAILABLE", + "RESOURCE_EXHAUSTED", + "api_error_529", + "overloaded_error", +]); +/** A limit without a reported reset benches the instance this long. */ +const LIMIT_COOLDOWN_MS = 30 * 60_000; +/** No capacity is usually short-lived. */ +const CAPACITY_COOLDOWN_MS = 5 * 60_000; +/** A reported reset further out than this is treated as this. */ +const MAX_COOLDOWN_MS = 7 * 24 * 60 * 60_000; +/** At most this many failovers per thread per hour, so a misreported limit cannot loop. */ +export const MAX_FAILOVERS_PER_HOUR = 6; +/** The run's error item lands around the same time as the run update; let the shell catch up. */ +const SETTLE_DELAY_MS = 1_500; + +const AUTO_FAILOVER_TEXT = + "Auto moved this thread to another subscription because the last one hit its usage limit. Continue where you left off."; + +export interface AutoFailoverPlan { + readonly failedInstanceId: string; + readonly cooldownUntilMs: number; + readonly command: Extract< + Parameters[0], + { readonly type: "message.dispatch" } + >; +} + +/** + * What to do when a run on an Auto thread fails: bench the instance that failed and send the + * thread back through Auto, which then picks the next subscription in the chain. Null when the + * run did not fail for lack of room, or the thread is not on Auto, or is no longer the + * thread's latest run. + */ +export function autoFailoverPlan(input: { + readonly shell: OrchestrationV2ThreadShell; + readonly runId: RunId; + readonly failedInstanceId: string; + readonly nowMs: number; +}): AutoFailoverPlan | null { + const { shell, runId, nowMs } = input; + if ( + shell.latestRunId !== runId || + shell.status !== "failed" || + shell.archivedAt !== null || + shell.settledOverride === "settled" || + shell.pendingRuntimeRequest !== null + ) + return null; + const level = routedAutoLevel(shell.modelSelection); + if (level === undefined) return null; + const limited = shell.lastErrorClass === "usage_limit"; + const noCapacity = !limited && CAPACITY_CODES.has(shell.lastErrorCode ?? ""); + if (!limited && !noCapacity) return null; + const resetMs = shell.usageLimitResetAt ? Date.parse(shell.usageLimitResetAt) : Number.NaN; + const cooldownUntilMs = noCapacity + ? nowMs + CAPACITY_COOLDOWN_MS + : Number.isFinite(resetMs) && resetMs > nowMs + ? Math.min(resetMs, nowMs + MAX_COOLDOWN_MS) + : nowMs + LIMIT_COOLDOWN_MS; + return { + failedInstanceId: input.failedInstanceId, + cooldownUntilMs, + command: { + type: "message.dispatch", + // One failover per failed run, even across duplicate events. + commandId: CommandId.make(`server:auto-failover:${shell.id}:${runId}`), + messageId: MessageId.make(`auto-failover:${shell.id}:${runId}`), + threadId: shell.id, + // The Auto level row; routing replaces it with the next usable subscription. + modelSelection: { instanceId: shell.modelSelection.instanceId, model: `auto-${level}` }, + text: AUTO_FAILOVER_TEXT, + attachments: [], + createdBy: "agent", + creationSource: "server", + dispatchMode: { type: "start_immediately" }, + }, + }; +} + +/** Keeps the timestamps of recent failovers under the hourly cap; true when one more fits. */ +export function admitFailover(history: Array, nowMs: number): boolean { + const recent = history.filter((at) => nowMs - at < 60 * 60_000); + history.splice(0, history.length, ...recent); + if (recent.length >= MAX_FAILOVERS_PER_HOUR) return false; + history.push(nowMs); + return true; +} + +/** + * Fork feature: when a run on an Auto thread fails because its subscription hit a usage limit + * (or has no capacity), the thread moves on at once to the next subscription Auto picks, instead + * of waiting hours for that account to reset. + */ +export const make = Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const history = new Map>(); + + const failOver = Effect.fn("AutoFailoverService.failOver")( + function* (threadId: ThreadId, runId: RunId, failedInstanceId: string) { + yield* Effect.sleep(Duration.millis(SETTLE_DELAY_MS)); + const shell = yield* orchestrator.getThreadShell(threadId); + if (shell === null) return; + const nowMs = DateTime.toEpochMillis(yield* DateTime.now); + const plan = autoFailoverPlan({ shell, runId, failedInstanceId, nowMs }); + if (plan === null) return; + markAutoCooldown(plan.failedInstanceId, plan.cooldownUntilMs); + const threadHistory = history.get(threadId) ?? []; + history.set(threadId, threadHistory); + if (!admitFailover(threadHistory, nowMs)) { + yield* Effect.logWarning("auto failover skipped: hourly cap reached", { threadId }); + return; + } + yield* Effect.logInfo("auto failover", { + threadId, + runId, + failedInstanceId, + errorClass: shell.lastErrorClass, + errorCode: shell.lastErrorCode, + cooldownUntil: DateTime.formatIso(DateTime.makeUnsafe(plan.cooldownUntilMs)), + }); + yield* orchestrator.dispatch(plan.command); + }, + (effect, threadId) => + effect.pipe( + Effect.catch((cause) => + // No usable subscription left: the usage-limit recovery worker still resumes at reset. + Effect.logWarning("auto failover did not dispatch", { threadId, cause }), + ), + ), + ); + + const start = Effect.fn("AutoFailoverService.start")(function* () { + const pending = yield* FiberMap.make(); + yield* forkParked( + Stream.runForEach(orchestrator.streamDomainEvents, (event) => + event.type === "run.updated" && event.payload.status === "failed" + ? FiberMap.run( + pending, + event.threadId, + failOver(event.threadId, event.payload.id, event.payload.providerInstanceId), + ) + : Effect.void, + ), + ); + }); + return { start }; +}); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 11b59f3b2669..0cbd2c65a921 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -83,6 +83,7 @@ import { import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { modelSelectionsEqual } from "@t3tools/shared/model"; import { isAutoModelSelection, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; +import { isAutoCoolingDown } from "./AutoCooldown.ts"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import { modelSwitchSince } from "./modelSwitch.ts"; import { contextBoundaryOrdinal, isScheduledFreshRun } from "./contextBoundary.ts"; @@ -16595,11 +16596,13 @@ const withAutoModelRouting = Effect.fn("OrchestratorV2.withAutoModelRouting")(fu ? ((yield* orchestrator.getThreadShell(threadId).pipe(Effect.orElseSucceed(() => null))) ?.modelSelection ?? null) : null; + const now = DateTime.toEpochMillis(yield* DateTime.now); const resolution = resolveAutoModelSelection({ selection, providers: Option.isSome(registry) ? yield* registry.value.getProviders : [], - now: DateTime.toEpochMillis(yield* DateTime.now), + now, current, + blocked: (instanceId) => isAutoCoolingDown(instanceId, now), }); if (resolution === null) { return yield* new OrchestratorCommandRejectedError({ diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 29e3143cbc63..eb7f5bfff981 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -218,6 +218,7 @@ import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts"; import * as IdleCompactionService from "./orchestration-v2/IdleCompactionService.ts"; +import * as AutoFailoverService from "./orchestration-v2/AutoFailoverService.ts"; import * as ThreadPullRequestService from "./orchestration-v2/ThreadPullRequestService.ts"; import * as ThreadIssueService from "./orchestration-v2/ThreadIssueService.ts"; import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts"; @@ -631,6 +632,10 @@ const layerThreadSettlementWorker = Layer.effectDiscard( ThreadSettlementService.make.pipe(Effect.flatMap((service) => service.start())), ).pipe(Layer.provide(layerPullRequestService), Layer.provide(ProjectionStoreV2.layer)); +const layerAutoFailoverWorker = Layer.effectDiscard( + AutoFailoverService.make.pipe(Effect.flatMap((service) => service.start())), +); + const layerIdleCompactionWorker = Layer.effectDiscard( IdleCompactionService.make.pipe(Effect.flatMap((service) => service.start())), ).pipe(Layer.provide(ProjectionStoreV2.layer)); @@ -690,6 +695,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( HeldHooksWaker.layer, layerThreadSettlementWorker, layerIdleCompactionWorker, + layerAutoFailoverWorker, StorageCleanup.layer.pipe(Layer.provide(ProjectionStoreV2.layer)), DatabaseStorage.layer.pipe( Layer.provide(ProjectionMaintenance.layer), diff --git a/docs/progress.md b/docs/progress.md index 1db4eaeb2169..236f4c4d9f34 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -74,3 +74,11 @@ - Numbers: autoModel 12/12, handoff + contextWindow 39/39 (a recursion the stamp caused was caught by the handoff test); shared, client-runtime, web, mobile and server typecheck clean. Checked in a clean incognito browser on a scratch copy of hub2's data: a thread started on Auto Low over the CLI shows Auto Low in the composer. - Deploy: service now runs from `~/.t3/fork-current` (a symlink to the deploy checkout), so a new build goes into a fresh checkout and the restart flips the link. - Next: hub (link it first) and a fork build of the PC desktop app; the stock app still shows the concrete model. + +## 2026-11-14: Auto fails over to the next subscription the moment one hits its limit + +- What: `AutoFailoverService` watches failed runs. When a run on an Auto thread fails with a usage limit (`usage_limit` class: Claude 429 / 5-hour / weekly, Codex `usageLimitExceeded`, Antigravity `RESOURCE_EXHAUSTED`) or no capacity (`UNAVAILABLE`, Claude 529), it benches that provider instance (`AutoCooldown`, until the reported reset, else 30 min; 5 min for no capacity) and sends the thread back through Auto with "Continue where you left off". Auto routing (`resolveAutoModelSelection`) skips benched instances, the sticky current one included. At most 6 failovers per thread per hour. +- Why: Auto routed only when a message was sent. A limit hit mid-work left the thread failed, and the upstream recovery worker resumed it on the same account hours later, at reset. Tomáš wants Auto to chain across all subscriptions as soon as one runs out. The PC's own DB showed 28 failed runs in two days, most of them limit errors (429, quota, capacity) that should have moved on. +- Numbers: autoModel 13/13 (new blocked case), AutoFailoverService 6/6; server typecheck clean. +- Limits: the bench is in memory, so a server restart forgets it (the usage report takes over). A failure whose session error differs from the run's error item has no error class and is not failed over. +- Next: build the PC desktop app from `tomas/pc-nightly`; deploy to hub/hub2. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index e3b6e708f89d..7391bb9fa06f 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -304,6 +304,24 @@ describe("resolveAutoModelSelection", () => { expect(autoLevelSelection(plain)).toBe(plain); }); + it("skips blocked instances, the thread's current one included", () => { + const current = { instanceId: ProviderInstanceId.make("claudeAuto"), model: "claude-opus-5-5" }; + const calm = [claude("claudeAuto", 20), claude("claudeAutoB", 5)]; + const blocked = (instanceId: string) => instanceId === "claudeAuto"; + expect( + resolveAutoModelSelection({ selection: auto(), providers: calm, now, current, blocked }), + ).toMatchObject({ sticky: false, selection: { instanceId: "claudeAutoB" } }); + expect( + resolveAutoModelSelection({ + selection: auto(), + providers: calm, + now, + current, + blocked: () => true, + }), + ).toBeNull(); + }); + it("returns null when nothing is usable", () => { const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; expect(resolveAutoModelSelection({ selection: auto(), providers, now })).toBeNull(); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 74519c6e38e5..d4eaee1d0dad 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -131,6 +131,11 @@ export function isAutoModelSelection(selection: ModelSelection | null | undefine } /** A routed thread's model as the Auto level it came from, for pickers; others unchanged. */ +/** The Auto level a routed thread runs at, or undefined for a thread not on Auto. */ +export function routedAutoLevel(selection: ModelSelection | null | undefined) { + return stampedLevel(selection); +} + export function autoLevelSelection( selection: T, ): T | ModelSelection { @@ -252,9 +257,16 @@ export function resolveAutoModelSelection(input: { readonly providers: ReadonlyArray; readonly now: number; readonly current?: ModelSelection | null; + /** + * Instances (and models) that just failed with a usage limit or no capacity, which the usage + * report may not show yet. Auto skips them, the thread's current model included. + */ + readonly blocked?: (instanceId: string, model: string) => boolean; }): AutoResolution | null { const level = autoLevelOf(input.selection); const candidates = AUTO_CANDIDATES[level]; + const open = (provider: ServerProvider, model: string) => + usable(provider, model, input.now) && !input.blocked?.(provider.instanceId, model); const current = input.current; if (current && !isAutoModelSlug(current.model)) { @@ -265,7 +277,7 @@ export function resolveAutoModelSelection(input: { if ( provider && candidate && - usable(provider, candidate.model, input.now) && + open(provider, candidate.model) && peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT ) { return { selection: toSelection(provider, candidate, level), level, sticky: true }; @@ -277,7 +289,7 @@ export function resolveAutoModelSelection(input: { .filter( (provider) => provider.driver === (candidate.driver as ProviderDriverKind) && - usable(provider, candidate.model, input.now), + open(provider, candidate.model), ) // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. .sort(compareInstances); From adac6a649705a999a78c8221712efa4834c0ba6c Mon Sep 17 00:00:00 2001 From: radys-s Date: Sun, 15 Nov 2026 14:59:37 +0100 Subject: [PATCH 052/230] fix(auto): return to the better model after a reset; failover follows auto-resume Review of the failover commit before it went on the PC: - A thread that failed over to a weaker model stayed there while that account was under 90% used, even after the better account reset. The sticky rule now gives way when a better candidate has room. - Failover follows the autoResumeLimitedThreads setting: off still benches the failed instance, but sends nothing on its own. - Failover skips a provider's own subagent threads, which cannot receive messages. --- .../AutoFailoverService.test.ts | 17 +++++++++++++ .../orchestration-v2/AutoFailoverService.ts | 10 +++++++- docs/progress.md | 9 +++++++ packages/shared/src/autoModel.test.ts | 22 ++++++++++++++++ packages/shared/src/autoModel.ts | 25 ++++++++++++++----- 5 files changed, 76 insertions(+), 7 deletions(-) diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts index e037eb675462..078076aca8a2 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts @@ -25,6 +25,12 @@ function shell(overrides: Partial> = {}): OrchestrationV ], }, latestRunId: runId, + lineage: { + rootThreadId: ThreadId.make("t1"), + parentThreadId: null, + relationshipToParent: null, + }, + creationSource: "user", status: "failed", lastErrorClass: "usage_limit", lastErrorCode: "api_error_429", @@ -86,6 +92,17 @@ describe("autoFailoverPlan", () => { }); describe("admitFailover", () => { + it("leaves a provider's own subagent alone, which cannot receive messages", () => { + const lineage = { + rootThreadId: ThreadId.make("t0"), + parentThreadId: ThreadId.make("t0"), + relationshipToParent: "subagent", + }; + expect(plan(shell({ lineage, creationSource: "provider" }))).toBeNull(); + // A delegate_task child takes messages like any thread. + expect(plan(shell({ lineage, creationSource: "agent" }))).not.toBeNull(); + }); + it("caps failovers per thread per hour", () => { const history: Array = []; for (let i = 0; i < MAX_FAILOVERS_PER_HOUR; i++) diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.ts b/apps/server/src/orchestration-v2/AutoFailoverService.ts index e5185172de09..b91420a90553 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.ts @@ -1,5 +1,6 @@ import { CommandId, + isProviderNativeSubagentThread, MessageId, type OrchestrationV2ThreadShell, type RunId, @@ -13,6 +14,7 @@ import * as FiberMap from "effect/FiberMap"; import * as Stream from "effect/Stream"; import { forkParked } from "../serverActivation.ts"; +import * as ServerSettings from "../serverSettings.ts"; import { markAutoCooldown } from "./AutoCooldown.ts"; import * as Orchestrator from "./Orchestrator.ts"; @@ -64,7 +66,9 @@ export function autoFailoverPlan(input: { shell.status !== "failed" || shell.archivedAt !== null || shell.settledOverride === "settled" || - shell.pendingRuntimeRequest !== null + shell.pendingRuntimeRequest !== null || + // A provider's own subagent cannot receive messages; its parent sees the failure. + isProviderNativeSubagentThread(shell) ) return null; const level = routedAutoLevel(shell.modelSelection); @@ -114,6 +118,7 @@ export function admitFailover(history: Array, nowMs: number): boolean { */ export const make = Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; + const settings = yield* ServerSettings.ServerSettingsService; const history = new Map>(); const failOver = Effect.fn("AutoFailoverService.failOver")( @@ -124,7 +129,10 @@ export const make = Effect.gen(function* () { const nowMs = DateTime.toEpochMillis(yield* DateTime.now); const plan = autoFailoverPlan({ shell, runId, failedInstanceId, nowMs }); if (plan === null) return; + // Bench the instance either way, so the next message the user sends routes around it. markAutoCooldown(plan.failedInstanceId, plan.cooldownUntilMs); + // The same switch as resuming at reset: off means T3 sends nothing on its own. + if (!(yield* settings.getSettings).autoResumeLimitedThreads) return; const threadHistory = history.get(threadId) ?? []; history.set(threadId, threadHistory); if (!admitFailover(threadHistory, nowMs)) { diff --git a/docs/progress.md b/docs/progress.md index 236f4c4d9f34..3b15d3cdc7c9 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -82,3 +82,12 @@ - Numbers: autoModel 13/13 (new blocked case), AutoFailoverService 6/6; server typecheck clean. - Limits: the bench is in memory, so a server restart forgets it (the usage report takes over). A failure whose session error differs from the run's error item has no error class and is not failed over. - Next: build the PC desktop app from `tomas/pc-nightly`; deploy to hub/hub2. + +## 2026-11-15: Auto failover review fixes, and a way back to the better model + +- What: (1) Auto's sticky rule now gives way when a better candidate for the level has room again. Before, a thread that failed over to a weaker model (say Grok) stayed there for good while that account was under 90% used, even after Claude reset. (2) Failover follows the `autoResumeLimitedThreads` setting: off means the failed instance is still benched (the next message the user sends routes around it), but T3 sends nothing on its own. (3) Failover skips a provider's own subagent threads, which cannot receive messages. +- Why: review of `d25e0609c7` before it went on the PC. The failover sends turns by itself, so a mistake there spends every subscription. The one-way downgrade contradicted the Auto skill, which says a provider re-enters the chain when its window resets. +- Checked and left alone: the domain event stream starts at the latest sequence, so a server restart does not replay old failed runs into failovers. A failover and the upstream reset-resume cannot both fire: the resume needs the thread's latest run to be the failed one. The return to a better model needs that account under 90%, so a thread does not hop back onto an account about to run out. +- Numbers: autoModel 14/14, AutoFailoverService 7/7, server typecheck 0 errors. +- Cost: moving back up is one more provider handoff (a thread summary). It happens once per reset, on the next message. +- Next: build the PC desktop app from `tomas/pc-nightly` and install it. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index 7391bb9fa06f..d179263a94a5 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -322,6 +322,28 @@ describe("resolveAutoModelSelection", () => { ).toBeNull(); }); + it("returns from a weaker fallback once a better model has room again", () => { + const grok = { + ...claude("grok", 0, false), + driver: ProviderDriverKind.make("grok"), + models: [{ slug: "grok-4.7", name: "Grok 4.7", isCustom: false, capabilities: null }], + usageLimits: undefined, + } as unknown as ServerProvider; + const current = { instanceId: ProviderInstanceId.make("grok"), model: "grok-4.7" }; + const resolve = (claudeUsed: number) => + resolveAutoModelSelection({ + selection: auto(), + providers: [claude("claudeAuto", claudeUsed), grok], + now, + current, + }); + // Claude is back: the thread leaves Grok. + expect(resolve(10)).toMatchObject({ sticky: false, selection: { instanceId: "claudeAuto" } }); + // Claude is nearly out or exhausted: no hop back that would fail again at once. + expect(resolve(95)).toMatchObject({ sticky: true, selection: { instanceId: "grok" } }); + expect(resolve(100)).toMatchObject({ sticky: true, selection: { instanceId: "grok" } }); + }); + it("returns null when nothing is usable", () => { const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; expect(resolveAutoModelSelection({ selection: auto(), providers, now })).toBeNull(); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index d4eaee1d0dad..2ee6fa04460e 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -130,12 +130,12 @@ export function isAutoModelSelection(selection: ModelSelection | null | undefine return isAutoModelSlug(selection?.model) || stampedLevel(selection) !== undefined; } -/** A routed thread's model as the Auto level it came from, for pickers; others unchanged. */ /** The Auto level a routed thread runs at, or undefined for a thread not on Auto. */ export function routedAutoLevel(selection: ModelSelection | null | undefined) { return stampedLevel(selection); } +/** A routed thread's model as the Auto level it came from, for pickers; others unchanged. */ export function autoLevelSelection( selection: T, ): T | ModelSelection { @@ -248,9 +248,9 @@ interface AutoResolution { } /** - * Keeps the thread's model while it fits this level and is under 90% used (no account hop, no - * lost prompt cache); otherwise the first usable candidate on the best instance (see - * `compareInstances`). Null when nothing is usable. + * Keeps the thread's model while it fits this level, is under 90% used and no better candidate + * has room (no account hop, no lost prompt cache); otherwise the first usable candidate on the + * best instance (see `compareInstances`). Null when nothing is usable. */ export function resolveAutoModelSelection(input: { readonly selection: ModelSelection; @@ -271,14 +271,27 @@ export function resolveAutoModelSelection(input: { const current = input.current; if (current && !isAutoModelSlug(current.model)) { const provider = input.providers.find((entry) => entry.instanceId === current.instanceId); - const candidate = candidates.find( + const rank = candidates.findIndex( (entry) => entry.driver === provider?.driver && entry.model === current.model, ); + const candidate = candidates[rank]; + // A thread that fell back to a weaker model returns once a better one has room again. + const betterHasRoom = candidates + .slice(0, Math.max(rank, 0)) + .some((better) => + input.providers.some( + (entry) => + entry.driver === (better.driver as ProviderDriverKind) && + open(entry, better.model) && + hasRoom(entry), + ), + ); if ( provider && candidate && open(provider, candidate.model) && - peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT + hasRoom(provider) && + !betterHasRoom ) { return { selection: toSelection(provider, candidate, level), level, sticky: true }; } From 7f9ac37e29ef2110fbff64d75c6e51c81af7c93e Mon Sep 17 00:00:00 2001 From: radys-s Date: Sun, 15 Nov 2026 21:12:52 +0100 Subject: [PATCH 053/230] fix: Resume works on providers without native resume; limited threads move to Auto On the PC a thread stuck on Grok after Claude hit its limit: every Resume failed with "Native resume is unavailable" and the thread never moved on. - Resume on a provider without native resume starts an ordinary turn that asks the agent to continue, instead of failing. - A thread not on Auto that hits a usage limit fails over through Auto at the level its model implies. Delegated threads keep their model. --- .../AutoFailoverService.test.ts | 30 +++++++++++------- .../orchestration-v2/AutoFailoverService.ts | 20 +++++++++--- .../ProviderTurnStartService.test.ts | 22 +++++-------- .../ProviderTurnStartService.ts | 31 +++++++++---------- docs/progress.md | 8 +++++ 5 files changed, 65 insertions(+), 46 deletions(-) diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts index 078076aca8a2..f35ce55d2995 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts @@ -71,20 +71,28 @@ describe("autoFailoverPlan", () => { expect(result?.cooldownUntilMs).toBe(now + 5 * 60_000); }); - it("leaves other failures, non-Auto threads and stale runs alone", () => { + it("moves a hand-picked thread to Auto at the level its model implies", () => { + const picked = (model: string) => + shell({ modelSelection: { instanceId: ProviderInstanceId.make("grok"), model } }); + expect(plan(picked("grok-4.7"))?.command.modelSelection).toEqual({ + instanceId: "grok", + model: "auto-medium", + }); + expect(plan(picked("claude-fable-5-2"))?.command.modelSelection?.model).toBe("auto-high"); + expect(plan(picked("claude-haiku-5-5"))?.command.modelSelection?.model).toBe("auto-low"); + // A delegated thread keeps the model its parent chose. + const delegated = { + rootThreadId: ThreadId.make("t0"), + parentThreadId: ThreadId.make("t0"), + relationshipToParent: "subagent", + }; + expect(plan(shell({ ...picked("grok-4.7"), lineage: delegated }))).toBeNull(); + }); + + it("leaves other failures and stale runs alone", () => { expect( plan(shell({ lastErrorClass: "provider_error", lastErrorCode: "api_error_404" })), ).toBeNull(); - expect( - plan( - shell({ - modelSelection: { - instanceId: ProviderInstanceId.make("claudeAgent"), - model: "claude-opus-5-5", - }, - }), - ), - ).toBeNull(); expect(plan(shell({ latestRunId: RunId.make("run:newer") }))).toBeNull(); expect(plan(shell({ status: "idle" }))).toBeNull(); expect(plan(shell({ settledOverride: "settled" }))).toBeNull(); diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.ts b/apps/server/src/orchestration-v2/AutoFailoverService.ts index b91420a90553..0b491a57b9c2 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.ts @@ -1,5 +1,6 @@ import { CommandId, + isDelegatedAppThread, isProviderNativeSubagentThread, MessageId, type OrchestrationV2ThreadShell, @@ -51,8 +52,8 @@ export interface AutoFailoverPlan { /** * What to do when a run on an Auto thread fails: bench the instance that failed and send the * thread back through Auto, which then picks the next subscription in the chain. Null when the - * run did not fail for lack of room, or the thread is not on Auto, or is no longer the - * thread's latest run. + * run did not fail for lack of room, or the thread is a delegated one not on Auto, or the run is + * no longer the thread's latest. */ export function autoFailoverPlan(input: { readonly shell: OrchestrationV2ThreadShell; @@ -71,8 +72,12 @@ export function autoFailoverPlan(input: { isProviderNativeSubagentThread(shell) ) return null; - const level = routedAutoLevel(shell.modelSelection); - if (level === undefined) return null; + // A thread not on Auto (an older thread, or one where a model was picked by hand) moves to + // Auto at the level its model implies: a limit there means the picked model is out anyway. + // Delegated threads keep the model their parent chose; their parent sees the failure. + const routed = routedAutoLevel(shell.modelSelection); + if (routed === undefined && isDelegatedAppThread(shell)) return null; + const level = routed ?? impliedAutoLevel(shell.modelSelection.model); const limited = shell.lastErrorClass === "usage_limit"; const noCapacity = !limited && CAPACITY_CODES.has(shell.lastErrorCode ?? ""); if (!limited && !noCapacity) return null; @@ -102,6 +107,13 @@ export function autoFailoverPlan(input: { }; } +/** The Auto level whose orchestrator is closest to a hand-picked model. */ +function impliedAutoLevel(model: string): "low" | "medium" | "high" { + if (/fable|gpt-6\.1-sol|astra/i.test(model)) return "high"; + if (/sonnet|haiku|flash|opencode\/|luna/i.test(model)) return "low"; + return "medium"; +} + /** Keeps the timestamps of recent failovers under the hourly cap; true when one more fits. */ export function admitFailover(history: Array, nowMs: number): boolean { const recent = history.filter((at) => nowMs - at < 60 * 60_000); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index d12e6fd1e8bd..5ca2309ed429 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -2173,7 +2173,9 @@ effectIt.effect("sends new steering text when restarting a manual continuation", }), ); -effectIt.effect("refuses unsupported resume instead of manufacturing a user prompt", () => +// Fork: upstream failed here with "Native resume is unavailable", which left Grok, OpenCode and +// Antigravity threads stuck on Resume. The fork starts an ordinary turn that asks to continue. +effectIt.effect("asks to continue when the provider cannot resume natively", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "", @@ -2182,20 +2184,10 @@ effectIt.effect("refuses unsupported resume instead of manufacturing a user prom sideChat: { contextRun: "delivered" }, }); yield* harness.start; - expect(harness.startTurn).not.toHaveBeenCalled(); - expect(harness.startRootRun).not.toHaveBeenCalled(); - expect(harness.settledRuns).toEqual(["failed"]); - expect(harness.projection().turnItems).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - type: "error", - failure: expect.objectContaining({ - message: - "This provider cannot resume without a new message. Send a message to continue.", - }), - }), - ]), - ); + expect(harness.startTurn.mock.calls.map(([turn]) => turn.message.text)).toEqual([ + "Continue where you left off.", + ]); + expect(harness.settledRuns).not.toContain("failed"); }), ); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 28f8f474cd6a..178bbbc34b3b 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -99,6 +99,9 @@ const isProviderAdapterOpenSessionError = Schema.is( ProviderAdapter.ProviderAdapterOpenSessionError, ); +/** Sent in place of a native resume the provider does not support. */ +const MANUAL_RESUME_CONTINUE_TEXT = "Continue where you left off."; + /** * Claude refuses these before it reads the prompt: replacing a process running background work, * launch arguments whose appended system prompt or settings cannot be read, or MCP registration @@ -893,10 +896,17 @@ export const layer: Layer.Layer< }); let effectiveHandoffs = handoffs; let resumeFellBack = false; - const userText = projectComposerContextForProvider({ - text: providerMessage.text, - records: providerMessage.context?.records ?? [], - }); + // Fork: Resume on a provider with no native resume (Grok, OpenCode, Antigravity, or a run + // that moved to another provider) used to fail with "Native resume is unavailable". It now + // starts an ordinary turn that asks the agent to continue. + const continueInstead = + manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined; + const userText = continueInstead + ? MANUAL_RESUME_CONTINUE_TEXT + : projectComposerContextForProvider({ + text: providerMessage.text, + records: providerMessage.context?.records ?? [], + }); // Native goal commands go verbatim; handoff history waits a turn. const goalDriver = session.driver === "codex" || @@ -1634,17 +1644,6 @@ export const layer: Layer.Layer< legacyInputRunIds, budget, } = handoffContext; - if (manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined) { - yield* settleStartFailure({ - signal: "resume-unsupported", - title: "Native resume is unavailable", - error: new ProviderAdapter.ProviderResumeUnsupportedError({ - driver: session.driver, - providerThreadId: providerThread.id, - }), - }); - return; - } const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, @@ -1962,7 +1961,7 @@ export const layer: Layer.Layer< .filter((turn) => turn.providerThreadId === providerThread.id) .map((turn) => turn.ordinal), ) + 1, - resume: manualResume && unsentResumeMessage === undefined, + resume: manualResume && unsentResumeMessage === undefined && !continueInstead, nativeThreadHasTurns: nativeInputRunIds.size > 0 || (legacyInputRunIds.size > 0 && diff --git a/docs/progress.md b/docs/progress.md index 3b15d3cdc7c9..069401bf3429 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -91,3 +91,11 @@ - Numbers: autoModel 14/14, AutoFailoverService 7/7, server typecheck 0 errors. - Cost: moving back up is one more provider handoff (a thread summary). It happens once per reset, on the next message. - Next: build the PC desktop app from `tomas/pc-nightly` and install it. + +## 2026-11-15: Resume works on every provider; limited hand-picked threads move to Auto + +- What happened (PC, thread "Port Hub T3 App Improvements to PC"): Claude hit its 5-hour limit. The thread was not on Auto (it started on the Auto instance before Auto existed, with a plain Opus model), so no failover ran. The composer was switched to Grok and Resume pressed. Grok has no native resume, so each Resume failed at once with "Native resume is unavailable". The one "continue" that reached Grok ran a few tool calls, then hit Grok's free limit, which T3 cannot see in usage windows. Every later "continue" went to Grok again and failed. Result: about ten turns with no answer. +- Fix 1 (`ProviderTurnStartService`): Resume on a provider without native resume now starts an ordinary turn with "Continue where you left off." (plus the handoff context when the provider changed) instead of failing. Upstream's test "refuses unsupported resume" was rewritten to the new behavior. +- Fix 2 (`AutoFailoverService`): a thread not on Auto that hits a usage limit now fails over through Auto at the level its model implies (Fable/Sol/Astra high; Sonnet/Haiku/Flash/OpenCode/Luna low; else medium). Delegated threads not on Auto are left alone: their parent chose the model. +- Setup repo: `fallbackModelSelection` (Grok) is cleared by `apply-auto-settings.py`; the health check warns while it is set. +- Numbers: AutoFailoverService 8/8; ProviderTurnStartService 65/69, the same 4 failures as before the change (Windows-only git/startup tests); server typecheck 0 errors. From 3450759f69330afbb121b1d28408602e096cbd2e Mon Sep 17 00:00:00 2001 From: radys-s Date: Mon, 16 Nov 2026 08:32:10 +0100 Subject: [PATCH 054/230] fix: let a thread switch providers after a failed failover turn MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When Auto failover moved a thread to Grok and Grok hit its limit on the first turn, the thread kept Grok as its selection with no provider thread for that instance. The client only allowed a handoff from a provider thread matching the current selection, so the picker locked every other provider ("Claude is unavailable in this thread"). The server hands off from the app's own run history, so any provider thread of this app thread is enough. The empty case stays locked as before. Origin: Tomáš's screenshot in thread 'Agent Skills and Design Guide Overhaul' (2026-11-16). --- .../src/state/threadWorkflows.test.ts | 16 +++++++++++++++- .../client-runtime/src/state/threadWorkflows.ts | 12 ++++-------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts index 3fe571e84b5b..cace83a3ab3b 100644 --- a/packages/client-runtime/src/state/threadWorkflows.test.ts +++ b/packages/client-runtime/src/state/threadWorkflows.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vite-plus/test"; -import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import { ProviderInstanceId, type OrchestrationV2ThreadProjection } from "@t3tools/contracts"; import { canForkProjectedAssistantItem, @@ -64,6 +64,20 @@ describe("thread workflows", () => { }), ).toBe(true); expect(threadSupportsProviderHandoff({ ...projection, providerThreads: [] })).toBe(false); + // Failover moved the selection to Grok, whose first turn failed on its limit. + expect( + threadSupportsProviderHandoff({ + ...projection, + thread: { + ...projection.thread, + modelSelection: { + instanceId: ProviderInstanceId.make("grok"), + model: "grok-4.7", + }, + }, + runs: [{ ...projection.runs[0]!, status: "failed" }], + }), + ).toBe(true); }); it("sorts queued messages and gates promotion from capabilities", () => { diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts index ef39233707a7..5b9a7edc84b9 100644 --- a/packages/client-runtime/src/state/threadWorkflows.ts +++ b/packages/client-runtime/src/state/threadWorkflows.ts @@ -112,14 +112,10 @@ export function threadSupportsProviderHandoff(projection: Projection | null | un if (projection.thread.historyOrigin === "v1_import" || projection.runs.length === 0) return true; // Detaching a stopped session removes it from the projection. The server still - // hands off from saved app history, which needs the source provider thread but - // not its native ref. - return projection.providerThreads.some( - (thread) => - thread.id === projection.thread.activeProviderThreadId && - thread.appThreadId === projection.thread.id && - thread.providerInstanceId === projection.thread.modelSelection.instanceId, - ); + // hands off from saved app history. A switch whose first turn failed (a limit hit + // right away) leaves the selection on an instance with no matching provider + // thread; any provider thread of this app thread is enough to hand off from. + return projection.providerThreads.some((thread) => thread.appThreadId === projection.thread.id); } export function getUserQueuedThreadRuns( From 9342acccd8c180ac3b641cef6c34eaae7f053f60 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Wed, 18 Nov 2026 12:29:22 +0100 Subject: [PATCH 055/230] chore(i18n): add the fork's Usage copy to the web catalogs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Upstream now translates the whole app and CI fails when a committed catalog drifts from the source. The fork's pooled usage view, reset advice and subscriptions list now wrap their copy in and gt(), so `vp run i18n:generate` adds those keys (English in every locale until translated) and drops "left", which the fork's pooled card replaced. Origin: Tomáš's request to bring the fork up to current upstream. --- apps/web/src/i18n/translations/de.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/en.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/es.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/fr.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/ja.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/ko.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/pt-BR.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/ru.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/sv.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/zh.json | 18 +++++++++++++++++- 10 files changed, 170 insertions(+), 10 deletions(-) diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 4c9f0f6d27e4..8598d571e161 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -11814,8 +11814,20 @@ "1b16346722b65812": "{timeLeft} % des Zeitfensters übrig", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "0-$-Limit", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "Nutzung verwalten", - "a00e74aaa421c524": "übrig", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "Kein Anbieter in den ausgewählten Umgebungen meldet Abo-Limits.", "87f5d0c61b335f38": "Nutzung in ChatGPT mit deinem verbundenen Konto ansehen.", "5b4c71b36b979e80": "Kosten", @@ -11906,6 +11918,10 @@ "b11af3f3da3d494e": "Die Summen sind unvollständig, während ausgewählte Umgebungen scannen.", "8062808b87ce6032": "Modellpreise", "cf5409d12fc3f53b": "Alle Anbieter", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "Preise nicht geladen", "ed447281261f2d0e": "Nur Lesezugriff", "67633defded66bf7": "Gib eine Modell-ID ein.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index c40470b46e6a..10dd304a2117 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -11822,8 +11822,20 @@ "1b16346722b65812": "{timeLeft}% of the window left", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "$0 cap", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "Manage usage", - "a00e74aaa421c524": "left", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "No provider on the selected environments reports subscription limits.", "87f5d0c61b335f38": "View usage in ChatGPT with your connected account.", "5b4c71b36b979e80": "Cost", @@ -11914,6 +11926,10 @@ "b11af3f3da3d494e": "Totals are partial while selected environments scan.", "8062808b87ce6032": "Model prices", "cf5409d12fc3f53b": "All providers", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "Prices not loaded", "ed447281261f2d0e": "Read-only access", "67633defded66bf7": "Enter a model ID.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 68f63f589f51..9e17eac95ce9 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -11807,8 +11807,20 @@ "1b16346722b65812": "Queda un {timeLeft}% de la ventana", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Límite de 0 $", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "Gestionar uso", - "a00e74aaa421c524": "restante", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "Ningún proveedor de los entornos seleccionados informa de límites de suscripción.", "87f5d0c61b335f38": "Consulta el uso en ChatGPT con tu cuenta conectada.", "5b4c71b36b979e80": "Coste", @@ -11899,6 +11911,10 @@ "b11af3f3da3d494e": "Los totales son parciales mientras se escanean los entornos seleccionados.", "8062808b87ce6032": "Precios de modelos", "cf5409d12fc3f53b": "Todos los proveedores", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "No se cargaron los precios", "ed447281261f2d0e": "Acceso de solo lectura", "67633defded66bf7": "Introduce un ID de modelo.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 442c22ed3a2d..ba113b7144d3 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -11812,8 +11812,20 @@ "1b16346722b65812": "{timeLeft} % de la fenêtre restant", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Plafond de 0 $", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "Gérer l’utilisation", - "a00e74aaa421c524": "restant", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "Aucun fournisseur des environnements sélectionnés ne signale de limites d’abonnement.", "87f5d0c61b335f38": "Consultez l’utilisation dans ChatGPT avec votre compte connecté.", "5b4c71b36b979e80": "Coût", @@ -11904,6 +11916,10 @@ "b11af3f3da3d494e": "Les totaux sont partiels pendant l’analyse des environnements sélectionnés.", "8062808b87ce6032": "Prix des modèles", "cf5409d12fc3f53b": "Tous les fournisseurs", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "Prix non chargés", "ed447281261f2d0e": "Accès en lecture seule", "67633defded66bf7": "Saisissez un ID de modèle.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index c9417551b208..ce57232d7388 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -11762,8 +11762,20 @@ "1b16346722b65812": "期間の残り {timeLeft}%", "7aaaff1c6484f25c": "セグメント", "8bcab2ef61de6518": "上限 $0", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "使用量を管理", - "a00e74aaa421c524": "残り", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "選択した環境には、サブスクリプションの上限を報告するプロバイダーがありません。", "87f5d0c61b335f38": "接続したアカウントで ChatGPT の使用量を表示します。", "5b4c71b36b979e80": "コスト", @@ -11854,6 +11866,10 @@ "b11af3f3da3d494e": "選択した環境のスキャン中は、合計は一部のみです。", "8062808b87ce6032": "モデルの価格", "cf5409d12fc3f53b": "すべてのプロバイダー", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "価格が読み込まれていません", "ed447281261f2d0e": "読み取り専用アクセス", "67633defded66bf7": "モデル ID を入力してください。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 362d29d071a8..12e42a37bc8e 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -11759,8 +11759,20 @@ "1b16346722b65812": "기간 {timeLeft}% 남음", "7aaaff1c6484f25c": "구간", "8bcab2ef61de6518": "$0 한도", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "사용량 관리", - "a00e74aaa421c524": "남음", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "선택한 환경에 구독 한도를 보고하는 제공자가 없습니다.", "87f5d0c61b335f38": "연결된 계정으로 ChatGPT에서 사용량을 확인하세요.", "5b4c71b36b979e80": "비용", @@ -11851,6 +11863,10 @@ "b11af3f3da3d494e": "선택한 환경을 스캔하는 동안에는 합계가 일부만 표시됩니다.", "8062808b87ce6032": "모델 가격", "cf5409d12fc3f53b": "모든 제공자", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "가격을 불러오지 않음", "ed447281261f2d0e": "읽기 전용 액세스", "67633defded66bf7": "모델 ID를 입력하세요.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index b598943e9238..30df2e8c5a9b 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -11811,8 +11811,20 @@ "1b16346722b65812": "{timeLeft}% da janela restante", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Limite de $0", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "Gerenciar uso", - "a00e74aaa421c524": "restante", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "Nenhum provedor nos ambientes selecionados informa limites de assinatura.", "87f5d0c61b335f38": "Veja o uso no ChatGPT com sua conta conectada.", "5b4c71b36b979e80": "Custo", @@ -11903,6 +11915,10 @@ "b11af3f3da3d494e": "Os totais são parciais enquanto os ambientes selecionados são verificados.", "8062808b87ce6032": "Preços dos modelos", "cf5409d12fc3f53b": "Todos os provedores", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "Preços não carregados", "ed447281261f2d0e": "Acesso somente leitura", "67633defded66bf7": "Informe o ID de um modelo.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index a8a54a6500e5..cfbe32a1511b 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -11812,8 +11812,20 @@ "1b16346722b65812": "От окна осталось {timeLeft}%", "7aaaff1c6484f25c": "Сегмент", "8bcab2ef61de6518": "Лимит $0", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "Управление использованием", - "a00e74aaa421c524": "осталось", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "Ни один провайдер в выбранных окружениях не сообщает лимиты подписки.", "87f5d0c61b335f38": "Смотрите использование в ChatGPT через подключённый аккаунт.", "5b4c71b36b979e80": "Стоимость", @@ -11904,6 +11916,10 @@ "b11af3f3da3d494e": "Итоги неполные, пока выбранные окружения сканируются.", "8062808b87ce6032": "Цены моделей", "cf5409d12fc3f53b": "Все провайдеры", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "Цены не загружены", "ed447281261f2d0e": "Доступ только для чтения", "67633defded66bf7": "Введите ID модели.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index adaf8566b641..4c71ced88d4d 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -11820,8 +11820,20 @@ "1b16346722b65812": "{timeLeft} % av fönstret kvar", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Tak på 0 $", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "Hantera användning", - "a00e74aaa421c524": "kvar", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "Ingen leverantör i de valda miljöerna rapporterar abonnemangsgränser.", "87f5d0c61b335f38": "Visa användning i ChatGPT med ditt anslutna konto.", "5b4c71b36b979e80": "Kostnad", @@ -11912,6 +11924,10 @@ "b11af3f3da3d494e": "Summorna är ofullständiga medan valda miljöer genomsöks.", "8062808b87ce6032": "Modellpriser", "cf5409d12fc3f53b": "Alla leverantörer", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "Priserna har inte lästs in", "ed447281261f2d0e": "Skrivskyddad åtkomst", "67633defded66bf7": "Ange ett modell-id.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index f386e717a061..a0fd8882e174 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -11837,8 +11837,20 @@ "1b16346722b65812": "窗口剩余 {timeLeft}%", "7aaaff1c6484f25c": "分段", "8bcab2ef61de6518": "上限 $0", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "管理用量", - "a00e74aaa421c524": "剩余", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "选中的环境上没有提供方报告订阅限制。", "87f5d0c61b335f38": "用已连接的账户在 ChatGPT 中查看用量。", "5b4c71b36b979e80": "费用", @@ -11929,6 +11941,10 @@ "b11af3f3da3d494e": "选中的环境仍在扫描,总计暂不完整。", "8062808b87ce6032": "模型价格", "cf5409d12fc3f53b": "所有提供方", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "价格未加载", "ed447281261f2d0e": "只读权限", "67633defded66bf7": "请输入模型 ID。", From b4586b2e53d8ff6d43adfa2d98457604d4f7754a Mon Sep 17 00:00:00 2001 From: radys-s Date: Wed, 18 Nov 2026 12:39:59 +0100 Subject: [PATCH 056/230] feat(auto): run Auto High on Opus at Extra High effort Auto High started with Fable 5.2, which these Claude accounts cannot use, so it always fell through to Opus at plain High. Opus at the xhigh effort level now leads the high chain, Fable is out of it, and the failover heuristic no longer reads Fable as a high model. Requested by Tomas: Auto High should mean Opus at a bigger effort level until Fable is available. --- .../src/orchestration-v2/AutoFailoverService.test.ts | 2 +- apps/server/src/orchestration-v2/AutoFailoverService.ts | 2 +- docs/progress.md | 7 +++++++ packages/shared/src/autoModel.test.ts | 8 ++++---- packages/shared/src/autoModel.ts | 3 +-- 5 files changed, 14 insertions(+), 8 deletions(-) diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts index f35ce55d2995..21bee86e34e8 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts @@ -78,7 +78,7 @@ describe("autoFailoverPlan", () => { instanceId: "grok", model: "auto-medium", }); - expect(plan(picked("claude-fable-5-2"))?.command.modelSelection?.model).toBe("auto-high"); + expect(plan(picked("gpt-6.1-sol"))?.command.modelSelection?.model).toBe("auto-high"); expect(plan(picked("claude-haiku-5-5"))?.command.modelSelection?.model).toBe("auto-low"); // A delegated thread keeps the model its parent chose. const delegated = { diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.ts b/apps/server/src/orchestration-v2/AutoFailoverService.ts index 0b491a57b9c2..51531943ae2f 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.ts @@ -109,7 +109,7 @@ export function autoFailoverPlan(input: { /** The Auto level whose orchestrator is closest to a hand-picked model. */ function impliedAutoLevel(model: string): "low" | "medium" | "high" { - if (/fable|gpt-6\.1-sol|astra/i.test(model)) return "high"; + if (/gpt-6\.1-sol|astra/i.test(model)) return "high"; if (/sonnet|haiku|flash|opencode\/|luna/i.test(model)) return "low"; return "medium"; } diff --git a/docs/progress.md b/docs/progress.md index 069401bf3429..895f7db50d02 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -99,3 +99,10 @@ - Fix 2 (`AutoFailoverService`): a thread not on Auto that hits a usage limit now fails over through Auto at the level its model implies (Fable/Sol/Astra high; Sonnet/Haiku/Flash/OpenCode/Luna low; else medium). Delegated threads not on Auto are left alone: their parent chose the model. - Setup repo: `fallbackModelSelection` (Grok) is cleared by `apply-auto-settings.py`; the health check warns while it is set. - Numbers: AutoFailoverService 8/8; ProviderTurnStartService 65/69, the same 4 failures as before the change (Windows-only git/startup tests); server typecheck 0 errors. + +## 2026-11-18: Auto High runs Opus 5.5 at Extra High, not Fable + +- What: `AUTO_CANDIDATES.high` now starts with `claude-opus-5-5` at the `xhigh` effort level ("Extra High", one step above High), and Fable 5.2 is gone from the high chain. The Antigravity Opus, Codex Sol/Astra/Luna, Grok and Gemini fallbacks keep their `high` effort. `impliedAutoLevel` (the failover path for hand-picked threads) no longer reads Fable as a high model, since Fable now only sits in the medium chain. +- Why: Tomáš's Claude accounts have no Fable access yet, so Auto High routed to a model that was never usable there and fell through to Opus at plain High. He asked for Auto High to mean Opus at a higher effort. +- Numbers: autoModel 14/14, AutoFailoverService 8/8, claudeModelOptions 7/7. Effort levels the catalog offers for Opus 5.5: low, medium, high, xhigh, max, ultracode, ultrathink; `max` is one step above `xhigh` if he wants the ceiling. +- Next: ship on the PC fork build, then hub and hub2. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index d179263a94a5..3eea2812219c 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -23,7 +23,7 @@ const effortCapabilities = { id: "effort", label: "Effort", type: "select" as const, - options: ["low", "medium", "high"].map((id) => ({ id, label: id })), + options: ["low", "medium", "high", "xhigh"].map((id) => ({ id, label: id })), }, ], }; @@ -82,9 +82,9 @@ describe("resolveAutoModelSelection", () => { resolveAutoModelSelection({ selection: auto("high"), providers, now })?.selection, ).toEqual({ instanceId: "claudeAuto", - model: "claude-fable-5-2", + model: "claude-opus-5-5", options: [ - { id: "effort", value: "high" }, + { id: "effort", value: "xhigh" }, { id: "auto", value: "high" }, ], }); @@ -283,7 +283,7 @@ describe("resolveAutoModelSelection", () => { providers, now, })?.selection.model; - expect(pick("auto-high")).toBe("claude-fable-5-2"); + expect(pick("auto-high")).toBe("claude-opus-5-5"); expect(pick("auto-medium")).toBe("claude-opus-5-5"); expect(pick("auto-low")).toBe("claude-sonnet-5-5"); expect(isAutoModelSlug("auto-low")).toBe(true); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 2ee6fa04460e..2d31d95c4739 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -59,8 +59,7 @@ const opencode = (model: string, effort: string): AutoCandidate => ({ */ const AUTO_CANDIDATES: Readonly>> = { high: [ - claude("claude-fable-5-2", "high"), - claude("claude-opus-5-5", "high"), + claude("claude-opus-5-5", "xhigh"), antigravity("claude-opus-4-6-thinking", "high"), codex("gpt-6.1-sol", "high"), codex("gpt-6-astra", "high"), From 23d4ab8829c8e28769b5f45902e38e4a7609799a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Wed, 18 Nov 2026 12:47:16 +0100 Subject: [PATCH 057/230] docs: log the sync onto upstream 373ec12be6 in progress.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Records how the fork was replayed onto upstream main, which conflicts came up and how they were resolved, and how it was verified. Origin: Tomáš's request to bring the fork up to current upstream. --- docs/progress.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/progress.md b/docs/progress.md index 069401bf3429..d81fcd98b34e 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -99,3 +99,13 @@ - Fix 2 (`AutoFailoverService`): a thread not on Auto that hits a usage limit now fails over through Auto at the level its model implies (Fable/Sol/Astra high; Sonnet/Haiku/Flash/OpenCode/Luna low; else medium). Delegated threads not on Auto are left alone: their parent chose the model. - Setup repo: `fallbackModelSelection` (Grok) is cleared by `apply-auto-settings.py`; the health check warns while it is set. - Numbers: AutoFailoverService 8/8; ProviderTurnStartService 65/69, the same 4 failures as before the change (Windows-only git/startup tests); server typecheck 0 errors. + +## 2026-11-18: Fork synced onto upstream `373ec12be6` + +- What: the 18 fork commits from `1f698f01d9..bd33ae897c` were rebased onto upstream main `373ec12be6` (300 upstream commits newer). `origin/main` is recorded as an ancestor with an `-s ours` merge, as in the previous sync, so the PR merges without a force-push. +- Why: the fork was 300 commits behind upstream two days after the last sync. +- Conflicts: 3 sites in 2 files, all from upstream translating the whole app (#37893): `ProviderModelPicker.tsx` (fork's Auto trigger label vs upstream's `gt()` labels) and `UsageLimitsPooled.tsx` (imports moved to `usageLimitsCopy.ts`). Kept upstream's translated strings and the fork's Auto and pooled-view behavior. +- Adapted to upstream: reset advice (`suggestResetCredit`) moved from `usageLimits.ts` to `usageLimitsCopy.ts`, where upstream now keeps `formatDuration` and other client copy. The fork's pooled view, chart, reset advice and Subscriptions heading wrap their copy in ``/`gt()` (upstream's `no-untranslated-copy` lint), and the web catalogs gained those 17 keys. +- Numbers: `vp run check:changed` all pass (typecheck 42 packages, 492 tests in 25 files, lint, knip, format, react compiler); `vp run i18n:check` pass; `UsageLimitsPooled.browser.test.tsx` 2/2. +- Real run (worktree `.t3`, seeded copy, never `~/.t3/userdata`): Auto High/Medium/Low pinned at the top of Favorites with their routes, Usage → Limits pooled view and reset advice render, one Claude Haiku turn answered. Production build (`apps/web vp run build`, `apps/server node scripts/cli.ts build`) boots on an empty data dir. +- Next: Tomáš switches hub2 and hub to the new build. From 3af9cc78d902716ef2d6d2e2781143a62a8f178b Mon Sep 17 00:00:00 2001 From: radys-s Date: Wed, 18 Nov 2026 18:40:43 +0100 Subject: [PATCH 058/230] feat(auto): run Auto High on Opus at max effort MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tomáš asked for the highest available effort after Auto High was set to Extra High; \max\ is one step above \xhigh\ for Opus 5.5. The routing test now pins \max\ for the high level. --- packages/shared/src/autoModel.test.ts | 4 ++-- packages/shared/src/autoModel.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index 3eea2812219c..ff03d6791dc9 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -23,7 +23,7 @@ const effortCapabilities = { id: "effort", label: "Effort", type: "select" as const, - options: ["low", "medium", "high", "xhigh"].map((id) => ({ id, label: id })), + options: ["low", "medium", "high", "xhigh", "max"].map((id) => ({ id, label: id })), }, ], }; @@ -84,7 +84,7 @@ describe("resolveAutoModelSelection", () => { instanceId: "claudeAuto", model: "claude-opus-5-5", options: [ - { id: "effort", value: "xhigh" }, + { id: "effort", value: "max" }, { id: "auto", value: "high" }, ], }); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 2d31d95c4739..b88b26456a67 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -59,7 +59,7 @@ const opencode = (model: string, effort: string): AutoCandidate => ({ */ const AUTO_CANDIDATES: Readonly>> = { high: [ - claude("claude-opus-5-5", "xhigh"), + claude("claude-opus-5-5", "max"), antigravity("claude-opus-4-6-thinking", "high"), codex("gpt-6.1-sol", "high"), codex("gpt-6-astra", "high"), From bbfbc8627d4a88eb509f51966d96d82858e94d82 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Wed, 18 Nov 2026 19:07:48 +0100 Subject: [PATCH 059/230] fix(server): tell Auto-routed Claude turns their level MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since Auto High runs Opus 5.5 at Extra High (#10), the Auto orchestrator prompt (auto-mode.md), which derives the routing level from the model name, made every Auto High thread route itself as medium. The model had no way to see the level Auto picked. A Claude turn whose selection carries Auto's `auto` stamp now ends its system prompt with `Auto level: `. Hand-picked models are unchanged. The level is part of the compiled selection and its identity, and a level change cannot be applied live, so switching Auto Medium to Auto High on the same model reopens the process with resume instead of keeping a stale line. Requested by Tomáš: Auto High threads routed as medium. --- apps/server/src/claudeModelOptions.ts | 6 ++ .../Adapters/ClaudeAdapterV2.test.ts | 68 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 11 ++- docs/progress.md | 9 +++ 4 files changed, 92 insertions(+), 2 deletions(-) diff --git a/apps/server/src/claudeModelOptions.ts b/apps/server/src/claudeModelOptions.ts index c3376ef7ed8d..dc1a073e6347 100644 --- a/apps/server/src/claudeModelOptions.ts +++ b/apps/server/src/claudeModelOptions.ts @@ -5,6 +5,7 @@ import { getProviderOptionDescriptors, resolvePromptInjectedEffort, } from "@t3tools/shared/model"; +import { routedAutoLevel } from "@t3tools/shared/autoModel"; import { BUNDLED_CLAUDE_MODEL_CATALOG, @@ -26,6 +27,8 @@ export interface CompiledClaudeModelSelection { readonly settings: Readonly>; /** The alias of a custom model named like one, which Claude Code would otherwise expand. */ readonly pinnedAlias: string | undefined; + /** The level Auto routed this selection at; undefined for a hand-picked model. */ + readonly autoLevel: string | undefined; readonly queryIdentity: string; } @@ -65,17 +68,20 @@ export function compileClaudeModelSelection( resolveClaudeModelSlug(catalog, selection.model) === apiModelId ? apiModelId : undefined; + const autoLevel = routedAutoLevel(selection); return { apiModelId, effort, promptEffort, settings, pinnedAlias, + autoLevel, queryIdentity: JSON.stringify({ apiModelId, effort: effort ?? null, settings, pinnedAlias: pinnedAlias ?? null, + autoLevel: autoLevel ?? null, }), }; } diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index a0e186c4f7d4..3376223732cd 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -7605,6 +7605,74 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect( + "tells an Auto-routed turn its level and reopens the process when the level changes", + () => + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions({ freshQueueOnReopen: true }); + const now = yield* DateTime.now; + const opus = { + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + model: "claude-opus-5-5", + } satisfies ModelSelection; + const routed = (level: string, effort: string) => + ({ + ...opus, + options: [ + { id: "effort", value: effort }, + { id: "auto", value: level }, + ], + }) satisfies ModelSelection; + const appendText = () => + (harness.getOpenedOptions()?.systemPrompt as { readonly append?: string } | undefined) + ?.append ?? ""; + const runTurn = Effect.fnUntraced(function* (ordinal: number, selection: ModelSelection) { + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(`attempt-auto-level:${ordinal}`), + text: `Request ${ordinal}`, + attachments: [], + providerTurnOrdinal: ordinal, + modelSelection: selection, + }), + ); + yield* harness.offerAndWait(turnOneResult); + yield* Queue.take(harness.terminalReceipts); + return harness.getOpenedOptions(); + }); + + const handPicked = yield* runTurn(1, { + ...opus, + options: [{ id: "effort", value: "medium" }], + }); + assert.notInclude(appendText(), "Auto level:"); + + const medium = yield* runTurn(2, routed("medium", "medium")); + assert.notStrictEqual(medium, handPicked); + assert.isTrue(appendText().endsWith("\n\nAuto level: medium")); + + // Only the effort differs between these levels, which would otherwise change live. + const high = yield* runTurn(3, routed("high", "xhigh")); + assert.notStrictEqual(high, medium); + assert.isTrue(appendText().endsWith("\n\nAuto level: high")); + assert.deepEqual(harness.liveSelectionChanges, []); + + assert.strictEqual(yield* runTurn(4, routed("high", "xhigh")), high); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #34549 a model change sent with a steer was shown but never applied to the turn. it.effect("applies a model change sent with a steer to the running turn", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 2974c1a81ab2..e1f4289274ff 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2061,7 +2061,10 @@ export const layerQueryRunner: Layer.Layer< type ClaudeFlagSettings = Parameters[0]; -/** Thinking requires a new process. Clearing effort also requires one to reload user settings instead of model defaults. */ +/** + * Thinking requires a new process. Clearing effort also requires one to reload user settings + * instead of model defaults. The Auto level is in the system prompt, which only a new process reads. + */ function canApplyClaudeSelectionLive( live: CompiledClaudeModelSelection, next: CompiledClaudeModelSelection, @@ -2069,7 +2072,8 @@ function canApplyClaudeSelectionLive( return ( live.settings.alwaysThinkingEnabled === next.settings.alwaysThinkingEnabled && (next.effort !== undefined || live.effort === undefined) && - live.pinnedAlias === next.pinnedAlias + live.pinnedAlias === next.pinnedAlias && + live.autoLevel === next.autoLevel ); } @@ -2341,6 +2345,9 @@ export function makeClaudeQueryOptions(input: { ? `\n${T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH}\n` : "")), ...launchAppendSystemPrompt, + ...(compiledSelection.autoLevel === undefined + ? [] + : [`Auto level: ${compiledSelection.autoLevel}`]), ].join("\n\n"), }, ...(deviceInstructions || input.onStop !== undefined diff --git a/docs/progress.md b/docs/progress.md index 070a636a2827..c3425129e2df 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -116,3 +116,12 @@ - Numbers: `vp run check:changed` all pass (typecheck 42 packages, 492 tests in 25 files, lint, knip, format, react compiler); `vp run i18n:check` pass; `UsageLimitsPooled.browser.test.tsx` 2/2. - Real run (worktree `.t3`, seeded copy, never `~/.t3/userdata`): Auto High/Medium/Low pinned at the top of Favorites with their routes, Usage → Limits pooled view and reset advice render, one Claude Haiku turn answered. Production build (`apps/web vp run build`, `apps/server node scripts/cli.ts build`) boots on an empty data dir. - Next: Tomáš switches hub2 and hub to the new build. + +## 2026-11-18: Auto-routed Claude turns see their level in the system prompt + +- What: when Auto routed a Claude turn, the system prompt ends with one line, `Auto level: `, taken from the `auto` option the router stamps on the selection. Hand-picked models get nothing new. The level is part of the compiled Claude selection, so a level change on a live session (say Auto Medium → Auto High, where only the effort moves on the same Opus 5.5) is no longer applied live: the next turn reopens the process with resume, as a thinking change already does. A level change while a background shell runs is refused the same way. +- Why: since #10, Auto High runs Opus 5.5 at Extra High. `~/.agents/auto-mode.md` told the orchestrator to read its level from its model name (Opus → medium), so every Auto High thread routed itself as medium and could not see the level Auto picked. +- Providers: Claude only. Only the Claude Auto instances (`claudeAuto`, `claudeAutoB`) carry `auto-mode.md`; Codex, Grok, OpenCode and Antigravity have no Auto orchestrator prompt to correct. +- Numbers: the new adapter test failed on base (live effort change, no reopen) and passes; ClaudeAdapterV2 + claudeModelOptions 475/475. Real run on the worktree's seeded `.t3`: one Auto Low thread over the CLI (Sonnet 5.5 at low, Auto's first Low candidate) quoted `Auto level: low` from its system prompt. +- `~/.agents`: `auto-mode.md` and the `auto` skill read the level from that line and fall back to the model name only without it. +- Next: deploy on hub2 and the PC; copy the `~/.agents` change into `radys-s/t3-setup-improvements` for hub. From 744c6c457981b133ee84dc110ce57f82ada9562c Mon Sep 17 00:00:00 2001 From: radys-s Date: Thu, 19 Nov 2026 09:57:42 +0100 Subject: [PATCH 060/230] ci: run fork CI on GitHub-hosted runners Upstream's CI asks for Blacksmith runners (blacksmith-*-ubuntu-2404, blacksmith-6vcpu-macos-27). The fork has no Blacksmith runners, so since the upstream sync every CI and Mobile Fingerprint Check job on this repo has sat in "queued" until GitHub cancels it, and no fork PR can go green. Each runs-on now keeps the Blacksmith label when the workflow runs in pingdotgg/t3code and falls back to ubuntu-24.04 (macos-latest for the native mobile lint) everywhere else. GitHub-hosted runners are free for this public repo. The task-cache token step already skips when the secret is missing, so nothing else needs the upstream infrastructure. After an upstream sync that touches these lines, re-apply with: sed -i -E "s#^(\s*)runs-on: (blacksmith-[0-9]+vcpu-ubuntu-2404)\s*\$#\1runs-on: \${{ github.repository == 'pingdotgg/t3code' \&\& '\2' || 'ubuntu-24.04' }}#" .github/workflows/ci.yml Origin: PR #12 stayed pending for 16 hours with every CI job queued. --- .github/workflows/ci.yml | 20 +++++++++---------- .../workflows/mobile-fingerprint-check.yml | 2 +- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 40c84a71ad84..d5b44721c7a0 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,7 +22,7 @@ jobs: # open: if the diff cannot be resolved, everything runs. changes: name: Changes - runs-on: blacksmith-2vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 5 outputs: typecheck: ${{ steps.detect.outputs.typecheck }} @@ -64,7 +64,7 @@ jobs: contents: read id-token: write name: Lint - runs-on: blacksmith-8vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 10 steps: - name: Checkout @@ -126,7 +126,7 @@ jobs: name: Build and Typecheck needs: changes if: ${{ !cancelled() && (needs.changes.outputs.build != 'false' || needs.changes.outputs.typecheck != 'false') }} - runs-on: blacksmith-8vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 10 steps: - name: Checkout @@ -281,7 +281,7 @@ jobs: name: Test needs: changes if: ${{ !cancelled() && needs.changes.outputs.test != 'false' }} - runs-on: blacksmith-8vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 10 steps: - name: Checkout @@ -371,7 +371,7 @@ jobs: name: Test Web ${{ matrix.shard }} needs: changes if: ${{ !cancelled() && needs.changes.outputs.test_web != 'false' }} - runs-on: blacksmith-8vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 10 strategy: fail-fast: false @@ -433,7 +433,7 @@ jobs: contents: read id-token: write name: Test Server ${{ matrix.shard }} - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-24.04' }} # Shards take 2-5 minutes. When the shared task cache throttles reads, each # failed fetch stalls vp for 15-90s, which pushed shards past 10 minutes. timeout-minutes: 20 @@ -563,7 +563,7 @@ jobs: name: Rust needs: changes if: ${{ !cancelled() && needs.changes.outputs.rust != 'false' }} - runs-on: blacksmith-4vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-4vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 10 steps: - name: Checkout @@ -597,7 +597,7 @@ jobs: name: Mobile Native Static Analysis needs: changes if: ${{ !cancelled() && needs.changes.outputs.mobile_native != 'false' }} - runs-on: blacksmith-6vcpu-macos-27 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-6vcpu-macos-27' || 'macos-latest' }} timeout-minutes: 10 steps: - name: Checkout @@ -630,7 +630,7 @@ jobs: name: Release Smoke needs: changes if: ${{ !cancelled() && needs.changes.outputs.release_smoke != 'false' }} - runs-on: blacksmith-8vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 15 steps: - name: Checkout @@ -670,7 +670,7 @@ jobs: mobile_native_static_analysis, release_smoke, ] - runs-on: blacksmith-2vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-2vcpu-ubuntu-2404' || 'ubuntu-24.04' }} timeout-minutes: 5 steps: - name: Require every job to pass diff --git a/.github/workflows/mobile-fingerprint-check.yml b/.github/workflows/mobile-fingerprint-check.yml index 11d2ee60e122..151e1ffa93b9 100644 --- a/.github/workflows/mobile-fingerprint-check.yml +++ b/.github/workflows/mobile-fingerprint-check.yml @@ -28,7 +28,7 @@ jobs: fingerprint: name: Native fingerprint diff if: github.event.action != 'edited' || github.event.changes.base - runs-on: blacksmith-8vcpu-ubuntu-2404 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} permissions: contents: read env: From 4403f316df197b2e473cfbfb348573793b80a5c5 Mon Sep 17 00:00:00 2001 From: radys-s Date: Thu, 19 Nov 2026 10:12:33 +0100 Subject: [PATCH 061/230] test(web): expect Auto High to name Opus in the route label Since "run Auto High on Opus at Extra High effort" the high chain starts with claude-opus-5-5, but autoRoute.test.ts still expected Fable 5.2 for the high level. That PR merged while fork CI was stuck in "queued", so the failure only surfaced on the first CI run on GitHub-hosted runners. High and medium now both name Opus, so the case also checks low (Sonnet) to keep covering that the level changes the routed model. Origin: failing "Test Web 1" job on PR #14. --- apps/web/src/components/chat/autoRoute.test.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/apps/web/src/components/chat/autoRoute.test.ts b/apps/web/src/components/chat/autoRoute.test.ts index 85ae44be3be8..9258af398e31 100644 --- a/apps/web/src/components/chat/autoRoute.test.ts +++ b/apps/web/src/components/chat/autoRoute.test.ts @@ -58,7 +58,10 @@ describe("describeAutoRoute", () => { expect(medium?.label).toMatch(/^.*Opus 5\.5 \(B\)$/); const high = describeAutoRoute({ entries, options: [{ id: "effort", value: "high" }], now }); - expect(high?.label).toMatch(/Fable 5\.2 \(B\)$/); + expect(high?.label).toMatch(/Opus 5\.5 \(B\)$/); + + const low = describeAutoRoute({ entries, options: [{ id: "effort", value: "low" }], now }); + expect(low?.label).toMatch(/Sonnet 5\.5 \(B\)$/); }); it("names another provider when both Claude accounts are used up", () => { From e0bda62424087607692461415285816b1aa9ba75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 10:13:01 +0100 Subject: [PATCH 062/230] fix(shared): a Claude one-model weekly limit blocks only that model MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude reports a weekly allowance for one model as a `seven_day_` window (claudeUsageLimits.ts) without `modelIds`, so exhaustedUsageWindow treated a spent Fable-only allowance as exhausting every model on that account. The server's hub pool check (`windowLimitsModel`) already reads these windows per model. The per-window rule moves into `usageWindowLimitsModel`, which exhaustedUsageWindow now uses and Auto's weekly pace will reuse, so both decide the same way which windows limit a model. The other drivers' rules are unchanged. Origin: weekly-first Auto routing (Tomáš, 2026-11-19), which needs model-scoped weekly windows to count only for their own model. --- packages/shared/src/usageLimits.test.ts | 2 + packages/shared/src/usageLimits.ts | 91 ++++++++++++++----------- 2 files changed, 54 insertions(+), 39 deletions(-) diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index bd616cf5865d..cd47f96a8bcd 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -126,6 +126,8 @@ describe("new thread model fallback", () => { ).toBeDefined(); }); it.each([ + ["claudeAgent", ["seven_day_fable"], "claude-opus-5-5", false, undefined, undefined], + ["claudeAgent", ["seven_day_fable"], "claude-fable-5-2", true, undefined, undefined], ["cursor", ["autoPercentUsed"], "claude-opus-5-5", false, undefined, undefined], ["cursor", ["autoPercentUsed"], "composer-2.5", false, undefined, undefined], ["cursor", ["autoPercentUsed", "apiPercentUsed"], "composer-2.5", true, undefined, undefined], diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index c46c420a226e..2df18df8b4ad 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -23,56 +23,69 @@ import { isLocalLoopbackHost, isWildcardHost } from "./hostClassification.ts"; const MINUTE = 60_000; +/** Whether `window` limits `model`; a window for some models or one pool limits only those. */ +function usageWindowLimitsModel( + provider: ServerProvider, + window: ServerProviderUsageWindow, + model: string, +): boolean { + if (window.modelIds !== undefined && !window.modelIds.includes(model)) return false; + if (window.providerIds !== undefined && !window.providerIds.includes(model.split("/")[0] ?? "")) { + return false; + } + switch (provider.driver) { + case "claudeAgent": + // Claude names a one-model weekly allowance `seven_day_` (see claudeUsageLimits.ts). + return ( + !window.id.startsWith("seven_day_") || + model + .toLowerCase() + .replace(/[^a-z0-9]+/g, "_") + .includes(window.id.slice("seven_day_".length)) + ); + case "antigravity": { + const family = model.match(/^(gemini|claude|gpt)-/)?.[1]; + const pool = window.id.match(/^(gemini|claude|gpt|3p)-/)?.[1]; + return ( + pool === undefined || + family === undefined || + pool === family || + (pool === "3p" && (family === "claude" || family === "gpt")) + ); + } + case "codex": + // Seat-based plans spend credits only past their plan windows, so the credit cap blocks only plans without them. + return ( + window.id !== "individual" || + !(provider.usageLimits?.windows ?? []).some( + (entry) => entry.id === "primary" || entry.id === "secondary", + ) + ); + case "opencode": + return !window.id.startsWith("go_") || model.startsWith("opencode-go/"); + default: + return true; + } +} + export function exhaustedUsageWindow( provider: ServerProvider | undefined, now: number, model?: string, ) { - const windows = provider?.usageLimits?.windows ?? []; - const exhausted = windows.filter( + if (!provider) return undefined; + const exhausted = (provider.usageLimits?.windows ?? []).filter( (window) => (window.usedPercent ?? 0) >= 100 && - (model === undefined || window.modelIds === undefined || window.modelIds.includes(model)) && - (model === undefined || - window.providerIds === undefined || - window.providerIds.includes(model.split("/")[0] ?? "")) && + (model === undefined || usageWindowLimitsModel(provider, window, model)) && (!window.resetsAt || !Number.isFinite(Date.parse(window.resetsAt)) || Date.parse(window.resetsAt) > now), ); - if (model === undefined) return exhausted[0]; - switch (provider?.driver) { - case "cursor": { - const api = exhausted.find((window) => window.id === "apiPercentUsed"); - const auto = exhausted.find((window) => window.id === "autoPercentUsed"); - return /^(auto|default|grok|composer)/.test(model) ? auto && api : api; - } - case "antigravity": { - const family = model.match(/^(gemini|claude|gpt)-/)?.[1]; - return exhausted.find((window) => { - const pool = window.id.match(/^(gemini|claude|gpt|3p)-/)?.[1]; - return ( - pool === undefined || - family === undefined || - pool === family || - (pool === "3p" && (family === "claude" || family === "gpt")) - ); - }); - } - case "codex": { - // Seat-based plans spend credits only past their plan windows, so the credit cap blocks only plans without them. - const hasPlanWindows = windows.some( - (window) => window.id === "primary" || window.id === "secondary", - ); - return exhausted.find((window) => window.id !== "individual" || !hasPlanWindows); - } - case "opencode": - return exhausted.find( - (window) => !window.id.startsWith("go_") || model.startsWith("opencode-go/"), - ); - default: - return exhausted[0]; - } + if (model === undefined || provider.driver !== "cursor") return exhausted[0]; + const api = exhausted.find((window) => window.id === "apiPercentUsed"); + const auto = exhausted.find((window) => window.id === "autoPercentUsed"); + return /^(auto|default|grok|composer)/.test(model) ? auto && api : api; } export function resolveNewThreadModelSelection(input: { From 6140e41bf1beae72bdbeb1aee552953e2bb5a95e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 10:14:39 +0100 Subject: [PATCH 063/230] test(web): check the Auto route per level with Auto Low Since #10 and #12 Auto High runs Opus 5.5 instead of Fable 5.2, so this test failed on main: it still expected Auto High to name Fable. Auto High and Auto Medium now both name Opus, so the second level check uses Auto Low (Sonnet 5.5), which still shows a level picking a different model. Origin: the weekly-first Auto routing brief requires the autoRoute tests to pass; this one already failed on fork main 04d5047a05. --- apps/web/src/components/chat/autoRoute.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/autoRoute.test.ts b/apps/web/src/components/chat/autoRoute.test.ts index 85ae44be3be8..d49bf6bf86b3 100644 --- a/apps/web/src/components/chat/autoRoute.test.ts +++ b/apps/web/src/components/chat/autoRoute.test.ts @@ -57,8 +57,8 @@ describe("describeAutoRoute", () => { expect(medium?.driverKind).toBe("claudeAgent"); expect(medium?.label).toMatch(/^.*Opus 5\.5 \(B\)$/); - const high = describeAutoRoute({ entries, options: [{ id: "effort", value: "high" }], now }); - expect(high?.label).toMatch(/Fable 5\.2 \(B\)$/); + const low = describeAutoRoute({ entries, options: [{ id: "effort", value: "low" }], now }); + expect(low?.label).toMatch(/Sonnet 5\.5 \(B\)$/); }); it("names another provider when both Claude accounts are used up", () => { From 2a16fea299df701f11106fc611fa19d9cf16da35 Mon Sep 17 00:00:00 2001 From: radys-s Date: Thu, 19 Nov 2026 10:15:08 +0100 Subject: [PATCH 064/230] ci: give the test jobs more time on fork runners GitHub-hosted ubuntu-24.04 runners have 4 vCPU against Blacksmith's 8. On the first fork run the Test job was still passing package after package when its 10-minute limit cancelled it (10m18s, cut off in packages/contracts), and Test Web 2 used 6m49s of its 10 minutes. Outside pingdotgg/t3code, Test now gets 30 minutes and Test Web 20. Upstream keeps its 10-minute limits. Origin: cancelled "Test" job on PR #14. --- .github/workflows/ci.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d5b44721c7a0..36c2a2f0b270 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -282,7 +282,7 @@ jobs: needs: changes if: ${{ !cancelled() && needs.changes.outputs.test != 'false' }} runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} - timeout-minutes: 10 + timeout-minutes: ${{ github.repository == 'pingdotgg/t3code' && 10 || 30 }} steps: - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -372,7 +372,7 @@ jobs: needs: changes if: ${{ !cancelled() && needs.changes.outputs.test_web != 'false' }} runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} - timeout-minutes: 10 + timeout-minutes: ${{ github.repository == 'pingdotgg/t3code' && 10 || 20 }} strategy: fail-fast: false matrix: From 76324552faa0bb1b18958b4298eb1062603ca5b1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 10:29:09 +0100 Subject: [PATCH 065/230] feat(auto): rank accounts by weekly pace MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auto ranked two accounts with room by their 5-hour windows and used the weekly window only as a tie-break. The weekly quota is the scarce one: what is left at the weekly reset is lost, and an account that runs dry early blocks a whole day. On 2026-11-19 07:15 CET Claude A had 32% left for 52.8 h and Claude B 60% for 149.8 h, and the 5-hour stagger chose. Among accounts with room, Auto now goes first to the higher weekly pace: weekly % left per hour until that window resets (A 0.61%/h, B 0.40%/h, so A). Paces within 15% tie, and then the old order decides: the further along 5-hour window, then the sooner weekly reset. An account without weekly data ranks after one with it. Weekly windows count only for the models they limit, through `usageWindowLimitsModel`. Auto-aware instances first, the 90% guard and the sticky rule are unchanged. Origin: Tomáš, 2026-11-19: "focus mainly on the weekly limit, by how depleted it is, with the rules we agreed" (brief: ~/.agents/prompts/t3-auto-weekly-routing.md). --- docs/progress.md | 8 +++ packages/shared/src/autoModel.test.ts | 79 +++++++++++++++++++++++++-- packages/shared/src/autoModel.ts | 58 +++++++++++++++----- packages/shared/src/usageLimits.ts | 2 +- 4 files changed, 127 insertions(+), 20 deletions(-) diff --git a/docs/progress.md b/docs/progress.md index c3425129e2df..f8e10439d896 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -125,3 +125,11 @@ - Numbers: the new adapter test failed on base (live effort change, no reopen) and passes; ClaudeAdapterV2 + claudeModelOptions 475/475. Real run on the worktree's seeded `.t3`: one Auto Low thread over the CLI (Sonnet 5.5 at low, Auto's first Low candidate) quoted `Auto level: low` from its system prompt. - `~/.agents`: `auto-mode.md` and the `auto` skill read the level from that line and fall back to the model name only without it. - Next: deploy on hub2 and the PC; copy the `~/.agents` change into `radys-s/t3-setup-improvements` for hub. + +## 2026-11-19: Auto ranks accounts by weekly pace + +- What: among accounts with room, Auto now goes first to the one with the higher weekly pace: weekly % left divided by the hours until that weekly window resets, the burn rate that spends the quota exactly at its reset. Paces within 15% of each other tie, and then the old order decides (the further along 5-hour window, so windows still stagger, then the sooner weekly reset). An account without weekly data ranks after accounts that have it. A one-model weekly window counts only for its model: the per-window check moved out of `exhaustedUsageWindow` into `usageWindowLimitsModel`, which Auto's pace reuses and which now reads Claude's `seven_day_` windows the way the server's hub pool check already did, so a spent Fable-only allowance no longer blocks Opus on that account. Unchanged: Auto-aware instances first, the 90% guard, the sticky rule and the return to a better model. +- Why: Tomáš asked Auto to "focus mainly on the weekly limit, by how depleted it is". The weekly quota is the scarce one: what is left at the weekly reset is lost, and an account that runs dry early blocks a whole day. On 2026-11-19 07:15 CET Claude A had 32% left for 52.8 h (0.61%/h) and Claude B 60% for 149.8 h (0.40%/h), and the 5-hour stagger, not the weekly state, chose between them. +- Numbers: autoModel 17/17 (the 2026-11-19 example, the no-weekly-data case and the one-model-window case failed on base), usageLimits 99/99 (the new Claude row failed on base), AutoFailoverService 8/8, handoff 17/17, codexUsageLimits 20/20, autoRoute 2/2 (it already failed on fork main: it still expected Fable for Auto High). `vp run check:changed`: format, lint, knip, typecheck (36 packages) and 120 tests in 4 files pass. Real run on the worktree's seeded `.t3` with the two Auto instances: Usage → Limits showed A at 27% weekly left for 2d 2h (0.54%/h) and B at 60% for 6d 3h (0.41%/h), and the picker named A for every level (Auto High · Opus 5.5 (A)). The old rule also picks A right now (A's 5-hour window 39% used, B's 1%), so this run shows the wiring, and the unit tests cover where the rules differ. +- `~/.agents`: the `auto` skill drops "Never move work between Claude A and Claude B because of limits" and says Auto picks the account by weekly pace. +- Next: backlog 2 (model-aware room) can build `hasRoom` on `usageWindowLimitsModel`; today a one-model window at 90% still marks the whole account as out of room. Deploy on Tomáš's word. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index ff03d6791dc9..453d074b1d53 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -4,6 +4,7 @@ import { type ModelSelection, type ServerProvider, } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; import { describe, expect, it } from "vite-plus/test"; import { @@ -16,6 +17,7 @@ import { const now = Date.parse("2026-11-12T12:00:00.000Z"); const resetsAt = "2026-11-12T15:00:00.000Z"; +const inHours = (hours: number) => DateTime.formatIso(DateTime.makeUnsafe(now + hours * 3_600_000)); const effortCapabilities = { optionDescriptors: [ @@ -57,13 +59,18 @@ function claude(id: string, usedPercent: number, autoAware = true): ServerProvid } as unknown as ServerProvider; } -function withWeekly(provider: ServerProvider, usedPercent: number, weeklyResetsAt: string) { +function withWeekly( + provider: ServerProvider, + usedPercent: number, + weeklyResetsAt: string, + id = "seven_day", +) { return { ...provider, usageLimits: { windows: [ ...(provider.usageLimits?.windows ?? []), - { id: "seven_day", kind: "weekly", label: "Weekly", usedPercent, resetsAt: weeklyResetsAt }, + { id, kind: "weekly", label: "Weekly", usedPercent, resetsAt: weeklyResetsAt }, ], }, } as unknown as ServerProvider; @@ -75,6 +82,9 @@ const auto = (level?: string): ModelSelection => ({ ...(level ? { options: [{ id: "effort", value: level }] } : {}), }); +const routeTo = (providers: ReadonlyArray) => + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId; + describe("resolveAutoModelSelection", () => { it("maps each level to its orchestrator model and effort, medium by default", () => { const providers = [claude("claudeAuto", 10)]; @@ -128,6 +138,16 @@ describe("resolveAutoModelSelection", () => { expect( resolveAutoModelSelection({ selection: auto(), providers: busy, now, current }), ).toMatchObject({ sticky: false, selection: { instanceId: "claudeAutoB" } }); + + // A higher weekly pace elsewhere does not move a thread whose account still has room. + const onB = { instanceId: ProviderInstanceId.make("claudeAutoB"), model: "claude-opus-5-5" }; + const urgentA = [ + withWeekly(claude("claudeAuto", 10), 68, inHours(52.8)), + withWeekly(claude("claudeAutoB", 45), 40, inHours(149.8)), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: urgentA, now, current: onB }), + ).toMatchObject({ sticky: true, selection: { instanceId: "claudeAutoB" } }); }); it("steps down to other subscriptions when both Claude accounts are exhausted", () => { @@ -156,6 +176,55 @@ describe("resolveAutoModelSelection", () => { expect( resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, ).toBe("claudeAuto"); + // Weekly paces within 15% count as equal: B's 0.54%/h does not beat A's 0.5%/h. + const closePaces = [ + withWeekly(claude("claudeAutoB", 10), 46, inHours(100)), + withWeekly(claude("claudeAuto", 50), 50, inHours(100)), + ]; + expect(routeTo(closePaces)).toBe("claudeAuto"); + }); + + it("spends first the account whose weekly quota would be lost at its reset", () => { + // 2026-11-19 07:15 CET: A has 32% left for 52.8 h (0.61%/h), B 60% for 149.8 h (0.40%/h). + // B's 5-hour window is further along, but A's quota is gone in two days. + const route = (aWeeklyUsed: number) => + routeTo([ + withWeekly(claude("claudeAutoB", 45), 40, inHours(149.8)), + withWeekly(claude("claudeAuto", 10), aWeeklyUsed, inHours(52.8)), + ]); + expect(route(68)).toBe("claudeAuto"); + // With 15% left (0.28%/h), A has less to lose and waits; at 97% it has no room at all. + expect(route(85)).toBe("claudeAutoB"); + expect(route(97)).toBe("claudeAutoB"); + }); + + it("ranks an account without weekly data after one with it", () => { + // A's 5-hour window is further along, but A's weekly use is unknown, not 0%. + const providers = [ + claude("claudeAuto", 50), + withWeekly(claude("claudeAutoB", 10), 40, inHours(100)), + ]; + expect(routeTo(providers)).toBe("claudeAutoB"); + }); + + it("counts a one-model weekly window only for that model", () => { + // A's nearly spent Opus allowance resets late, so A has little Opus quota to lose. B's nearly + // spent allowance is Fable's, which does not slow B's Opus pace. + const providers = [ + withWeekly( + withWeekly(claude("claudeAuto", 50), 20, inHours(30)), + 85, + inHours(140), + "seven_day_opus", + ), + withWeekly( + withWeekly(claude("claudeAutoB", 10), 50, inHours(100)), + 85, + inHours(140), + "seven_day_fable", + ), + ]; + expect(routeTo(providers)).toBe("claudeAutoB"); }); it("switches to the other account once a 5-hour or weekly window is 90% used", () => { @@ -181,11 +250,11 @@ describe("resolveAutoModelSelection", () => { ).toBe("claudeAuto"); }); - it("with similar 5-hour use, spends the account whose weekly limit resets first", () => { - // B's window is slightly further along, but A's unused weekly quota is gone tomorrow. + it("with similar weekly pace and 5-hour use, spends the account whose weekly limit resets first", () => { + // Both paces are 0.42%/h and B's window is slightly further along, but A resets a day sooner. const providers = [ withWeekly(claude("claudeAutoB", 30), 40, "2026-11-18T12:00:00.000Z"), - withWeekly(claude("claudeAuto", 25), 40, "2026-11-13T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 25), 50, "2026-11-17T12:00:00.000Z"), ]; expect( resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index b88b26456a67..2b82dee5dbe4 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -5,7 +5,7 @@ import { type ServerProvider, } from "@t3tools/contracts"; -import { exhaustedUsageWindow } from "./usageLimits.ts"; +import { exhaustedUsageWindow, usageWindowLimitsModel } from "./usageLimits.ts"; /** * "Auto" is a custom model (slug `auto`) on any provider instance. Picking it never reaches @@ -155,37 +155,67 @@ function autoLevelOf(selection: ModelSelection): AutoLevel { /** Accounts whose 5-hour use differs by less than this many points count as equally far along. */ const SESSION_BAND_PERCENT = 10; +/** Weekly paces within this share of each other count as equal. */ +const PACE_BAND = 0.15; +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; function sessionUsedPercent(provider: ServerProvider): number { const windows = (provider.usageLimits?.windows ?? []).filter((w) => w.kind === "session"); return Math.max(0, ...windows.map((w) => w.usedPercent ?? 0)); } +/** Weekly windows with a known reset that limit `model`; a one-model window counts only for it. */ +function weeklyWindows(provider: ServerProvider, model: string) { + return (provider.usageLimits?.windows ?? []).filter( + (w) => + w.kind === "weekly" && + Number.isFinite(Date.parse(w.resetsAt ?? "")) && + usageWindowLimitsModel(provider, w, model), + ); +} + +/** + * Weekly % left per hour until that window resets: the burn rate that spends the quota exactly + * at its reset, when whatever is left is lost. The tightest window decides; undefined without + * weekly data. + */ +function weeklyPace(provider: ServerProvider, model: string, now: number): number | undefined { + const paces = weeklyWindows(provider, model).map( + (w) => (100 - w.usedPercent) / (Math.max(Date.parse(w.resetsAt!) - now, MINUTE) / HOUR), + ); + return paces.length > 0 ? Math.min(...paces) : undefined; +} + /** When the soonest weekly window resets; unused weekly quota is lost then. */ -function weeklyResetAt(provider: ServerProvider): number { - const resets = (provider.usageLimits?.windows ?? []) - .filter((w) => w.kind === "weekly" && w.resetsAt !== undefined) - .map((w) => Date.parse(w.resetsAt!)) - .filter(Number.isFinite); - return resets.length > 0 ? Math.min(...resets) : Infinity; +function weeklyResetAt(provider: ServerProvider, model: string): number { + return Math.min(...weeklyWindows(provider, model).map((w) => Date.parse(w.resetsAt!))); +} + +/** The higher pace first; paces within 15% tie, and an account without weekly data goes last. */ +function comparePace(a: number | undefined, b: number | undefined): number { + if (a === undefined || b === undefined) return Number(a === undefined) - Number(b === undefined); + return Math.abs(a - b) > PACE_BAND * Math.max(a, b) ? b - a : 0; } /** - * Best instance first: Auto-aware, then accounts under 90% everywhere. Among those, the further - * along 5-hour window, so windows stagger (one refreshes while the other runs); within 10 - * points, the sooner weekly reset. Past 90% everywhere, the most left. + * Best instance for `model` first: Auto-aware, then accounts under 90% everywhere. Among those, + * the higher weekly pace, so the quota a reset would waste is spent first. With similar paces, + * the further along 5-hour window, so windows stagger (one refreshes while the other runs); + * within 10 points, the sooner weekly reset. Past 90% everywhere, the most left. */ -function compareInstances(a: ServerProvider, b: ServerProvider): number { +function compareInstances(a: ServerProvider, b: ServerProvider, model: string, now: number) { const aware = Number(isAutoAware(b)) - Number(isAutoAware(a)); if (aware !== 0) return aware; const room = Number(hasRoom(b)) - Number(hasRoom(a)); if (room !== 0) return room; if (!hasRoom(a)) return peakUsedPercent(a) - peakUsedPercent(b); + const pace = comparePace(weeklyPace(a, model, now), weeklyPace(b, model, now)); + if (pace !== 0) return pace; const session = sessionUsedPercent(b) - sessionUsedPercent(a); if (Math.abs(session) >= SESSION_BAND_PERCENT) return session; - const weekly = weeklyResetAt(a) - weeklyResetAt(b); + const weekly = weeklyResetAt(a, model) - weeklyResetAt(b, model); if (Number.isFinite(weekly) && weekly !== 0) return weekly; - if (weekly === Infinity || weekly === -Infinity) return weekly > 0 ? 1 : -1; return session || peakUsedPercent(a) - peakUsedPercent(b); } @@ -304,7 +334,7 @@ export function resolveAutoModelSelection(input: { open(provider, candidate.model), ) // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. - .sort(compareInstances); + .sort((a, b) => compareInstances(a, b, candidate.model, input.now)); const provider = instances[0]; if (provider) { return { selection: toSelection(provider, candidate, level), level, sticky: false }; diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 2df18df8b4ad..a0375c7c865e 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -24,7 +24,7 @@ import { isLocalLoopbackHost, isWildcardHost } from "./hostClassification.ts"; const MINUTE = 60_000; /** Whether `window` limits `model`; a window for some models or one pool limits only those. */ -function usageWindowLimitsModel( +export function usageWindowLimitsModel( provider: ServerProvider, window: ServerProviderUsageWindow, model: string, From f070746a520da15f27f15e402e51b5aa086e563f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 10:37:07 +0100 Subject: [PATCH 066/230] fix(auto): a weekly window with no reset counts as a fresh week Claude's get_usage types `resets_at` as nullable, and a window that has not started (an account right after its weekly reset) can report usage without a reset. The weekly pace skipped such a window, so the fresh account ranked as having no weekly data and lost to every account with a reset, even a slower one. Nothing then used it, so its week never started. Such a window now resets a full window length from now (100% left over a week is about 0.6%/h). A window with neither a reset nor a length is still skipped, and an account without any weekly window still ranks after those with one. Origin: read-only review of the weekly-pace routing (finding S1). --- docs/progress.md | 4 ++-- packages/shared/src/autoModel.test.ts | 20 +++++++++++++++++ packages/shared/src/autoModel.ts | 31 ++++++++++++++++----------- 3 files changed, 40 insertions(+), 15 deletions(-) diff --git a/docs/progress.md b/docs/progress.md index f8e10439d896..f25a8eeaa73e 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -128,8 +128,8 @@ ## 2026-11-19: Auto ranks accounts by weekly pace -- What: among accounts with room, Auto now goes first to the one with the higher weekly pace: weekly % left divided by the hours until that weekly window resets, the burn rate that spends the quota exactly at its reset. Paces within 15% of each other tie, and then the old order decides (the further along 5-hour window, so windows still stagger, then the sooner weekly reset). An account without weekly data ranks after accounts that have it. A one-model weekly window counts only for its model: the per-window check moved out of `exhaustedUsageWindow` into `usageWindowLimitsModel`, which Auto's pace reuses and which now reads Claude's `seven_day_` windows the way the server's hub pool check already did, so a spent Fable-only allowance no longer blocks Opus on that account. Unchanged: Auto-aware instances first, the 90% guard, the sticky rule and the return to a better model. +- What: among accounts with room, Auto now goes first to the one with the higher weekly pace: weekly % left divided by the hours until that weekly window resets, the burn rate that spends the quota exactly at its reset. Paces within 15% of each other tie, and then the old order decides (the further along 5-hour window, so windows still stagger, then the sooner weekly reset). An account without weekly data ranks after accounts that have it; a weekly window that reports no reset has not started, so it counts as a full window from now (a fresh week, about 0.6%/h). A one-model weekly window counts only for its model: the per-window check moved out of `exhaustedUsageWindow` into `usageWindowLimitsModel`, which Auto's pace reuses and which now reads Claude's `seven_day_` windows the way the server's hub pool check already did, so a spent Fable-only allowance no longer blocks Opus on that account. Unchanged: Auto-aware instances first, the 90% guard, the sticky rule and the return to a better model. - Why: Tomáš asked Auto to "focus mainly on the weekly limit, by how depleted it is". The weekly quota is the scarce one: what is left at the weekly reset is lost, and an account that runs dry early blocks a whole day. On 2026-11-19 07:15 CET Claude A had 32% left for 52.8 h (0.61%/h) and Claude B 60% for 149.8 h (0.40%/h), and the 5-hour stagger, not the weekly state, chose between them. -- Numbers: autoModel 17/17 (the 2026-11-19 example, the no-weekly-data case and the one-model-window case failed on base), usageLimits 99/99 (the new Claude row failed on base), AutoFailoverService 8/8, handoff 17/17, codexUsageLimits 20/20, autoRoute 2/2 (it already failed on fork main: it still expected Fable for Auto High). `vp run check:changed`: format, lint, knip, typecheck (36 packages) and 120 tests in 4 files pass. Real run on the worktree's seeded `.t3` with the two Auto instances: Usage → Limits showed A at 27% weekly left for 2d 2h (0.54%/h) and B at 60% for 6d 3h (0.41%/h), and the picker named A for every level (Auto High · Opus 5.5 (A)). The old rule also picks A right now (A's 5-hour window 39% used, B's 1%), so this run shows the wiring, and the unit tests cover where the rules differ. +- Numbers: autoModel 17/17 (the 2026-11-19 example, the no-weekly-data case, the unstarted-window case and the one-model-window case failed on base), usageLimits 99/99 (the new Claude row failed on base), AutoFailoverService 8/8, handoff 17/17, codexUsageLimits 20/20, autoRoute 2/2 (it already failed on fork main: it still expected Fable for Auto High). `vp run check:changed`: format, lint, knip, typecheck (36 packages) and 120 tests in 4 files pass. Real run on the worktree's seeded `.t3` with the two Auto instances: Usage → Limits showed A at 27% weekly left for 2d 2h (0.54%/h) and B at 60% for 6d 3h (0.41%/h), and the picker named A for every level (Auto High · Opus 5.5 (A)). The old rule also picks A right now (A's 5-hour window 39% used, B's 1%), so this run shows the wiring, and the unit tests cover where the rules differ. - `~/.agents`: the `auto` skill drops "Never move work between Claude A and Claude B because of limits" and says Auto picks the account by weekly pace. - Next: backlog 2 (model-aware room) can build `hasRoom` on `usageWindowLimitsModel`; today a one-model window at 90% still marks the whole account as out of room. Deploy on Tomáš's word. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index 453d074b1d53..a543672bbcee 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -205,6 +205,26 @@ describe("resolveAutoModelSelection", () => { withWeekly(claude("claudeAutoB", 10), 40, inHours(100)), ]; expect(routeTo(providers)).toBe("claudeAutoB"); + + // A weekly window that has not started reports no reset; it runs a full week from now + // (0.6%/h), so the fresh account beats A's 0.47%/h. + const unstarted = { + ...claude("claudeAutoB", 0), + usageLimits: { + windows: [ + { + id: "seven_day", + kind: "weekly", + label: "Weekly", + usedPercent: 0, + windowDurationMins: 10_080, + }, + ], + }, + } as unknown as ServerProvider; + expect(routeTo([withWeekly(claude("claudeAuto", 50), 30, inHours(150)), unstarted])).toBe( + "claudeAutoB", + ); }); it("counts a one-model weekly window only for that model", () => { diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 2b82dee5dbe4..64d8d766ad29 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -165,14 +165,19 @@ function sessionUsedPercent(provider: ServerProvider): number { return Math.max(0, ...windows.map((w) => w.usedPercent ?? 0)); } -/** Weekly windows with a known reset that limit `model`; a one-model window counts only for it. */ -function weeklyWindows(provider: ServerProvider, model: string) { - return (provider.usageLimits?.windows ?? []).filter( - (w) => - w.kind === "weekly" && - Number.isFinite(Date.parse(w.resetsAt ?? "")) && - usageWindowLimitsModel(provider, w, model), - ); +/** + * Weekly windows that limit `model` (a one-model window counts only for it) and when each + * resets. A window that has not started reports no reset; it would run its full length from now. + */ +function weeklyWindows(provider: ServerProvider, model: string, now: number) { + return (provider.usageLimits?.windows ?? []).flatMap((w) => { + if (w.kind !== "weekly" || !usageWindowLimitsModel(provider, w, model)) return []; + const resetsAt = + w.resetsAt === undefined + ? now + (w.windowDurationMins ?? Number.NaN) * MINUTE + : Date.parse(w.resetsAt); + return Number.isFinite(resetsAt) ? [{ usedPercent: w.usedPercent, resetsAt }] : []; + }); } /** @@ -181,15 +186,15 @@ function weeklyWindows(provider: ServerProvider, model: string) { * weekly data. */ function weeklyPace(provider: ServerProvider, model: string, now: number): number | undefined { - const paces = weeklyWindows(provider, model).map( - (w) => (100 - w.usedPercent) / (Math.max(Date.parse(w.resetsAt!) - now, MINUTE) / HOUR), + const paces = weeklyWindows(provider, model, now).map( + (w) => (100 - w.usedPercent) / (Math.max(w.resetsAt - now, MINUTE) / HOUR), ); return paces.length > 0 ? Math.min(...paces) : undefined; } /** When the soonest weekly window resets; unused weekly quota is lost then. */ -function weeklyResetAt(provider: ServerProvider, model: string): number { - return Math.min(...weeklyWindows(provider, model).map((w) => Date.parse(w.resetsAt!))); +function weeklyResetAt(provider: ServerProvider, model: string, now: number): number { + return Math.min(...weeklyWindows(provider, model, now).map((w) => w.resetsAt)); } /** The higher pace first; paces within 15% tie, and an account without weekly data goes last. */ @@ -214,7 +219,7 @@ function compareInstances(a: ServerProvider, b: ServerProvider, model: string, n if (pace !== 0) return pace; const session = sessionUsedPercent(b) - sessionUsedPercent(a); if (Math.abs(session) >= SESSION_BAND_PERCENT) return session; - const weekly = weeklyResetAt(a, model) - weeklyResetAt(b, model); + const weekly = weeklyResetAt(a, model, now) - weeklyResetAt(b, model, now); if (Number.isFinite(weekly) && weekly !== 0) return weekly; return session || peakUsedPercent(a) - peakUsedPercent(b); } From 312a5f3c8b84a87e834e8f5bee2b10c3d1d27e3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 10:39:22 +0100 Subject: [PATCH 067/230] docs(auto): say when a weekly window has no reset A weekly window can lack a reset because it has not started yet, but also when a stream update reached the server before any usage probe. The comment named only the first case. Origin: read-only review of the weekly-pace routing, round 2 (nit S4). --- packages/shared/src/autoModel.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 64d8d766ad29..bdf7948a4a79 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -167,7 +167,8 @@ function sessionUsedPercent(provider: ServerProvider): number { /** * Weekly windows that limit `model` (a one-model window counts only for it) and when each - * resets. A window that has not started reports no reset; it would run its full length from now. + * resets. A window with no reported reset, such as one that has not started, counts as a full + * window from now. */ function weeklyWindows(provider: ServerProvider, model: string, now: number) { return (provider.usageLimits?.windows ?? []).flatMap((w) => { From 6ed3e68e4ac1f1bf7809af2b4611a4929b50c3c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 12 Nov 2026 18:22:12 +0100 Subject: [PATCH 068/230] feat: Auto model routes across subscriptions by level and live usage limits --- .../src/orchestration-v2/Orchestrator.ts | 67 +++++- docs/progress.md | 10 + packages/shared/package.json | 4 + packages/shared/src/autoModel.test.ts | 132 ++++++++++++ packages/shared/src/autoModel.ts | 202 ++++++++++++++++++ 5 files changed, 412 insertions(+), 3 deletions(-) create mode 100644 docs/progress.md create mode 100644 packages/shared/src/autoModel.test.ts create mode 100644 packages/shared/src/autoModel.ts diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index c71addfa57c0..b8a30e277446 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -85,6 +85,8 @@ import { import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { modelSelectionsEqual } from "@t3tools/shared/model"; import { expandAssistantCitationsForProvider } from "@t3tools/shared/assistantCitations"; +import { isAutoModelSelection, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import { modelSwitchSince } from "./modelSwitch.ts"; import { contextBoundaryOrdinal, isScheduledFreshRun } from "./contextBoundary.ts"; import { isPlaceholderThreadTitle } from "./placeholderThreadTitle.ts"; @@ -16843,6 +16845,65 @@ export const layer: Layer.Layer< | RuntimePolicyV2 | ServerSettings.ServerSettingsService | ThreadForkServiceV2 -> = Layer.effect(OrchestratorV2, makeOrchestrator()).pipe( - Layer.provide(ThreadCommandExecutor.layer), -); +> = Layer.effect( + OrchestratorV2, + makeOrchestrator().pipe(Effect.flatMap((orchestrator) => withAutoModelRouting(orchestrator))), +).pipe(Layer.provide(ThreadCommandExecutor.layer)); + +/** Commands whose `auto` model keeps the thread's current model while it still fits. */ +const AUTO_STICKY_COMMANDS: ReadonlySet = new Set([ + "message.dispatch", + "thread.model-selection.set", + "provider.switch", +]); + +/** + * Replaces the `auto` model in any command with the concrete model Auto picks from live usage + * limits, so every surface (web, mobile, MCP, scheduled tasks) gets the same routing. + */ +const withAutoModelRouting = Effect.fn("OrchestratorV2.withAutoModelRouting")(function* ( + orchestrator: OrchestratorV2Shape, +) { + // Optional so layers without provider snapshots (tests, CLI tools) still build; there, Auto + // is rejected instead of routed. + const registry = yield* Effect.serviceOption(ProviderRegistry.ProviderRegistry); + const resolve = Effect.fn("OrchestratorV2.resolveAutoModel")(function* ( + command: OrchestrationV2ServerCommand, + ) { + const selection = (command as { readonly modelSelection?: ModelSelection }).modelSelection; + if (!isAutoModelSelection(selection) || selection === undefined) return command; + const threadId = (command as { readonly threadId?: ThreadId }).threadId; + const current = + threadId !== undefined && AUTO_STICKY_COMMANDS.has(command.type) + ? ((yield* orchestrator.getThreadShell(threadId).pipe(Effect.orElseSucceed(() => null))) + ?.modelSelection ?? null) + : null; + const resolution = resolveAutoModelSelection({ + selection, + providers: Option.isSome(registry) ? yield* registry.value.getProviders : [], + now: DateTime.toEpochMillis(yield* DateTime.now), + current, + }); + if (resolution === null) { + return yield* new OrchestratorCommandRejectedError({ + commandId: command.commandId, + commandType: command.type, + cause: new Error( + "Auto found no usable model: every candidate is disabled, signed out, or at its usage limit.", + ), + }); + } + yield* Effect.logInfo("auto model routing", { + commandType: command.type, + level: resolution.level, + sticky: resolution.sticky, + instanceId: resolution.selection.instanceId, + model: resolution.selection.model, + }); + return { ...command, modelSelection: resolution.selection } as OrchestrationV2ServerCommand; + }); + return { + ...orchestrator, + dispatch: (command) => resolve(command).pipe(Effect.flatMap(orchestrator.dispatch)), + } satisfies OrchestratorV2Shape; +}); diff --git a/docs/progress.md b/docs/progress.md new file mode 100644 index 000000000000..dfb3c4eafab5 --- /dev/null +++ b/docs/progress.md @@ -0,0 +1,10 @@ +# Progress (radys-s fork) + +## 2026-11-12: Auto model + +- What: an "Auto" model with its own Low/Medium/High level. Picking it never reaches a provider; the server replaces it in every command (`OrchestratorV2.dispatch`) with a concrete model chosen from live usage limits: Fable (high), Opus (medium) or Sonnet (low) on whichever Claude account has more room, then Codex, Grok and OpenCode when Claude is out. +- Why: Tomáš wanted one Auto entry in the model picker that routes across all his subscriptions, including Claude A vs B. +- How it shows up: a custom model `auto` (with an `effort` select of low/medium/high) on the Auto Claude instances in settings. No web change was needed; the picker already renders custom models and their options. +- Numbers: resolver 5/5 tests; shared and server typecheck clean (server took 22 min on the first, cold run, ~6 min warm). +- Worked: one wrapper around `dispatch` covers web, mobile, MCP and scheduled tasks. Stickiness keeps a thread on its model until it passes 90% used, so threads do not hop accounts on each message. +- Next: after the first message the composer shows the concrete model, not "Auto"; keeping Auto selected mid-thread needs a client change. diff --git a/packages/shared/package.json b/packages/shared/package.json index 68a0b589f880..ec663c437ffa 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -411,6 +411,10 @@ "types": "./src/usageFormat.ts", "import": "./src/usageFormat.ts" }, + "./autoModel": { + "types": "./src/autoModel.ts", + "import": "./src/autoModel.ts" + }, "./usageLimits": { "types": "./src/usageLimits.ts", "import": "./src/usageLimits.ts" diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts new file mode 100644 index 000000000000..e7846c214e74 --- /dev/null +++ b/packages/shared/src/autoModel.test.ts @@ -0,0 +1,132 @@ +import { + ProviderDriverKind, + ProviderInstanceId, + type ModelSelection, + type ServerProvider, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { AUTO_LEVEL_DESCRIPTOR, resolveAutoModelSelection } from "./autoModel.ts"; + +const now = Date.parse("2026-11-12T12:00:00.000Z"); +const resetsAt = "2026-11-12T15:00:00.000Z"; + +const effortCapabilities = { + optionDescriptors: [ + { + id: "effort", + label: "Effort", + type: "select" as const, + options: ["low", "medium", "high"].map((id) => ({ id, label: id })), + }, + ], +}; + +function claude(id: string, usedPercent: number, autoAware = true): ServerProvider { + return { + instanceId: ProviderInstanceId.make(id), + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-11-12T11:00:00.000Z", + models: [ + ...["claude-fable-5-2", "claude-opus-5-5", "claude-sonnet-5-5"].map((slug) => ({ + slug, + name: slug, + isCustom: false, + capabilities: effortCapabilities, + })), + ...(autoAware + ? [ + { + slug: "auto", + name: "Auto", + isCustom: true, + capabilities: { optionDescriptors: [AUTO_LEVEL_DESCRIPTOR] }, + }, + ] + : []), + ], + slashCommands: [], + skills: [], + usageLimits: { + windows: [{ id: "five_hour", kind: "session", label: "Session", usedPercent, resetsAt }], + }, + } as unknown as ServerProvider; +} + +const auto = (level?: string): ModelSelection => ({ + instanceId: ProviderInstanceId.make("claudeAuto"), + model: "auto", + ...(level ? { options: [{ id: "effort", value: level }] } : {}), +}); + +describe("resolveAutoModelSelection", () => { + it("maps each level to its orchestrator model and effort, medium by default", () => { + const providers = [claude("claudeAuto", 10)]; + expect( + resolveAutoModelSelection({ selection: auto("high"), providers, now })?.selection, + ).toEqual({ + instanceId: "claudeAuto", + model: "claude-fable-5-2", + options: [{ id: "effort", value: "high" }], + }); + expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.model).toBe( + "claude-opus-5-5", + ); + expect( + resolveAutoModelSelection({ selection: auto("low"), providers, now })?.selection, + ).toEqual({ + instanceId: "claudeAuto", + model: "claude-sonnet-5-5", + options: [{ id: "effort", value: "low" }], + }); + }); + + it("picks the Claude account with more room, preferring Auto-aware instances", () => { + const providers = [ + claude("claudeAgent", 0, false), + claude("claudeAuto", 70), + claude("claudeAutoB", 20), + ]; + expect( + resolveAutoModelSelection({ selection: auto("medium"), providers, now })?.selection + .instanceId, + ).toBe("claudeAutoB"); + }); + + it("keeps the thread's current model until it passes 90% used", () => { + const current = { instanceId: ProviderInstanceId.make("claudeAuto"), model: "claude-opus-5-5" }; + const calm = [claude("claudeAuto", 60), claude("claudeAutoB", 5)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: calm, now, current }), + ).toMatchObject({ sticky: true, selection: { instanceId: "claudeAuto" } }); + + const busy = [claude("claudeAuto", 95), claude("claudeAutoB", 5)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: busy, now, current }), + ).toMatchObject({ sticky: false, selection: { instanceId: "claudeAutoB" } }); + }); + + it("steps down to other subscriptions when both Claude accounts are exhausted", () => { + const grok = { + ...claude("grok", 0, false), + driver: ProviderDriverKind.make("grok"), + models: [{ slug: "grok-4.7", name: "Grok 4.7", isCustom: false, capabilities: null }], + usageLimits: undefined, + } as unknown as ServerProvider; + const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100), grok]; + expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection).toEqual({ + instanceId: "grok", + model: "grok-4.7", + }); + }); + + it("returns null when nothing is usable", () => { + const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; + expect(resolveAutoModelSelection({ selection: auto(), providers, now })).toBeNull(); + }); +}); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts new file mode 100644 index 000000000000..87f997204b42 --- /dev/null +++ b/packages/shared/src/autoModel.ts @@ -0,0 +1,202 @@ +import { + isProviderAvailable, + type ModelSelection, + type ProviderDriverKind, + type ProviderOptionDescriptor, + type ServerProvider, +} from "@t3tools/contracts"; + +import { exhaustedUsageWindow } from "./usageLimits.ts"; + +/** + * "Auto" is a custom model (slug `auto`) on any provider instance. Picking it never reaches + * a provider: the server replaces it with a concrete model chosen here, from the providers' + * live usage limits. The level (`low` | `medium` | `high`) rides in the `effort` option. + */ +const AUTO_MODEL_SLUG = "auto"; +const AUTO_LEVELS = ["low", "medium", "high"] as const; +type AutoLevel = (typeof AUTO_LEVELS)[number]; +const DEFAULT_LEVEL: AutoLevel = "medium"; +/** Above this peak usage, a sticky model gives way when another candidate has more room. */ +const STICKY_MAX_USED_PERCENT = 90; + +interface AutoCandidate { + readonly driver: string; + readonly model: string; + /** The candidate's own reasoning effort for this level. */ + readonly effort: string; +} + +const claude = (model: string, effort: string): AutoCandidate => ({ + driver: "claudeAgent", + model, + effort, +}); +const codex = (model: string, effort: string): AutoCandidate => ({ + driver: "codex", + model, + effort, +}); +const grok = (effort: string): AutoCandidate => ({ driver: "grok", model: "grok-4.7", effort }); +const opencode = (model: string, effort: string): AutoCandidate => ({ + driver: "opencode", + model, + effort, +}); + +/** + * Orchestrator candidates per level, best first. Each level starts on its Claude model and + * steps down through the other subscriptions as limits run out. + */ +const AUTO_CANDIDATES: Readonly>> = { + high: [ + claude("claude-fable-5-2", "high"), + claude("claude-opus-5-5", "high"), + codex("gpt-6.1-sol", "high"), + codex("gpt-6-astra", "high"), + grok("high"), + codex("gpt-6-luna", "high"), + ], + medium: [ + claude("claude-opus-5-5", "medium"), + claude("claude-fable-5-2", "medium"), + codex("gpt-6.1-sol", "medium"), + codex("gpt-6-astra", "medium"), + claude("claude-sonnet-5-5", "medium"), + grok("medium"), + codex("gpt-6-luna", "medium"), + ], + low: [ + claude("claude-sonnet-5-5", "low"), + claude("claude-haiku-5-5", "low"), + opencode("opencode/big-pickle", "medium"), + opencode("opencode/deepseek-v4.1-flash-free", "medium"), + codex("gpt-6-luna", "low"), + grok("low"), + ], +}; + +/** The option each driver uses for reasoning effort. */ +const EFFORT_OPTION_ID: Readonly> = { + claudeAgent: "effort", + codex: "reasoningEffort", + grok: "reasoningEffort", + opencode: "variant", +}; + +export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { + return selection?.model === AUTO_MODEL_SLUG; +} + +function autoLevelOf(selection: ModelSelection): AutoLevel { + const value = selection.options?.find((option) => option.id === "effort")?.value; + return AUTO_LEVELS.find((level) => level === value) ?? DEFAULT_LEVEL; +} + +/** The `effort` descriptor an `auto` custom model declares, so pickers show Low/Medium/High. */ +export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { + id: "effort", + label: "Auto level", + type: "select", + options: [ + { id: "low", label: "Low", description: "Sonnet orchestrates; cheaper models do more" }, + { id: "medium", label: "Medium", description: "Opus orchestrates", isDefault: true }, + { id: "high", label: "High", description: "Fable orchestrates" }, + ], +}; + +function peakUsedPercent(provider: ServerProvider): number { + return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); +} + +/** Instances that list the `auto` model carry the Auto-mode prompt, so they win ties. */ +function isAutoAware(provider: ServerProvider): boolean { + return provider.models.some((model) => model.slug === AUTO_MODEL_SLUG); +} + +function usable(provider: ServerProvider, model: string, now: number): boolean { + return ( + provider.enabled && + provider.installed && + provider.auth.status !== "unauthenticated" && + isProviderAvailable(provider) && + provider.models.some((entry) => entry.slug === model) && + exhaustedUsageWindow(provider, now, model) === undefined + ); +} + +function effortOptions(provider: ServerProvider, candidate: AutoCandidate) { + const id = EFFORT_OPTION_ID[candidate.driver]; + const descriptor = provider.models + .find((entry) => entry.slug === candidate.model) + ?.capabilities?.optionDescriptors?.find((entry) => entry.id === id); + if (!id || descriptor?.type !== "select") return undefined; + return descriptor.options.some((choice) => choice.id === candidate.effort) + ? [{ id, value: candidate.effort }] + : undefined; +} + +function toSelection(provider: ServerProvider, candidate: AutoCandidate): ModelSelection { + const options = effortOptions(provider, candidate); + return { + instanceId: provider.instanceId, + model: candidate.model, + ...(options ? { options } : {}), + }; +} + +interface AutoResolution { + readonly selection: ModelSelection; + readonly level: AutoLevel; + /** True when the thread's current model was kept. */ + readonly sticky: boolean; +} + +/** + * Keeps the thread's model while it fits this level and is under 90% used (no account hop, no + * lost prompt cache); otherwise the first usable candidate, Auto-aware and least-used instance + * first. Null when nothing is usable. + */ +export function resolveAutoModelSelection(input: { + readonly selection: ModelSelection; + readonly providers: ReadonlyArray; + readonly now: number; + readonly current?: ModelSelection | null; +}): AutoResolution | null { + const level = autoLevelOf(input.selection); + const candidates = AUTO_CANDIDATES[level]; + + const current = input.current; + if (current && !isAutoModelSelection(current)) { + const provider = input.providers.find((entry) => entry.instanceId === current.instanceId); + const candidate = candidates.find( + (entry) => entry.driver === provider?.driver && entry.model === current.model, + ); + if ( + provider && + candidate && + usable(provider, candidate.model, input.now) && + peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT + ) { + return { selection: toSelection(provider, candidate), level, sticky: true }; + } + } + + for (const candidate of candidates) { + const instances = input.providers + .filter( + (provider) => + provider.driver === (candidate.driver as ProviderDriverKind) && + usable(provider, candidate.model, input.now), + ) + // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. + .sort( + (a, b) => + Number(isAutoAware(b)) - Number(isAutoAware(a)) || + peakUsedPercent(a) - peakUsedPercent(b), + ); + const provider = instances[0]; + if (provider) return { selection: toSelection(provider, candidate), level, sticky: false }; + } + return null; +} From 261b91b2459f44c81f81b88afd7095074574968d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 09:45:23 +0100 Subject: [PATCH 069/230] Give the Auto model its own icon in the model picker --- apps/web/src/components/chat/ModelListRow.tsx | 1 + apps/web/src/components/chat/ProviderInstanceIcon.tsx | 9 +++++++-- apps/web/src/components/chat/ProviderModelPicker.tsx | 2 ++ docs/progress.md | 8 ++++++++ 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/ModelListRow.tsx b/apps/web/src/components/chat/ModelListRow.tsx index 74dae2dc2358..a483f93f417a 100644 --- a/apps/web/src/components/chat/ModelListRow.tsx +++ b/apps/web/src/components/chat/ModelListRow.tsx @@ -59,6 +59,7 @@ export const ModelListRow = memo(function ModelListRow(props: { - {isAcpRegistry ? ( + {props.modelSlug === "auto" ? ( + + ) : isAcpRegistry ? ( )} - {isCustomEndpoint ? null : props.showBadge ? ( + {isCustomEndpoint || props.modelSlug === "auto" ? null : props.showBadge ? ( Date: Thu, 12 Nov 2026 17:51:46 +0100 Subject: [PATCH 070/230] feat(web): pooled quota view with burn projection on Usage limits Every account of a provider adds into one pool (two Claude accounts = 200%). Each limits card now shows the summed headline, when the pool and the first account run out, the next reset, the burn rate, and a recorded and projected chart. Readings are kept in this browser to draw history and measure burn. --- .../usage/UsageLimitsPooled.browser.test.tsx | 52 ++++ .../components/usage/UsageLimitsPooled.tsx | 138 ++++++++-- .../src/components/usage/UsagePoolChart.tsx | 255 ++++++++++++++++++ .../src/components/usage/usagePoolHistory.ts | 64 +++++ packages/shared/package.json | 4 + .../shared/src/usagePoolProjection.test.ts | 144 ++++++++++ packages/shared/src/usagePoolProjection.ts | 179 ++++++++++++ 7 files changed, 813 insertions(+), 23 deletions(-) create mode 100644 apps/web/src/components/usage/UsagePoolChart.tsx create mode 100644 apps/web/src/components/usage/usagePoolHistory.ts create mode 100644 packages/shared/src/usagePoolProjection.test.ts create mode 100644 packages/shared/src/usagePoolProjection.ts diff --git a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx index ab114fbbd6f2..dc806b1341b2 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx @@ -63,3 +63,55 @@ describe("UsageLimitsPooled ChatGPT usage card", () => { .toBeVisible(); }); }); + +function claude(instanceId: string, displayName: string, weeklyUsed: number, resetsAt: string) { + return { + ...managedChatGpt(instanceId, displayName), + driver: ProviderDriverKind.make("claudeAgent"), + usageLimits: { + checkedAt, + windows: [ + { + id: "seven_day", + kind: "weekly" as const, + label: "Weekly", + usedPercent: weeklyUsed, + resetsAt, + windowDurationMins: 7 * 24 * 60, + }, + ], + }, + } satisfies ServerProvider; +} + +describe("UsageLimitsPooled pooled quota", () => { + it("adds the accounts into one pool and projects when it runs out", async () => { + const presentations = new Map([ + [ + EnvironmentId.make("desk"), + { + entry: { target: { label: "Desk" } }, + serverConfig: { + providers: [ + claude("claude_a", "Auto", 68, "2026-10-27T12:00:00.000Z"), + claude("claude_b", "Auto B", 27, "2026-10-31T13:00:00.000Z"), + ], + }, + }, + ], + ]); + await using screen = await render( + , + ); + + await expect.element(screen.getByText("105%", { exact: true })).toBeVisible(); + await expect.element(screen.getByText("of 200%")).toBeVisible(); + await expect.element(screen.getByText("Pool empty")).toBeVisible(); + await expect.element(screen.getByText("Burn, window avg")).toBeVisible(); + await expect + .element( + screen.getByRole("img", { name: "Weekly: pooled quota left, recorded and projected" }), + ) + .toBeVisible(); + }); +}); diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index 245b3021e4cd..6cce3e77e62f 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -12,6 +12,12 @@ import { type ResetCreditChoice, } from "@t3tools/shared/usageLimits"; import { T, useGT, useMessages } from "gt-react"; +import { + poolBurn, + projectionHorizon, + projectPool, + recordedPool, +} from "@t3tools/shared/usagePoolProjection"; import type { Popover as PopoverPrimitive } from "@base-ui/react/popover"; import { normalizeProviderAccentColor } from "@t3tools/client-runtime/state/provider-instance-display"; import { AlertTriangleIcon, ExternalLinkIcon, TicketIcon } from "lucide-react"; @@ -21,6 +27,7 @@ import { type ReactNode, type RefObject, use, + useEffect, useLayoutEffect, useRef, useState, @@ -42,9 +49,14 @@ import { collectExternalUsageLinks, collectLimitNotices, cursorUsageWindowDetails, + formatDuration, formatResetsIn, resetCreditChoices, } from "@t3tools/shared/usageLimitsCopy"; +import { UsagePoolChart } from "./UsagePoolChart"; +import { poolHistoryKey, readPoolHistory, recordPoolReadings } from "./usagePoolHistory"; + +const BURN_LOOKBACK_MS = 3 * 3_600_000; function accountInitials(email: string): string { const [local = "", domain = ""] = email.split("@"); @@ -589,47 +601,120 @@ function PoolBar({ ); } +function PoolStat({ label, children }: { readonly label: string; readonly children: ReactNode }) { + return ( +
+ {label} + {children} +
+ ); +} + function PoolWindowCard({ pool, + historyKey, color, now, label, description, }: { readonly pool: LimitPoolWindow; + readonly historyKey: string; readonly color: string; readonly now: number; readonly label?: string | null | undefined; readonly description?: string | undefined; }) { - const nextRefill = pool.resets.find((reset) => reset.restoresPercent > 0); + const gt = useGT(); + const m = useMessages(); + const timestampFormat = usePrimarySettings((settings) => settings.timestampFormat); + const samples = readPoolHistory(historyKey); + const horizon = projectionHorizon(pool); + const burn = poolBurn(pool, samples, now, BURN_LOOKBACK_MS); + const projection = projectPool(pool, now, { burnPerHour: burn.perHour, horizonMs: horizon }); + const from = now - horizon * 0.3; + const formatTime = (at: number) => + formatUpcomingTimestamp(new Date(at).toISOString(), timestampFormat, now, undefined, m); + const nextRefill = projection.refills[0]; + const firstEmpty = projection.firstEmpty + ? pool.members.find((member) => member.account.key === projection.firstEmpty?.accountKey) + : undefined; + const burnText = `${burn.perHour >= 10 ? Math.round(burn.perHour) : burn.perHour.toFixed(1)}%/h`; return ( -
-
- {label !== null ? ( - {label ?? pool.label} - ) : null} - - - {pool.remainingPercent}% - - - - left +
+
+
+ {label !== null ? ( + {label ?? pool.label} + ) : null} + + + {Math.round(projection.remaining)}% + + + + {gt("of {capacity}%", { + capacity: projection.capacity, + $context: "share of the pooled usage capacity", + })} + + {pool.pace ? : null} - {pool.pace ? : null} - - - {nextRefill && pool.columns.length > 1 ? ( - - ↻ +{nextRefill.restoresPercent}% - ) : null} +
+
+ + {projection.poolEmpty === null + ? gt("Not by {date}", { + date: new Date(now + horizon).toLocaleDateString([], { + month: "short", + day: "numeric", + }), + }) + : projection.poolEmpty <= now + ? gt("Empty now") + : formatTime(projection.poolEmpty)} + + + {firstEmpty && projection.firstEmpty ? ( + + {pool.members.length > 1 ? ( + + ) : null} + + {projection.firstEmpty.at <= now + ? gt("now", { $context: "an account is already empty" }) + : gt("in {duration}", { + duration: formatDuration(projection.firstEmpty.at - now, m), + })} + + + ) : ( + gt("None", { $context: "no account runs out" }) + )} + + + {nextRefill ? `+${Math.round(nextRefill.restores)}% ${formatTime(nextRefill.at)}` : "–"} + + + {burnText} + +
+ - {description ? ( -

{description}

- ) : null} + {description ?

{description}

: null}
); } @@ -658,6 +743,7 @@ function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: nu PopoverCreateHandle()); const segmentPopoverActions = useRef(null); const pools = collectLimitPools(collectLimitAccounts(presentations), now); + // Readings are stamped with each provider's checkedAt, so re-renders of the same data store + // nothing new. + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps this browser's localStorage reading history in step with the limits it has been shown + useEffect(() => { + recordPoolReadings(pools, now); + }, [pools, now]); const notices = collectLimitNotices(presentations, m); const externalLinks = collectExternalUsageLinks(presentations, m); return ( diff --git a/apps/web/src/components/usage/UsagePoolChart.tsx b/apps/web/src/components/usage/UsagePoolChart.tsx new file mode 100644 index 000000000000..9e753375a44c --- /dev/null +++ b/apps/web/src/components/usage/UsagePoolChart.tsx @@ -0,0 +1,255 @@ +import type { PoolProjection } from "@t3tools/shared/usagePoolProjection"; +import { T, useGT } from "gt-react"; +import { useId, useLayoutEffect, useRef, useState } from "react"; + +import { observeResize } from "../../lib/observeResize"; + +const HEIGHT = 190; +const PAD = { left: 44, right: 8, top: 22, bottom: 22 }; +const DAY = 86_400_000; +const HOUR = 3_600_000; + +type Point = { readonly at: number; readonly remaining: number }; + +function percent(value: number) { + return `${Math.round(value)}%`; +} + +function timeTicks(from: number, to: number): ReadonlyArray<{ at: number; label: string }> { + const span = to - from; + if (span > 2 * DAY) { + const every = Math.max(1, Math.ceil(span / DAY / 10)); + const start = new Date(from); + start.setHours(24, 0, 0, 0); + const ticks = []; + for (let at = start.getTime(); at < to; at += every * DAY) { + ticks.push({ + at: at + DAY / 2, + label: new Date(at).toLocaleDateString([], { weekday: "short", day: "numeric" }), + }); + } + return ticks; + } + const start = new Date(from); + start.setMinutes(60, 0, 0); + while (start.getHours() % 3 !== 0) start.setHours(start.getHours() + 1); + const ticks = []; + for (let at = start.getTime(); at < to; at += 3 * HOUR) { + ticks.push({ + at, + label: new Date(at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" }), + }); + } + return ticks; +} + +/** Drops a label that would overlap the one before it. */ +function spacedLabels(labels: readonly T[]): T[] { + const shown: T[] = []; + for (const label of labels) { + if (label.x - (shown.at(-1)?.x ?? -Infinity) >= 34) shown.push(label); + } + return shown; +} + +/** Pooled remaining quota: readings so far as a solid line, the projection dashed. */ +export function UsagePoolChart({ + color, + label, + recorded, + projection, + from, + to, + now, + formatTime, +}: { + readonly color: string; + readonly label: string; + readonly recorded: readonly Point[]; + readonly projection: PoolProjection; + readonly from: number; + readonly to: number; + readonly now: number; + readonly formatTime: (at: number) => string; +}) { + const gt = useGT(); + const box = useRef(null); + const [width, setWidth] = useState(0); + const [hover, setHover] = useState(null); + const gradient = useId(); + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- measures the container DOM width before paint and remeasures through a ResizeObserver + useLayoutEffect(() => { + const element = box.current; + if (!element) return; + const measure = () => setWidth(element.getBoundingClientRect().width); + measure(); + return observeResize(element, measure); + }, []); + + const cap = Math.max(100, projection.capacity); + const x = (at: number) => + PAD.left + ((at - from) / (to - from)) * Math.max(0, width - PAD.left - PAD.right); + const y = (value: number) => PAD.top + (HEIGHT - PAD.top - PAD.bottom) * (1 - value / cap); + const line = (points: readonly Point[]) => + points + .map((p, i) => `${i === 0 ? "M" : "L"}${x(p.at).toFixed(1)},${y(p.remaining).toFixed(1)}`) + .join(""); + const all = [...recorded, ...projection.points]; + const first = all[0]; + const last = all.at(-1); + const area = first && last ? `${line(all)}L${x(last.at)},${y(0)}L${x(first.at)},${y(0)}Z` : ""; + const start = projection.points[0]; + + const refillLabels = spacedLabels( + projection.refills.map((refill) => ({ ...refill, x: x(refill.at) })), + ); + + const pick = (clientX: number) => { + const rect = box.current?.getBoundingClientRect(); + if (!rect || all.length === 0) return; + const at = + from + ((clientX - rect.left - PAD.left) / (width - PAD.left - PAD.right)) * (to - from); + setHover( + all.reduce((best, p) => (Math.abs(p.at - at) < Math.abs(best.at - at) ? p : best), all[0]!), + ); + }; + + return ( +
+ {width > 0 ? ( + pick(event.clientX)} + onPointerLeave={() => setHover(null)} + > + + + + + + + {[0, cap / 2, cap].map((value) => ( + + + + {percent(value)} + + + ))} + {timeTicks(from, to).map((tick) => ( + + {tick.label} + + ))} + + {recorded.length > 0 && start ? ( + + ) : null} + + {refillLabels.map((refill) => ( + + +{percent(refill.restores)} + + ))} + + + Now + + {start ? ( + + ) : null} + {projection.poolEmpty !== null && projection.poolEmpty > now ? ( + + + + {gt("Empty {time}", { + time: formatTime(projection.poolEmpty), + $context: "when the usage pool runs out", + })} + + + ) : null} + {hover ? : null} + + ) : null} + {hover ? ( +
+
+ {formatTime(hover.at)} + {hover.at > now ? ` · ${gt("projected", { $context: "a forecast value" })}` : ""} +
+
+ {percent(hover.remaining)} of {percent(projection.capacity)} +
+
+ ) : null} +
+ ); +} diff --git a/apps/web/src/components/usage/usagePoolHistory.ts b/apps/web/src/components/usage/usagePoolHistory.ts new file mode 100644 index 000000000000..3780d4e6af53 --- /dev/null +++ b/apps/web/src/components/usage/usagePoolHistory.ts @@ -0,0 +1,64 @@ +import type { LimitPool, LimitPoolWindow } from "@t3tools/shared/usageLimits"; +import type { PoolSample } from "@t3tools/shared/usagePoolProjection"; +import * as Schema from "effect/Schema"; + +import { getLocalStorageItem, setLocalStorageItem } from "../../hooks/useLocalStorage"; + +// Providers report limits only as a current percentage, so this browser keeps the readings it +// has seen to draw the recorded line and measure burn. +const STORAGE_KEY = "t3code:usage-pool-history:v1"; +const KEEP_MS = 14 * 24 * 3_600_000; +const MIN_GAP_MS = 4 * 60_000; + +const Sample = Schema.Struct({ + at: Schema.Number, + used: Schema.Record(Schema.String, Schema.Number), +}); +const History = Schema.Record(Schema.String, Schema.Array(Sample)); +type History = typeof History.Type; + +export function poolHistoryKey(pool: LimitPool, window: LimitPoolWindow): string { + return `${pool.driver}:${window.kind}:${window.id}`; +} + +function read(): History { + try { + return getLocalStorageItem(STORAGE_KEY, History) ?? {}; + } catch { + return {}; + } +} + +export function readPoolHistory(key: string): readonly PoolSample[] { + return read()[key] ?? []; +} + +/** Stores one reading per window, stamped with when the provider was checked. */ +export function recordPoolReadings(pools: readonly LimitPool[], now: number): void { + const history: Record = { ...read() }; + let changed = false; + for (const pool of pools) { + for (const window of pool.windows) { + const checked = window.members + .map((member) => Date.parse(member.account.limits.checkedAt)) + .filter(Number.isFinite); + if (checked.length === 0) continue; + const at = Math.min(now, Math.max(...checked)); + const key = poolHistoryKey(pool, window); + const samples = (history[key] ?? []).filter((sample) => sample.at >= now - KEEP_MS); + const last = samples.at(-1); + if (last && at - last.at < MIN_GAP_MS) continue; + const used = Object.fromEntries( + window.members.map((member) => [member.account.key, member.window.usedPercent]), + ); + history[key] = [...samples, { at, used }]; + changed = true; + } + } + if (!changed) return; + try { + setLocalStorageItem(STORAGE_KEY, history, History); + } catch (error) { + console.error("Could not save usage limit readings.", error); + } +} diff --git a/packages/shared/package.json b/packages/shared/package.json index ec663c437ffa..9d6ce207a274 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -419,6 +419,10 @@ "types": "./src/usageLimits.ts", "import": "./src/usageLimits.ts" }, + "./usagePoolProjection": { + "types": "./src/usagePoolProjection.ts", + "import": "./src/usagePoolProjection.ts" + }, "./desktopAppControl": { "types": "./src/desktopAppControl.ts", "import": "./src/desktopAppControl.ts" diff --git a/packages/shared/src/usagePoolProjection.test.ts b/packages/shared/src/usagePoolProjection.test.ts new file mode 100644 index 000000000000..79ccd0905a18 --- /dev/null +++ b/packages/shared/src/usagePoolProjection.test.ts @@ -0,0 +1,144 @@ +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; + +import type { LimitPoolWindow } from "./usageLimits.ts"; +import { poolBurn, projectionHorizon, projectPool, recordedPool } from "./usagePoolProjection.ts"; + +const HOUR = 3_600_000; +const now = Date.parse("2026-11-12T12:00:00.000Z"); +const iso = (at: number) => DateTime.formatIso(DateTime.makeUnsafe(at)); + +function pool( + members: ReadonlyArray<{ key: string; used: number; resetsIn?: number; mins?: number }>, + kind: LimitPoolWindow["kind"] = "weekly", +): LimitPoolWindow { + const list = members.map((m) => ({ + account: { key: m.key } as LimitPoolWindow["members"][number]["account"], + window: { + id: "seven_day", + kind, + label: "Weekly", + usedPercent: m.used, + ...(m.resetsIn === undefined ? {} : { resetsAt: iso(now + m.resetsIn) }), + windowDurationMins: m.mins ?? 7 * 24 * 60, + }, + refillPercent: m.used, + })); + return { + id: "seven_day", + kind, + label: "Weekly", + members: list, + columns: list, + remainingPercent: 0, + usedPercent: 0, + pace: null, + resets: [], + }; +} + +describe("projectPool", () => { + it("sums every account into one pool", () => { + const projection = projectPool( + pool([ + { key: "a", used: 60, resetsIn: 48 * HOUR }, + { key: "b", used: 30, resetsIn: 120 * HOUR }, + ]), + now, + { burnPerHour: 0, horizonMs: 7 * 24 * HOUR }, + ); + expect(projection.capacity).toBe(200); + expect(projection.remaining).toBe(110); + expect(projection.poolEmpty).toBeNull(); + // With no spend, each reset gives back what that account had used. + expect(projection.refills.map((r) => [r.accountKey, r.restores, r.remainingAfter])).toEqual([ + ["a", 60, 170], + ["b", 30, 200], + ]); + expect(projection.points.at(-1)?.remaining).toBe(200); + }); + + it("spends the account that resets first and finds when the pool runs dry", () => { + const projection = projectPool( + pool([ + { key: "late", used: 0, resetsIn: 150 * HOUR }, + { key: "soon", used: 50, resetsIn: 140 * HOUR }, + ]), + now, + { burnPerHour: 10, horizonMs: 24 * HOUR, steps: 240 }, + ); + // 50 points left on "soon" at 10/h: empty after 5 h; then 100 on "late": pool dry at 15 h. + expect(projection.firstEmpty).toEqual({ at: now + 5 * HOUR, accountKey: "soon" }); + expect(projection.poolEmpty).toBe(now + 15 * HOUR); + }); + + it("reports an exhausted account as empty now", () => { + const projection = projectPool( + pool([ + { key: "a", used: 100, resetsIn: HOUR }, + { key: "b", used: 0, resetsIn: 5 * HOUR }, + ]), + now, + { burnPerHour: 0, horizonMs: 24 * HOUR }, + ); + expect(projection.firstEmpty).toEqual({ at: now, accountKey: "a" }); + expect(projection.poolEmpty).toBeNull(); + }); +}); + +describe("poolBurn", () => { + const twoAccounts = pool([ + { key: "a", used: 35, resetsIn: 100 * HOUR }, + { key: "b", used: 5, resetsIn: 100 * HOUR }, + ]); + + it("measures spend from stored readings and counts a drop as a reset", () => { + const burn = poolBurn( + twoAccounts, + [ + { at: now - 2 * HOUR, used: { a: 10, b: 90 } }, + { at: now - HOUR, used: { a: 20, b: 100 } }, + { at: now, used: { a: 35, b: 5 } }, + ], + now, + 3 * HOUR, + ); + // a: +10 +15, b: +10 then a reset worth 5 → 40 points over 2 h. + expect(burn).toEqual({ perHour: 20, source: "measured" }); + }); + + it("falls back to the average since each window opened", () => { + // Weekly windows with 100 h left have run 68 h: 35/68 + 5/68 points per hour. + const burn = poolBurn(twoAccounts, [{ at: now, used: { a: 35, b: 5 } }], now, 3 * HOUR); + expect(burn.source).toBe("window"); + expect(burn.perHour).toBeCloseTo(40 / 68, 6); + }); +}); + +describe("recordedPool", () => { + it("carries an account's last reading forward", () => { + const series = recordedPool( + pool([ + { key: "a", used: 0 }, + { key: "b", used: 0 }, + ]), + [ + { at: now - 3 * HOUR, used: { a: 10 } }, + { at: now - 2 * HOUR, used: { a: 20, b: 50 } }, + { at: now - HOUR, used: { b: 60 } }, + ], + now - 24 * HOUR, + ); + expect(series).toEqual([ + { at: now - 2 * HOUR, remaining: 130 }, + { at: now - HOUR, remaining: 120 }, + ]); + }); +}); + +describe("projectionHorizon", () => { + it("looks a day ahead for session windows and a week for weekly ones", () => { + expect(projectionHorizon(pool([{ key: "a", used: 0, mins: 300 }], "session"))).toBe(24 * HOUR); + expect(projectionHorizon(pool([{ key: "a", used: 0 }]))).toBe(7 * 24 * HOUR); + }); +}); diff --git a/packages/shared/src/usagePoolProjection.ts b/packages/shared/src/usagePoolProjection.ts new file mode 100644 index 000000000000..b157ac57fac5 --- /dev/null +++ b/packages/shared/src/usagePoolProjection.ts @@ -0,0 +1,179 @@ +/** + * Pooled quota projection: every account of a provider counts toward one pool (two Claude + * subscriptions = 200%). The pool drains at the current burn rate, spending the account that + * resets first, and each account refills when its window resets. + */ +import type { LimitPoolWindow } from "./usageLimits.ts"; + +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; +const DAY = 24 * HOUR; +/** Measured burn needs at least this much history; shorter spans are mostly noise. */ +const MIN_MEASURED_SPAN = 15 * MINUTE; + +/** One reading of a pool: used percent per account key. */ +export interface PoolSample { + readonly at: number; + readonly used: Readonly>; +} + +interface PoolBurn { + /** Percentage points of the pool spent per hour. */ + readonly perHour: number; + /** "measured" comes from stored readings, "window" from the average since each window opened. */ + readonly source: "measured" | "window"; +} + +export interface PoolProjection { + readonly capacity: number; + readonly remaining: number; + readonly points: ReadonlyArray<{ readonly at: number; readonly remaining: number }>; + readonly refills: ReadonlyArray<{ + readonly at: number; + readonly accountKey: string; + /** Percentage points this reset gives back. */ + readonly restores: number; + /** Pool remaining right after the reset. */ + readonly remainingAfter: number; + }>; + readonly firstEmpty: { readonly at: number; readonly accountKey: string } | null; + readonly poolEmpty: number | null; +} + +const clampUsed = (value: number) => Math.max(0, Math.min(100, value)); + +function resetAt(resetsAt: string | undefined): number | null { + if (resetsAt === undefined) return null; + const at = Date.parse(resetsAt); + return Number.isFinite(at) ? at : null; +} + +/** How far ahead to project: a day for session windows, otherwise one full window. */ +export function projectionHorizon(pool: LimitPoolWindow): number { + const longest = Math.max(0, ...pool.members.map((m) => m.window.windowDurationMins ?? 0)); + if (pool.kind === "session" || (longest > 0 && longest <= 12 * 60)) return DAY; + if (pool.kind === "monthly" || longest >= 28 * 24 * 60) return 31 * DAY; + return 7 * DAY; +} + +function windowAverageBurn(pool: LimitPoolWindow, now: number): number { + let perHour = 0; + for (const { window } of pool.members) { + const at = resetAt(window.resetsAt); + if (at === null || !window.windowDurationMins) continue; + const elapsed = window.windowDurationMins * MINUTE - (at - now); + if (elapsed >= MIN_MEASURED_SPAN) perHour += clampUsed(window.usedPercent) / (elapsed / HOUR); + } + return perHour; +} + +/** + * Burn over the last `lookbackMs` from stored readings. A drop between readings means the + * window reset, so the new value counts as fresh spend. Falls back to the window average while + * the readings span less than 15 minutes. + */ +export function poolBurn( + pool: LimitPoolWindow, + samples: readonly PoolSample[], + now: number, + lookbackMs: number, +): PoolBurn { + const recent = samples.filter((sample) => sample.at >= now - lookbackMs && sample.at <= now); + const first = recent[0]; + const last = recent.at(-1); + if (!first || !last || last.at - first.at < MIN_MEASURED_SPAN) { + return { perHour: windowAverageBurn(pool, now), source: "window" }; + } + let spent = 0; + for (const { account } of pool.members) { + let previous: number | undefined; + for (const sample of recent) { + const used = sample.used[account.key]; + if (used === undefined) continue; + if (previous !== undefined) spent += used >= previous ? used - previous : used; + previous = used; + } + } + return { perHour: spent / ((last.at - first.at) / HOUR), source: "measured" }; +} + +export function projectPool( + pool: LimitPoolWindow, + now: number, + options: { readonly burnPerHour: number; readonly horizonMs: number; readonly steps?: number }, +): PoolProjection { + const accounts = pool.members.map((member) => ({ + key: member.account.key, + used: clampUsed(member.window.usedPercent), + reset: resetAt(member.window.resetsAt), + length: (member.window.windowDurationMins ?? 0) * MINUTE, + })); + const remainingNow = () => accounts.reduce((sum, account) => sum + 100 - account.used, 0); + const capacity = accounts.length * 100; + const remaining = remainingNow(); + const points = [{ at: now, remaining }]; + const refills: Array = []; + const exhausted = accounts.find((account) => account.used >= 100); + let firstEmpty = exhausted ? { at: now, accountKey: exhausted.key } : null; + let poolEmpty = accounts.length > 0 && remaining <= 0 ? now : null; + const steps = options.steps ?? 480; + const step = options.horizonMs / steps; + + for (let index = 1; index <= steps; index += 1) { + const at = now + index * step; + for (const account of accounts) { + while (account.reset !== null && account.reset <= at) { + const restores = account.used; + account.used = 0; + if (restores > 0.5) { + refills.push({ + at: account.reset, + accountKey: account.key, + restores, + remainingAfter: remainingNow(), + }); + } + account.reset = account.length > 0 ? account.reset + account.length : null; + } + } + let drain = (options.burnPerHour * step) / HOUR; + const spendable = accounts + .filter((account) => account.used < 100) + .sort((left, right) => (left.reset ?? Infinity) - (right.reset ?? Infinity)); + for (const account of spendable) { + if (drain <= 0) break; + // An unused window opens on first spend. + if (account.reset === null && account.used === 0 && account.length > 0) { + account.reset = at + account.length; + } + const take = Math.min(drain, 100 - account.used); + account.used += take; + drain -= take; + if (account.used >= 100 && firstEmpty === null) firstEmpty = { at, accountKey: account.key }; + } + const left = remainingNow(); + if (left <= 1e-6 && poolEmpty === null) poolEmpty = at; + points.push({ at, remaining: left }); + } + return { capacity, remaining, points, refills, firstEmpty, poolEmpty }; +} + +/** Pool remaining at each stored reading since `from`, carrying an account's last value forward. */ +export function recordedPool( + pool: LimitPoolWindow, + samples: readonly PoolSample[], + from: number, +): ReadonlyArray<{ readonly at: number; readonly remaining: number }> { + const keys = pool.members.map((member) => member.account.key); + const last: Record = {}; + const series: Array<{ at: number; remaining: number }> = []; + for (const sample of samples) { + for (const key of keys) { + const used = sample.used[key]; + if (used !== undefined) last[key] = clampUsed(used); + } + if (sample.at < from || keys.some((key) => last[key] === undefined)) continue; + series.push({ at: sample.at, remaining: keys.reduce((sum, key) => sum + 100 - last[key]!, 0) }); + } + return series; +} From 09525763d85c7d4866140c2e1c8ee4d9981001cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 12:44:18 +0100 Subject: [PATCH 071/230] Show the model and account Auto routes to in the model picker --- .../chat/ComposerFooterControls.tsx | 3 + .../components/chat/ModelPickerContent.tsx | 9 ++- .../components/chat/ProviderInstanceIcon.tsx | 21 ++++-- .../components/chat/ProviderModelPicker.tsx | 38 +++++++--- .../web/src/components/chat/autoRoute.test.ts | 75 +++++++++++++++++++ apps/web/src/components/chat/autoRoute.ts | 54 +++++++++++++ docs/progress.md | 7 ++ 7 files changed, 191 insertions(+), 16 deletions(-) create mode 100644 apps/web/src/components/chat/autoRoute.test.ts create mode 100644 apps/web/src/components/chat/autoRoute.ts diff --git a/apps/web/src/components/chat/ComposerFooterControls.tsx b/apps/web/src/components/chat/ComposerFooterControls.tsx index 1df9cdbd3233..e3c829c98942 100644 --- a/apps/web/src/components/chat/ComposerFooterControls.tsx +++ b/apps/web/src/components/chat/ComposerFooterControls.tsx @@ -320,6 +320,9 @@ export function ComposerModelPicker({ return ( ; onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; lockedProvider: ProviderDriverKind | null; @@ -876,6 +879,7 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { modelJumpLabelByKey, activeModelKey, selectedModelKeySet, + autoRouteLabel: props.autoRoute?.label, }; const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { @@ -1189,15 +1193,16 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { } const disabledReason = getModelDisabledReason?.(model.instanceId, model.slug) ?? null; + const autoRoute = model.slug === "auto" ? props.autoRoute : null; return ( - {props.modelSlug === "auto" ? ( - - ) : isAcpRegistry ? ( + {isAcpRegistry ? ( )} - {isCustomEndpoint || props.modelSlug === "auto" ? null : props.showBadge ? ( + {isCustomEndpoint ? null : props.modelSlug === "auto" ? ( + // Auto keeps the logo of the provider it routes to and marks it with a route badge. + + + + ) : props.showBadge ? ( ; onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; lockedProvider: ProviderDriverKind | null; @@ -130,6 +135,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { footer?: ReactNode; }) { const composerFloatingLayerProps = useComposerMenuProps(); + const nowMinute = useNowMinute(); const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false); const isMenuOpen = props.open ?? uncontrolledIsMenuOpen; const registry = useContext(RegistryContext); @@ -172,16 +178,29 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { (activeEntry?.driverKind === "opencode" || activeEntry?.driverKind === "antigravity" ? undefined : selectedInstanceOptions[0]); - const triggerTitle = selectedModel - ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) - : props.model === ANTIGRAVITY_DEFAULT_MODEL - ? gt("Choose model") - : props.model || gt("Choose model"); + const isAuto = props.model === "auto"; + // Names the model Auto would pick now, at this selection's level (default level elsewhere). + const autoRoute = describeAutoRoute({ + entries: props.instanceEntries, + ...(isAuto && props.modelSelectionOptions ? { options: props.modelSelectionOptions } : {}), + now: Date.parse(nowMinute), + }); + const triggerTitle = + isAuto && autoRoute + ? `Auto · ${autoRoute.label}` + : selectedModel + ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) + : props.model === ANTIGRAVITY_DEFAULT_MODEL + ? gt("Choose model") + : props.model || gt("Choose model"); const withUnavailable = (model: string, isUnavailable: boolean | undefined) => isUnavailable ? gt("{model} (Unavailable)", { model }) : model; - const triggerLabel = selectedModel - ? withUnavailable(getDisplayModelName(selectedModel), selectedModel.isUnavailable) - : triggerTitle; + const triggerLabel = + isAuto && autoRoute + ? triggerTitle + : selectedModel + ? withUnavailable(getDisplayModelName(selectedModel), selectedModel.isUnavailable) + : triggerTitle; const showInstanceBadge = activeEntry !== null && shouldShowInstanceBadge(activeEntry, props.instanceEntries); @@ -297,6 +316,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { workspaceCwd={props.workspaceCwd ?? null} activeInstanceId={activeInstanceId} model={props.model} + autoRoute={autoRoute} {...(props.selectedModels !== undefined ? { selectedModels: props.selectedModels } : {})} {...(props.onToggleModel ? { @@ -417,7 +437,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { // Narrow compacted composers hide the provider icon before truncating the name. , + usedPercent: number, +): ServerProvider { + return { + instanceId: ProviderInstanceId.make(id), + driver: ProviderDriverKind.make(driver), + displayName, + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-11-13T11:00:00.000Z", + models: models.map((model) => ({ ...model, isCustom: false, capabilities: null })), + slashCommands: [], + skills: [], + usageLimits: { + windows: [ + { + id: "five_hour", + kind: "session", + label: "Session", + usedPercent, + resetsAt: "2026-11-13T15:00:00.000Z", + }, + ], + }, + } as unknown as ServerProvider; +} + +const claudeModels = [ + { slug: "claude-fable-5-2", name: "Claude Fable 5.2" }, + { slug: "claude-opus-5-5", name: "Claude Opus 5.5" }, + { slug: "claude-sonnet-5-5", name: "Claude Sonnet 5.5" }, + { slug: "auto", name: "Auto" }, +]; + +describe("describeAutoRoute", () => { + it("names the Claude model and account Auto would use", () => { + const entries = deriveProviderInstanceEntries([ + provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 70), + provider("claudeAutoB", "Auto B", "claudeAgent", claudeModels, 10), + ]); + const medium = describeAutoRoute({ entries, now }); + expect(medium?.driverKind).toBe("claudeAgent"); + expect(medium?.label).toMatch(/^.*Opus 5\.5 \(B\)$/); + + const high = describeAutoRoute({ entries, options: [{ id: "effort", value: "high" }], now }); + expect(high?.label).toMatch(/Fable 5\.2 \(B\)$/); + }); + + it("names another provider when both Claude accounts are used up", () => { + const entries = deriveProviderInstanceEntries([ + provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 100), + provider("claudeAutoB", "Auto B", "claudeAgent", claudeModels, 100), + provider("grok", "Grok Build", "grok", [{ slug: "grok-4.7", name: "Grok 4.7" }], 0), + ]); + expect(describeAutoRoute({ entries, now })).toMatchObject({ + driverKind: "grok", + label: expect.stringMatching(/Grok 4\.7 \(Grok Build\)$/), + }); + }); +}); diff --git a/apps/web/src/components/chat/autoRoute.ts b/apps/web/src/components/chat/autoRoute.ts new file mode 100644 index 000000000000..d1a89457bf7f --- /dev/null +++ b/apps/web/src/components/chat/autoRoute.ts @@ -0,0 +1,54 @@ +import { + ProviderInstanceId, + type ModelSelection, + type ProviderDriverKind, +} from "@t3tools/contracts"; +import { resolveAutoModelSelection } from "@t3tools/shared/autoModel"; + +import type { ProviderInstanceEntry } from "../../providerInstances"; +import { getTriggerDisplayModelName } from "./providerIconUtils"; + +/** What the `auto` model would run as right now, for labels such as "Auto · Opus 5.5 (B)". */ +export interface AutoRoute { + readonly driverKind: ProviderDriverKind; + /** The concrete model and its account, such as "Opus 5.5 (B)". */ + readonly label: string; +} + +/** + * Mirrors the server's routing (same resolver, same live usage snapshots), so the picker shows + * the model a new message would get. The server still decides per message; a thread already on + * a model may stay on it. + */ +export function describeAutoRoute(input: { + readonly entries: ReadonlyArray; + readonly options?: ModelSelection["options"]; + readonly now: number; +}): AutoRoute | null { + const resolution = resolveAutoModelSelection({ + selection: { + instanceId: ProviderInstanceId.make("auto"), + model: "auto", + ...(input.options ? { options: input.options } : {}), + }, + providers: input.entries.map((entry) => entry.snapshot), + now: input.now, + }); + if (!resolution) return null; + const entry = input.entries.find( + (candidate) => candidate.instanceId === resolution.selection.instanceId, + ); + const model = entry?.models.find((candidate) => candidate.slug === resolution.selection.model); + if (!entry || !model) return null; + // Claude instances are named "Auto" (account A) and "Auto B"; other providers keep their name. + const account = + entry.driverKind === "claudeAgent" + ? /\bB$/.test(entry.displayName) + ? "B" + : "A" + : entry.displayName; + return { + driverKind: entry.driverKind, + label: `${getTriggerDisplayModelName(model, entry.driverKind)} (${account})`, + }; +} diff --git a/docs/progress.md b/docs/progress.md index 46c2223b1d5c..3ba9579db6ab 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -16,3 +16,10 @@ - How: `ProviderInstanceIcon` takes an optional `modelSlug`; `ModelListRow` and `ProviderModelPicker` pass it. Lint rules ruled out Sparkles and raw palette colors. - Deploy: web-only, so the new `apps/web/dist` was copied into `apps/server/dist/client`; no service restart. The web build took ~45 min on the hub (disk-bound). - Next: keep "Auto" shown in the composer after the first message (needs the thread to remember the Auto selection). + +## 2026-11-13 — Auto shows the model it routes to + +- What: the `auto` entry keeps the logo of the provider it routes to (the Claude logo while Claude has room) with a small route badge, and its label names the model and account, e.g. "Auto · Opus 5.5 (B)", in the picker rows and on the composer button. +- Why: Tomáš wanted to see which Claude model Auto uses; the plain route icon hid it. +- How: `describeAutoRoute` (web) runs the server's `resolveAutoModelSelection` on the client's provider snapshots, at the composer's Auto level, on a minute clock. The server still decides per message (a thread may stay on its current model until 90% used). +- Tests: `autoRoute.test.ts` (2 tests: A/B pick per level, fallback to Grok). The test run alone took ~14 min on the hub. From 73748e541f1f397748171158dcba27f3e333ddea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 13:03:44 +0100 Subject: [PATCH 072/230] Auto routes Claude A/B by 5-hour use and weekly reset, adds Antigravity, lists levels as picker rows Between Claude accounts, Auto takes the freer 5-hour window; within 10 points it spends the account whose weekly quota resets first. Antigravity's Claude models follow the Claude subscriptions at every level. auto-low/auto-medium/auto-high fix the level in the slug so the Auto picker tab lists one row per level. Usage limits open with a per-subscription overview. --- .../components/chat/ModelPickerContent.tsx | 13 ++- .../components/chat/ProviderInstanceIcon.tsx | 3 +- .../components/chat/ProviderModelPicker.tsx | 12 ++- apps/web/src/components/chat/autoRoute.ts | 4 +- .../components/usage/UsageLimitsPooled.tsx | 55 +++++++++++++ docs/progress.md | 8 ++ packages/shared/src/autoModel.test.ts | 79 ++++++++++++++++++- packages/shared/src/autoModel.ts | 68 +++++++++++++--- 8 files changed, 223 insertions(+), 19 deletions(-) diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index 6f1afc2ff352..da1e18469547 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -45,6 +45,7 @@ import { ComboboxListVirtualized, } from "../ui/combobox"; import { ModelEsque } from "./providerIconUtils"; +import { isAutoModelSlug } from "@t3tools/shared/autoModel"; import type { AutoRoute } from "./autoRoute"; import { isCommandPaletteOpen } from "../../commandPaletteBus"; import { registerModelPickerContent } from "../../modelPickerVisibility"; @@ -339,8 +340,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { workspaceCwd?: string | null; activeInstanceId: ProviderInstanceId; model: string; - /** What the `auto` model routes to right now; its rows show it. */ - autoRoute?: AutoRoute | null; + /** What an Auto model row (`auto`, `auto-low`, ...) routes to right now; its row shows it. */ + autoRouteFor?: (slug: string) => AutoRoute | null; selectedModels?: ReadonlyArray<{ instanceId: ProviderInstanceId; model: string }>; onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; lockedProvider: ProviderDriverKind | null; @@ -879,7 +880,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { modelJumpLabelByKey, activeModelKey, selectedModelKeySet, - autoRouteLabel: props.autoRoute?.label, + autoRouteLabels: ["auto", "auto-low", "auto-medium", "auto-high"] + .map((slug) => props.autoRouteFor?.(slug)?.label ?? "") + .join("|"), }; const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { @@ -1193,7 +1196,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { } const disabledReason = getModelDisabledReason?.(model.instanceId, model.slug) ?? null; - const autoRoute = model.slug === "auto" ? props.autoRoute : null; + const autoRoute = isAutoModelSlug(model.slug) + ? (props.autoRouteFor?.(model.slug) ?? null) + : null; return ( )} - {isCustomEndpoint ? null : props.modelSlug === "auto" ? ( + {isCustomEndpoint ? null : isAutoModelSlug(props.modelSlug) ? ( // Auto keeps the logo of the provider it routes to and marks it with a route badge. + describeAutoRoute({ entries: props.instanceEntries, model: slug, now }); const triggerTitle = isAuto && autoRoute ? `Auto · ${autoRoute.label}` @@ -316,7 +322,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { workspaceCwd={props.workspaceCwd ?? null} activeInstanceId={activeInstanceId} model={props.model} - autoRoute={autoRoute} + autoRouteFor={autoRouteFor} {...(props.selectedModels !== undefined ? { selectedModels: props.selectedModels } : {})} {...(props.onToggleModel ? { diff --git a/apps/web/src/components/chat/autoRoute.ts b/apps/web/src/components/chat/autoRoute.ts index d1a89457bf7f..eff72e2a9e71 100644 --- a/apps/web/src/components/chat/autoRoute.ts +++ b/apps/web/src/components/chat/autoRoute.ts @@ -22,13 +22,15 @@ export interface AutoRoute { */ export function describeAutoRoute(input: { readonly entries: ReadonlyArray; + /** `auto`, or a fixed-level `auto-low` / `auto-medium` / `auto-high`. */ + readonly model?: string; readonly options?: ModelSelection["options"]; readonly now: number; }): AutoRoute | null { const resolution = resolveAutoModelSelection({ selection: { instanceId: ProviderInstanceId.make("auto"), - model: "auto", + model: input.model ?? "auto", ...(input.options ? { options: input.options } : {}), }, providers: input.entries.map((entry) => entry.snapshot), diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index 6cce3e77e62f..d0c3e5f43f99 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -755,6 +755,60 @@ function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: nu ); } +/** One row per subscription: every window it reports, so no account hides inside a pool. */ +function SubscriptionsOverview({ + pools, + now, +}: { + readonly pools: readonly LimitPool[]; + readonly now: number; +}) { + const rows = pools.flatMap((pool) => pool.accounts.map((account) => ({ pool, account }))); + if (rows.length === 0) return null; + return ( +
+

+ Subscriptions +

+
+ {rows.map(({ pool, account }) => ( +
+ + + + + {account.limits.windows.map((window) => { + const resetsIn = formatResetsIn(window, now); + return ( + + {window.label} + {remainingPercent(window)}% + {resetsIn ? {resetsIn.replace("resets in ", "↻ ")} : null} + + ); + })} +
+ ))} +
+
+ ); +} + export function UsageLimitsPooled({ presentations, now, @@ -782,6 +836,7 @@ export function UsageLimitsPooled({ No provider on the selected environments reports subscription limits.

) : null} + {pools.map((pool) => ( diff --git a/docs/progress.md b/docs/progress.md index 3ba9579db6ab..1a91af83a5bb 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -23,3 +23,11 @@ - Why: Tomáš wanted to see which Claude model Auto uses; the plain route icon hid it. - How: `describeAutoRoute` (web) runs the server's `resolveAutoModelSelection` on the client's provider snapshots, at the composer's Auto level, on a minute clock. The server still decides per message (a thread may stay on its current model until 90% used). - Tests: `autoRoute.test.ts` (2 tests: A/B pick per level, fallback to Grok). The test run alone took ~14 min on the hub. + +## 2026-11-13: Auto routes by 5-hour use and weekly reset; Auto levels as picker rows; subscriptions overview + +- What: Auto now picks between Claude accounts by the freer 5-hour window; when two accounts are within 10 points, it spends the one whose weekly quota resets first (unused quota is lost at reset). Antigravity's Claude models (Opus 4.6 Thinking, Sonnet 4.6) sit right after the Claude subscriptions in every level. `auto-low` / `auto-medium` / `auto-high` fix the level in the model slug, so the Auto tab in the picker lists one row per level, each naming its current route. Usage → Limits opens with a Subscriptions table: one row per account with every window's remaining % and reset. +- Why: Tomáš wants Auto to always use Claude A/B first and route by 5-hour room and weekly expiry, use the Antigravity subscription too, show its levels like other models, and see each subscription next to the pooled view. +- Numbers: autoModel tests 9/9 (3 new routing cases failed before the change, plus a level-slug test). Web typecheck clean in 47 s warm. +- What worked: the Limits page showed Claude and distinct A/B numbers once the hub was quiet. The missing Claude section and copied numbers came from limit probes timing out while the hub was overloaded (load 11, IO pressure ~90). +- Next: one combined web + server build, deployed with a stop/start of t3code.service, then settings switch the Auto tab to the three level rows. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index e7846c214e74..eda559c93c55 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { AUTO_LEVEL_DESCRIPTOR, resolveAutoModelSelection } from "./autoModel.ts"; +import { AUTO_LEVEL_DESCRIPTOR, isAutoModelSlug, resolveAutoModelSelection } from "./autoModel.ts"; const now = Date.parse("2026-11-12T12:00:00.000Z"); const resetsAt = "2026-11-12T15:00:00.000Z"; @@ -58,6 +58,18 @@ function claude(id: string, usedPercent: number, autoAware = true): ServerProvid } as unknown as ServerProvider; } +function withWeekly(provider: ServerProvider, usedPercent: number, weeklyResetsAt: string) { + return { + ...provider, + usageLimits: { + windows: [ + ...(provider.usageLimits?.windows ?? []), + { id: "seven_day", kind: "weekly", label: "Weekly", usedPercent, resetsAt: weeklyResetsAt }, + ], + }, + } as unknown as ServerProvider; +} + const auto = (level?: string): ModelSelection => ({ instanceId: ProviderInstanceId.make("claudeAuto"), model: "auto", @@ -125,6 +137,71 @@ describe("resolveAutoModelSelection", () => { }); }); + it("routes to the account with less of its 5-hour window used", () => { + // A has the busier week but a nearly unused 5-hour window, so it can take work right now. + const providers = [ + withWeekly(claude("claudeAutoB", 50), 20, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 10), 60, "2026-11-18T12:00:00.000Z"), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, + ).toBe("claudeAuto"); + }); + + it("with similar 5-hour use, spends the account whose weekly limit resets first", () => { + // B has slightly less 5-hour use, but A's unused weekly quota is gone tomorrow. + const providers = [ + withWeekly(claude("claudeAutoB", 25), 40, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 30), 40, "2026-11-13T12:00:00.000Z"), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, + ).toBe("claudeAuto"); + }); + + it("falls back to Claude on the Antigravity subscription before other providers", () => { + const antigravity = { + ...claude("antigravity", 0, false), + driver: ProviderDriverKind.make("antigravity"), + models: ["claude-opus-4-6-thinking", "claude-sonnet-4-6"].map((slug) => ({ + slug, + name: slug, + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "thinking_level", + label: "Thinking", + type: "select" as const, + options: ["low", "medium", "high"].map((id) => ({ id, label: id })), + }, + ], + }, + })), + } as unknown as ServerProvider; + const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100), antigravity]; + expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection).toEqual({ + instanceId: "antigravity", + model: "claude-opus-4-6-thinking", + options: [{ id: "thinking_level", value: "medium" }], + }); + }); + + it("reads the level from auto-low / auto-medium / auto-high", () => { + const providers = [claude("claudeAuto", 10)]; + const pick = (model: string) => + resolveAutoModelSelection({ + selection: { instanceId: ProviderInstanceId.make("claudeAuto"), model }, + providers, + now, + })?.selection.model; + expect(pick("auto-high")).toBe("claude-fable-5-2"); + expect(pick("auto-medium")).toBe("claude-opus-5-5"); + expect(pick("auto-low")).toBe("claude-sonnet-5-5"); + expect(isAutoModelSlug("auto-low")).toBe(true); + expect(isAutoModelSlug("auto-max")).toBe(false); + }); + it("returns null when nothing is usable", () => { const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; expect(resolveAutoModelSelection({ selection: auto(), providers, now })).toBeNull(); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 87f997204b42..d76eda593edb 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -38,6 +38,12 @@ const codex = (model: string, effort: string): AutoCandidate => ({ effort, }); const grok = (effort: string): AutoCandidate => ({ driver: "grok", model: "grok-4.7", effort }); +/** Claude models on the Antigravity (Google) subscription: a third Claude pool. */ +const antigravity = (model: string, effort: string): AutoCandidate => ({ + driver: "antigravity", + model, + effort, +}); const opencode = (model: string, effort: string): AutoCandidate => ({ driver: "opencode", model, @@ -52,6 +58,7 @@ const AUTO_CANDIDATES: Readonly>> high: [ claude("claude-fable-5-2", "high"), claude("claude-opus-5-5", "high"), + antigravity("claude-opus-4-6-thinking", "high"), codex("gpt-6.1-sol", "high"), codex("gpt-6-astra", "high"), grok("high"), @@ -60,6 +67,7 @@ const AUTO_CANDIDATES: Readonly>> medium: [ claude("claude-opus-5-5", "medium"), claude("claude-fable-5-2", "medium"), + antigravity("claude-opus-4-6-thinking", "medium"), codex("gpt-6.1-sol", "medium"), codex("gpt-6-astra", "medium"), claude("claude-sonnet-5-5", "medium"), @@ -69,6 +77,7 @@ const AUTO_CANDIDATES: Readonly>> low: [ claude("claude-sonnet-5-5", "low"), claude("claude-haiku-5-5", "low"), + antigravity("claude-sonnet-4-6", "low"), opencode("opencode/big-pickle", "medium"), opencode("opencode/deepseek-v4.1-flash-free", "medium"), codex("gpt-6-luna", "low"), @@ -82,13 +91,26 @@ const EFFORT_OPTION_ID: Readonly> = { codex: "reasoningEffort", grok: "reasoningEffort", opencode: "variant", + antigravity: "thinking_level", }; +/** + * `auto` takes its level from the `effort` option; `auto-low`, `auto-medium` and `auto-high` + * fix it in the slug, so a picker can list one row per level. + */ +export function isAutoModelSlug(slug: string | null | undefined): boolean { + return ( + slug === AUTO_MODEL_SLUG || AUTO_LEVELS.some((level) => slug === `${AUTO_MODEL_SLUG}-${level}`) + ); +} + export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { - return selection?.model === AUTO_MODEL_SLUG; + return isAutoModelSlug(selection?.model); } function autoLevelOf(selection: ModelSelection): AutoLevel { + const fixed = AUTO_LEVELS.find((level) => selection.model === `${AUTO_MODEL_SLUG}-${level}`); + if (fixed) return fixed; const value = selection.options?.find((option) => option.id === "effort")?.value; return AUTO_LEVELS.find((level) => level === value) ?? DEFAULT_LEVEL; } @@ -105,13 +127,45 @@ export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { ], }; +/** Accounts whose 5-hour use differs by less than this many points count as equally free. */ +const SESSION_BAND_PERCENT = 10; + +function sessionUsedPercent(provider: ServerProvider): number { + const windows = (provider.usageLimits?.windows ?? []).filter((w) => w.kind === "session"); + return Math.max(0, ...windows.map((w) => w.usedPercent ?? 0)); +} + +/** When the soonest weekly window resets; unused weekly quota is lost then. */ +function weeklyResetAt(provider: ServerProvider): number { + const resets = (provider.usageLimits?.windows ?? []) + .filter((w) => w.kind === "weekly" && w.resetsAt !== undefined) + .map((w) => Date.parse(w.resetsAt!)) + .filter(Number.isFinite); + return resets.length > 0 ? Math.min(...resets) : Infinity; +} + +/** + * Best instance first: Auto-aware (carries the Auto prompt), then the freer 5-hour window, + * then, between accounts with similar 5-hour use, the one whose weekly quota resets first. + */ +function compareInstances(a: ServerProvider, b: ServerProvider): number { + const aware = Number(isAutoAware(b)) - Number(isAutoAware(a)); + if (aware !== 0) return aware; + const session = sessionUsedPercent(a) - sessionUsedPercent(b); + if (Math.abs(session) >= SESSION_BAND_PERCENT) return session; + const weekly = weeklyResetAt(a) - weeklyResetAt(b); + if (Number.isFinite(weekly) && weekly !== 0) return weekly; + if (weekly === Infinity || weekly === -Infinity) return weekly > 0 ? 1 : -1; + return session || peakUsedPercent(a) - peakUsedPercent(b); +} + function peakUsedPercent(provider: ServerProvider): number { return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); } /** Instances that list the `auto` model carry the Auto-mode prompt, so they win ties. */ function isAutoAware(provider: ServerProvider): boolean { - return provider.models.some((model) => model.slug === AUTO_MODEL_SLUG); + return provider.models.some((model) => isAutoModelSlug(model.slug)); } function usable(provider: ServerProvider, model: string, now: number): boolean { @@ -154,8 +208,8 @@ interface AutoResolution { /** * Keeps the thread's model while it fits this level and is under 90% used (no account hop, no - * lost prompt cache); otherwise the first usable candidate, Auto-aware and least-used instance - * first. Null when nothing is usable. + * lost prompt cache); otherwise the first usable candidate on the best instance (see + * `compareInstances`). Null when nothing is usable. */ export function resolveAutoModelSelection(input: { readonly selection: ModelSelection; @@ -190,11 +244,7 @@ export function resolveAutoModelSelection(input: { usable(provider, candidate.model, input.now), ) // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. - .sort( - (a, b) => - Number(isAutoAware(b)) - Number(isAutoAware(a)) || - peakUsedPercent(a) - peakUsedPercent(b), - ); + .sort(compareInstances); const provider = instances[0]; if (provider) return { selection: toSelection(provider, candidate), level, sticky: false }; } From 4a57dfe63a248f930f8550e2e1cf734a1f44f404 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 14:24:07 +0100 Subject: [PATCH 073/230] Name the chosen Auto level on the model picker button MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The button showed the model Auto routes to ("Auto · Opus 5.5 (A)"), which read as if Auto Medium were Opus. It now shows the level, such as "Auto Medium", and the tooltip names the current route. --- .../components/chat/ProviderModelPicker.tsx | 30 ++++++++++--------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 30c9512c7e0f..078433557f9b 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -191,22 +191,24 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { // Each Auto level row in the list names its own route. const autoRouteFor = (slug: string) => describeAutoRoute({ entries: props.instanceEntries, model: slug, now }); - const triggerTitle = - isAuto && autoRoute - ? `Auto · ${autoRoute.label}` - : selectedModel - ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) - : props.model === ANTIGRAVITY_DEFAULT_MODEL - ? gt("Choose model") - : props.model || gt("Choose model"); + // The button names the chosen Auto level; the model it routes to now goes in the tooltip. + const autoName = selectedModel ? getDisplayModelName(selectedModel) : "Auto"; + const triggerTitle = isAuto + ? autoName + : selectedModel + ? getTriggerDisplayModelName(selectedModel, activeEntry?.driverKind) + : props.model === ANTIGRAVITY_DEFAULT_MODEL + ? gt("Choose model") + : props.model || gt("Choose model"); const withUnavailable = (model: string, isUnavailable: boolean | undefined) => isUnavailable ? gt("{model} (Unavailable)", { model }) : model; - const triggerLabel = - isAuto && autoRoute - ? triggerTitle - : selectedModel - ? withUnavailable(getDisplayModelName(selectedModel), selectedModel.isUnavailable) - : triggerTitle; + const triggerLabel = isAuto + ? autoRoute + ? `${autoName} · now ${autoRoute.label}` + : autoName + : selectedModel + ? withUnavailable(getDisplayModelName(selectedModel), selectedModel.isUnavailable) + : triggerTitle; const showInstanceBadge = activeEntry !== null && shouldShowInstanceBadge(activeEntry, props.instanceEntries); From 0f5b5c384473b0bcfcae152efcdde999f8bd11cd Mon Sep 17 00:00:00 2001 From: radys-s Date: Fri, 13 Nov 2026 14:24:39 +0100 Subject: [PATCH 074/230] docs: tell agents to commit each medium step with its origin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Agents batched a whole task into one commit at the end, so history could not show which request or review finding produced which change. AGENTS.md gains a Commits section: commit and push each finished, verified step of medium size or larger, one idea per commit, with a body that states why and where the change came from (issue, PR, review finding, thread link, or the request in one line). Origin: Tomáš asked for more frequent, traceable orchestrator commits. --- .github/pull_request_template.md | 1 + AGENTS.md | 9 +++++++++ docs/progress.md | 7 +++++++ 3 files changed, 17 insertions(+) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index 94157c4135fa..5325e46142f4 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -3,6 +3,7 @@ Read CONTRIBUTING.md before opening a PR. Review capacity is limited, and meetin the requirements does not guarantee review or merging. Solve one underlying problem. The same requirements apply to drafts. Draft status does not defer triage or closure. Use a conventional commit title in plain language, such as "fix(web): new threads no longer spike CPU". +Keep one step per commit, and say in each commit body why it exists and where it came from. --> ## Problem diff --git a/AGENTS.md b/AGENTS.md index 6d788cd6c9e2..32a6a9460b2f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -148,6 +148,14 @@ For mobile verification, a missing or outdated native client is an install step, `evals/` checks how real models behave with T3 Code's model-facing text: agent instructions, MCP tool descriptions and schemas, and generated titles. Before you change that text, read [evals/README.md](evals/README.md) and run the evals it names. When you fix a model behavior bug, add a case that fails before the fix. +## Commits + +- Commit as you go, not once at the end. Each finished, verified step of medium size or larger gets its own commit right away: a bug fix, a feature slice, a refactor, a test suite, a doc update. Fold small edits (a typo, a rename, a review nit) into the step they belong to. +- One commit is one idea. If the title needs "and", split it. Every commit should build and pass the checks for the files it touches, so `git bisect` and `git revert` work on it alone. +- Title: conventional commit, as for PRs. Body: why the change exists, what it changes, and its origin, the issue, PR, review finding, or thread link that asked for it, or the user's request in one line. A reader of `git log` or `git blame` should reach the reason without the chat. +- Commit worker or delegate output only after you review and check it. Push after each commit on a task branch so the work is never only local. +- Never commit to `main` directly. Never rewrite commits that are already pushed unless the developer asks. + ## Pull requests - Never make a PR unless the developer explicitly asks you to do so. @@ -157,6 +165,7 @@ For mobile verification, a missing or outdated native client is an install step, - UI changes need before/after images. Motion or timing needs a short video. - Upload PR evidence to GitHub. Never commit PR-only screenshots or assets such as `.github/pr-assets/`. - One request is one PR. Split it only when the maintainer asks. Outside contributions follow the stricter [one problem per PR](CONTRIBUTING.md#one-problem) rule. +- Merge with a merge commit (`gh pr merge --merge`) so the per-step commits stay in `main`'s history. Squash only when the maintainer asks. - When babysitting: call `watch_pull_request` and end your turn. T3 Code wakes you on checks, comments, or conflicts. Do not poll or sleep. Verify each bot finding against the source, fix real ones, dismiss false positives with a written reason. Stay quiet when nothing is new. Stop when the bots are green on the latest commit. ## Documentation diff --git a/docs/progress.md b/docs/progress.md index 1a91af83a5bb..821d5452b229 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -31,3 +31,10 @@ - Numbers: autoModel tests 9/9 (3 new routing cases failed before the change, plus a level-slug test). Web typecheck clean in 47 s warm. - What worked: the Limits page showed Claude and distinct A/B numbers once the hub was quiet. The missing Claude section and copied numbers came from limit probes timing out while the hub was overloaded (load 11, IO pressure ~90). - Next: one combined web + server build, deployed with a stop/start of t3code.service, then settings switch the Auto tab to the three level rows. + +## 2026-11-13: Agents commit each step with its origin + +- What: `AGENTS.md` gets a Commits section. Agents commit and push each finished, checked step of medium size or larger, one idea per commit, with a body that says why and where the change came from (issue, PR, review finding, thread link, or the request). PRs merge with a merge commit so those steps stay in `main`. The PR template repeats the rule in one line. Outside the repo, `~/.agents/T3-CODE.md` and the `auto` and `swarm` skills got the same rule. +- Why: Tomáš wants to trace a problem back to the step and request that caused it. One big commit per task, or a squash merge, hides that. +- Numbers: docs only, 4 commits in PR #4. The fork runs no CI checks on PRs. +- Next: watch whether agents keep the cadence. If they do not, add the rule to the built-in orchestration instructions (`orchestrationInstructions.ts`, needs evals). From 676b0fc66789e560cd961a66156d903dd919a079 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 15:34:22 +0100 Subject: [PATCH 075/230] feat(shared): stagger Claude A/B 5-hour windows in Auto routing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auto sent work to the account with less 5-hour use, so both windows started together and ran out together. It now keeps using the account whose window is already running until any of its windows reaches 90%, then moves to the other, so one refreshes while the other works. Within 10 points of 5-hour use, the sooner weekly reset still goes first. Origin: Tomáš asked that Auto pick the plan closer to running out and offset the 5-hour windows so one refreshes while the other is nearly used up. GPT review loop: 2 rounds, approved. --- .../web/src/components/chat/autoRoute.test.ts | 2 +- docs/progress.md | 7 ++ packages/shared/src/autoModel.test.ts | 90 ++++++++++++++++--- packages/shared/src/autoModel.ts | 35 ++++++-- 4 files changed, 111 insertions(+), 23 deletions(-) diff --git a/apps/web/src/components/chat/autoRoute.test.ts b/apps/web/src/components/chat/autoRoute.test.ts index fae0bdef7887..85ae44be3be8 100644 --- a/apps/web/src/components/chat/autoRoute.test.ts +++ b/apps/web/src/components/chat/autoRoute.test.ts @@ -50,7 +50,7 @@ const claudeModels = [ describe("describeAutoRoute", () => { it("names the Claude model and account Auto would use", () => { const entries = deriveProviderInstanceEntries([ - provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 70), + provider("claudeAuto", "Auto", "claudeAgent", claudeModels, 95), provider("claudeAutoB", "Auto B", "claudeAgent", claudeModels, 10), ]); const medium = describeAutoRoute({ entries, now }); diff --git a/docs/progress.md b/docs/progress.md index 821d5452b229..22b8a6855e87 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -38,3 +38,10 @@ - Why: Tomáš wants to trace a problem back to the step and request that caused it. One big commit per task, or a squash merge, hides that. - Numbers: docs only, 4 commits in PR #4. The fork runs no CI checks on PRs. - Next: watch whether agents keep the cadence. If they do not, add the rule to the built-in orchestration instructions (`orchestrationInstructions.ts`, needs evals). + +## 2026-11-13: Auto staggers Claude A/B 5-hour windows + +- What: Auto now keeps sending work to the account whose 5-hour window is already running, until any of its windows reaches 90%, then moves to the other account. Within 10 points of 5-hour use, the sooner weekly reset wins. Past 90% everywhere, the account with the most left wins. +- Why: preferring the emptier account started both 5-hour windows at the same time, so both ran out together. Staggered windows let one refresh while the other is in use. +- Numbers: 11 routing tests (3 new), a mutation check (dropping the 90% rule fails 3 tests). +- Next: watch real routing on the hub for a day of use. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index eda559c93c55..ecd8389c4ba3 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -98,12 +98,8 @@ describe("resolveAutoModelSelection", () => { }); }); - it("picks the Claude account with more room, preferring Auto-aware instances", () => { - const providers = [ - claude("claudeAgent", 0, false), - claude("claudeAuto", 70), - claude("claudeAutoB", 20), - ]; + it("prefers Auto-aware instances", () => { + const providers = [claude("claudeAgent", 0, false), claude("claudeAutoB", 20)]; expect( resolveAutoModelSelection({ selection: auto("medium"), providers, now })?.selection .instanceId, @@ -137,22 +133,46 @@ describe("resolveAutoModelSelection", () => { }); }); - it("routes to the account with less of its 5-hour window used", () => { - // A has the busier week but a nearly unused 5-hour window, so it can take work right now. + it("drains the account whose 5-hour window is already running, so the windows stagger", () => { + // A's window is half spent; B stays untouched and its window starts only when A is nearly + // out, so A refreshes while B is in use. const providers = [ - withWeekly(claude("claudeAutoB", 50), 20, "2026-11-18T12:00:00.000Z"), - withWeekly(claude("claudeAuto", 10), 60, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAutoB", 0), 20, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 50), 20, "2026-11-18T12:00:00.000Z"), ]; expect( resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, ).toBe("claudeAuto"); }); + it("switches to the other account once a 5-hour or weekly window is 90% used", () => { + const sessionFull = [claude("claudeAuto", 92), claude("claudeAutoB", 0)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: sessionFull, now })?.selection + .instanceId, + ).toBe("claudeAutoB"); + const weeklyFull = [ + withWeekly(claude("claudeAuto", 50), 95, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAutoB", 0), 20, "2026-11-18T12:00:00.000Z"), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: weeklyFull, now })?.selection + .instanceId, + ).toBe("claudeAutoB"); + }); + + it("when every account is past 90%, uses the one with the most left", () => { + const providers = [claude("claudeAuto", 92), claude("claudeAutoB", 97)]; + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, + ).toBe("claudeAuto"); + }); + it("with similar 5-hour use, spends the account whose weekly limit resets first", () => { - // B has slightly less 5-hour use, but A's unused weekly quota is gone tomorrow. + // B's window is slightly further along, but A's unused weekly quota is gone tomorrow. const providers = [ - withWeekly(claude("claudeAutoB", 25), 40, "2026-11-18T12:00:00.000Z"), - withWeekly(claude("claudeAuto", 30), 40, "2026-11-13T12:00:00.000Z"), + withWeekly(claude("claudeAutoB", 30), 40, "2026-11-18T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 25), 40, "2026-11-13T12:00:00.000Z"), ]; expect( resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, @@ -187,6 +207,50 @@ describe("resolveAutoModelSelection", () => { }); }); + it("after every Claude subscription, uses ChatGPT, then Grok, then Gemini", () => { + const other = (id: string, driver: string, slug: string, optionId: string) => + ({ + ...claude(id, 0, false), + driver: ProviderDriverKind.make(driver), + models: [ + { + slug, + name: slug, + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: optionId, + label: "Effort", + type: "select" as const, + options: ["low", "medium", "high"].map((value) => ({ id: value, label: value })), + }, + ], + }, + }, + ], + usageLimits: undefined, + }) as unknown as ServerProvider; + const claudeOut = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; + const codex = other("codex", "codex", "gpt-6-luna", "reasoningEffort"); + const grok = other("grok", "grok", "grok-4.7", "reasoningEffort"); + const gemini = other("antigravity", "antigravity", "gemini-3.8-flash", "thinking_level"); + const route = (providers: ServerProvider[]) => + resolveAutoModelSelection({ selection: auto("high"), providers, now })?.selection; + + expect(route([...claudeOut, gemini, grok, codex])).toEqual({ + instanceId: "codex", + model: "gpt-6-luna", + options: [{ id: "reasoningEffort", value: "high" }], + }); + expect(route([...claudeOut, gemini, grok])?.instanceId).toBe("grok"); + expect(route([...claudeOut, gemini])).toEqual({ + instanceId: "antigravity", + model: "gemini-3.8-flash", + options: [{ id: "thinking_level", value: "high" }], + }); + }); + it("reads the level from auto-low / auto-medium / auto-high", () => { const providers = [claude("claudeAuto", 10)]; const pick = (model: string) => diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index d76eda593edb..db3e53c713da 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -17,7 +17,8 @@ const AUTO_MODEL_SLUG = "auto"; const AUTO_LEVELS = ["low", "medium", "high"] as const; type AutoLevel = (typeof AUTO_LEVELS)[number]; const DEFAULT_LEVEL: AutoLevel = "medium"; -/** Above this peak usage, a sticky model gives way when another candidate has more room. */ +/** At this peak usage an account counts as nearly out: a sticky model gives way and routing + * moves to an account with room. */ const STICKY_MAX_USED_PERCENT = 90; interface AutoCandidate { @@ -51,8 +52,9 @@ const opencode = (model: string, effort: string): AutoCandidate => ({ }); /** - * Orchestrator candidates per level, best first. Each level starts on its Claude model and - * steps down through the other subscriptions as limits run out. + * Orchestrator candidates per level, best first: Claude A/B, Claude on Antigravity A/B, ChatGPT + * (Codex), Grok, Gemini, then free OpenCode models. Models a provider does not list are skipped, + * so paid-plan models (Sol, Astra) wait until the plan has them. */ const AUTO_CANDIDATES: Readonly>> = { high: [ @@ -61,8 +63,9 @@ const AUTO_CANDIDATES: Readonly>> antigravity("claude-opus-4-6-thinking", "high"), codex("gpt-6.1-sol", "high"), codex("gpt-6-astra", "high"), - grok("high"), codex("gpt-6-luna", "high"), + grok("high"), + antigravity("gemini-3.8-flash", "high"), ], medium: [ claude("claude-opus-5-5", "medium"), @@ -71,15 +74,21 @@ const AUTO_CANDIDATES: Readonly>> codex("gpt-6.1-sol", "medium"), codex("gpt-6-astra", "medium"), claude("claude-sonnet-5-5", "medium"), - grok("medium"), + antigravity("claude-sonnet-4-6", "medium"), codex("gpt-6-luna", "medium"), + grok("medium"), + antigravity("gemini-3.8-flash", "medium"), + opencode("opencode/big-pickle", "medium"), ], low: [ claude("claude-sonnet-5-5", "low"), claude("claude-haiku-5-5", "low"), antigravity("claude-sonnet-4-6", "low"), + antigravity("gemini-3.8-flash", "low"), opencode("opencode/big-pickle", "medium"), + opencode("opencode/beam-free", "medium"), opencode("opencode/deepseek-v4.1-flash-free", "medium"), + opencode("opencode/glm-5.3-flash-free", "medium"), codex("gpt-6-luna", "low"), grok("low"), ], @@ -127,7 +136,7 @@ export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { ], }; -/** Accounts whose 5-hour use differs by less than this many points count as equally free. */ +/** Accounts whose 5-hour use differs by less than this many points count as equally far along. */ const SESSION_BAND_PERCENT = 10; function sessionUsedPercent(provider: ServerProvider): number { @@ -145,13 +154,17 @@ function weeklyResetAt(provider: ServerProvider): number { } /** - * Best instance first: Auto-aware (carries the Auto prompt), then the freer 5-hour window, - * then, between accounts with similar 5-hour use, the one whose weekly quota resets first. + * Best instance first: Auto-aware, then accounts under 90% everywhere. Among those, the further + * along 5-hour window, so windows stagger (one refreshes while the other runs); within 10 + * points, the sooner weekly reset. Past 90% everywhere, the most left. */ function compareInstances(a: ServerProvider, b: ServerProvider): number { const aware = Number(isAutoAware(b)) - Number(isAutoAware(a)); if (aware !== 0) return aware; - const session = sessionUsedPercent(a) - sessionUsedPercent(b); + const room = Number(hasRoom(b)) - Number(hasRoom(a)); + if (room !== 0) return room; + if (!hasRoom(a)) return peakUsedPercent(a) - peakUsedPercent(b); + const session = sessionUsedPercent(b) - sessionUsedPercent(a); if (Math.abs(session) >= SESSION_BAND_PERCENT) return session; const weekly = weeklyResetAt(a) - weeklyResetAt(b); if (Number.isFinite(weekly) && weekly !== 0) return weekly; @@ -159,6 +172,10 @@ function compareInstances(a: ServerProvider, b: ServerProvider): number { return session || peakUsedPercent(a) - peakUsedPercent(b); } +function hasRoom(provider: ServerProvider): boolean { + return peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT; +} + function peakUsedPercent(provider: ServerProvider): number { return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); } From a33f20c4e85c3848f45c0ed0ceb340f4044f417f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 16:51:15 +0100 Subject: [PATCH 076/230] feat(server): list Auto levels on every Claude provider MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auto Low, Medium and High existed only as custom models in the hub's settings, so a fork server on another machine (Tomáš's PC) showed no Auto at all. Every Claude provider now lists them as built-in models; a custom model with the same slug still works because built-ins win. Origin: Tomáš asked that Auto work in threads that run only on his own device. --- .../src/provider/ClaudeProvider.test.ts | 22 +++++++++++++++++++ apps/server/src/provider/ClaudeProvider.ts | 10 ++++++++- .../src/provider/ProviderRegistry.test.ts | 5 ++++- packages/shared/src/autoModel.ts | 7 ++++++ 4 files changed, 42 insertions(+), 2 deletions(-) create mode 100644 apps/server/src/provider/ClaudeProvider.test.ts diff --git a/apps/server/src/provider/ClaudeProvider.test.ts b/apps/server/src/provider/ClaudeProvider.test.ts new file mode 100644 index 000000000000..0acb897d044b --- /dev/null +++ b/apps/server/src/provider/ClaudeProvider.test.ts @@ -0,0 +1,22 @@ +import { describe, expect, it } from "@effect/vitest"; +import { ClaudeSettings } from "@t3tools/contracts"; +import * as Effect from "effect/Effect"; +import * as Schema from "effect/Schema"; + +import { makePendingClaudeProvider } from "./ClaudeProvider.ts"; + +const defaultSettings = Schema.decodeSync(ClaudeSettings)({}); + +describe("makePendingClaudeProvider", () => { + it.effect("lists Auto Low, Medium and High after the real models, with no settings", () => + Effect.gen(function* () { + const provider = yield* makePendingClaudeProvider(defaultSettings); + expect(provider.models[0]?.slug).toMatch(/^claude-/); + expect(provider.models.slice(-3).map((model) => [model.slug, model.name])).toEqual([ + ["auto-low", "Auto Low"], + ["auto-medium", "Auto Medium"], + ["auto-high", "Auto High"], + ]); + }), + ); +}); diff --git a/apps/server/src/provider/ClaudeProvider.ts b/apps/server/src/provider/ClaudeProvider.ts index b657a2b813fe..082a34c4ad02 100644 --- a/apps/server/src/provider/ClaudeProvider.ts +++ b/apps/server/src/provider/ClaudeProvider.ts @@ -20,6 +20,7 @@ import * as Ref from "effect/Ref"; import * as Result from "effect/Result"; import * as Schema from "effect/Schema"; import { ChildProcess, ChildProcessSpawner } from "effect/process"; +import { AUTO_LEVEL_MODELS } from "@t3tools/shared/autoModel"; import { createModelCapabilities } from "@t3tools/shared/model"; import { envTrampoline, supportsEnvChdir } from "@t3tools/shared/envTrampoline"; import * as HostProcess from "@t3tools/shared/HostProcess"; @@ -83,12 +84,19 @@ const DEFAULT_CLAUDE_MODEL_CAPABILITIES: ModelCapabilities = createModelCapabili optionDescriptors: [], }); +const AUTO_MODELS: ReadonlyArray = AUTO_LEVEL_MODELS.map((model) => ({ + ...model, + isCustom: false, + capabilities: DEFAULT_CLAUDE_MODEL_CAPABILITIES, +})); + function claudeProviderModels( builtInModels: ReadonlyArray, customModels: ClaudeSettings["customModels"], ): ReadonlyArray { return providerModelsFromSettings( - builtInModels, + // After the real models: callers that default to a provider's first model keep a real one. + [...builtInModels, ...AUTO_MODELS], customModels, DEFAULT_CLAUDE_MODEL_CAPABILITIES, ).map((model) => diff --git a/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 617fb4731e08..aee9a0d33d97 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -45,6 +45,7 @@ import { ChildProcessSpawner } from "effect/process"; import * as HostProcess from "@t3tools/shared/HostProcess"; import { WindowsShellEnvironment } from "@t3tools/shared/shell"; import { deepMerge } from "@t3tools/shared/Struct"; +import { isAutoModelSlug } from "@t3tools/shared/autoModel"; import { createModelCapabilities } from "@t3tools/shared/model"; import { applyServerSettingsPatch } from "@t3tools/shared/serverSettings"; @@ -4391,7 +4392,9 @@ it.layer( }), ); const catalogSlugs = new Set(BUNDLED_CLAUDE_MODEL_CATALOG.models.map((m) => m.model.slug)); - const added = status.models.filter((model) => !catalogSlugs.has(model.slug)); + const added = status.models.filter( + (model) => !catalogSlugs.has(model.slug) && !isAutoModelSlug(model.slug), + ); assert.deepStrictEqual( added.map((model) => [model.slug, model.name, model.isCustom]), diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index db3e53c713da..312468f38d01 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -113,6 +113,13 @@ export function isAutoModelSlug(slug: string | null | undefined): boolean { ); } +/** One picker row per level; every Claude provider lists them, so Auto needs no settings. */ +export const AUTO_LEVEL_MODELS: ReadonlyArray<{ readonly slug: string; readonly name: string }> = + AUTO_LEVELS.map((level) => ({ + slug: `${AUTO_MODEL_SLUG}-${level}`, + name: `Auto ${level[0]!.toUpperCase()}${level.slice(1)}`, + })); + export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { return isAutoModelSlug(selection?.model); } From 458bb31f282c3831e9ddaf68b141be671f9ffc95 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 13 Nov 2026 16:51:16 +0100 Subject: [PATCH 077/230] feat(web): pin Auto levels at the top of Favorites MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Favorites live in each server's settings, so a machine without the hub's settings had no Auto pinned. The picker now puts Auto High, Medium and Low from the first Claude instance that lists them at the top of Favorites, until the user stars an Auto level themselves. Origin: Tomáš asked for the Auto levels to be the main pinned models in every thread. --- .../components/chat/ModelPickerContent.tsx | 7 ++- .../chat/ProviderModelPicker.logic.test.ts | 59 ++++++++++++++++++- .../chat/ProviderModelPicker.logic.ts | 37 +++++++++++- docs/progress.md | 7 +++ 4 files changed, 105 insertions(+), 5 deletions(-) diff --git a/apps/web/src/components/chat/ModelPickerContent.tsx b/apps/web/src/components/chat/ModelPickerContent.tsx index da1e18469547..32c32effec7b 100644 --- a/apps/web/src/components/chat/ModelPickerContent.tsx +++ b/apps/web/src/components/chat/ModelPickerContent.tsx @@ -44,6 +44,7 @@ import { ComboboxItem, ComboboxListVirtualized, } from "../ui/combobox"; +import { autoLevelsFirst, withPinnedAutoLevels } from "./ProviderModelPicker.logic"; import { ModelEsque } from "./providerIconUtils"; import { isAutoModelSlug } from "@t3tools/shared/autoModel"; import type { AutoRoute } from "./autoRoute"; @@ -383,7 +384,8 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes this picker's mount to global keydown handlers useLayoutEffect(() => registerModelPickerContent(), []); const highlightedModelKeyRef = useRef(null); - const { favorites } = useEnvironmentModelPreferences(props.environmentId); + const { favorites: savedFavorites } = useEnvironmentModelPreferences(props.environmentId); + const favorites = withPinnedAutoLevels(savedFavorites, instanceEntries, modelOptionsByInstance); const activeEntry = props.instanceEntries.find( (entry) => entry.instanceId === props.activeInstanceId, ); @@ -720,11 +722,12 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { result = result.filter((m) => m.instanceId === selectedInstanceId); } - return sortProviderModelItems(result, { + const sorted = sortProviderModelItems(result, { favoriteModelKeys: favoritesSet, groupFavorites: selectedInstanceId !== "favorites", instanceOrder: selectedInstanceId === "favorites" ? instanceOrder : [], }); + return selectedInstanceId === "favorites" ? autoLevelsFirst(sorted) : sorted; })(); const legacySection = (() => { diff --git a/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts b/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts index 7602a362d30c..988c683990f0 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts +++ b/apps/web/src/components/chat/ProviderModelPicker.logic.test.ts @@ -1,7 +1,11 @@ -import { ProviderDriverKind } from "@t3tools/contracts"; +import { ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { retainedModelWhileProviderLocked } from "./ProviderModelPicker.logic"; +import { + autoLevelsFirst, + retainedModelWhileProviderLocked, + withPinnedAutoLevels, +} from "./ProviderModelPicker.logic"; const claude = ProviderDriverKind.make("claudeAgent"); const opus = { slug: "claude-opus-5-5", name: "Claude Opus 5.5", shortName: "Opus 5.5" }; @@ -18,3 +22,54 @@ describe("retainedModelWhileProviderLocked", () => { expect(retainedModelWhileProviderLocked(null, opus.slug)).toBeUndefined(); }); }); + +describe("withPinnedAutoLevels", () => { + const id = (value: string) => ProviderInstanceId.make(value); + const autoRows = ["auto-low", "auto-medium", "auto-high"].map((slug) => ({ slug })); + const entries = [ + { instanceId: id("codex"), driverKind: ProviderDriverKind.make("codex") }, + { instanceId: id("claudeAgent"), driverKind: claude }, + { instanceId: id("claudeAgent_2"), driverKind: claude }, + ]; + const options = new Map([ + [id("codex"), [{ slug: "gpt-6-luna" }]], + [id("claudeAgent"), [...autoRows, opus]], + [id("claudeAgent_2"), [...autoRows, opus]], + ]); + const saved = [{ provider: id("codex"), model: "gpt-6-luna" }]; + + it("pins the first Claude instance's Auto levels above saved favorites", () => { + expect(withPinnedAutoLevels(saved, entries, options)).toEqual([ + { provider: "claudeAgent", model: "auto-high" }, + { provider: "claudeAgent", model: "auto-medium" }, + { provider: "claudeAgent", model: "auto-low" }, + ...saved, + ]); + }); + + it("keeps the user's own choice once any Auto level is starred", () => { + const own = [{ provider: id("claudeAgent_2"), model: "auto-low" }, ...saved]; + expect(withPinnedAutoLevels(own, entries, options)).toBe(own); + }); + + it("changes nothing when no Claude instance lists the Auto levels", () => { + expect(withPinnedAutoLevels(saved, entries.slice(0, 1), options)).toBe(saved); + }); +}); + +describe("autoLevelsFirst", () => { + it("puts Auto High, Medium and Low ahead of other favorites, keeping the rest in order", () => { + const items = ["gpt-6-luna", "auto-low", "grok-4.7", "auto-high", "auto-medium"].map( + (slug) => ({ + slug, + }), + ); + expect(autoLevelsFirst(items).map((item) => item.slug)).toEqual([ + "auto-high", + "auto-medium", + "auto-low", + "gpt-6-luna", + "grok-4.7", + ]); + }); +}); diff --git a/apps/web/src/components/chat/ProviderModelPicker.logic.ts b/apps/web/src/components/chat/ProviderModelPicker.logic.ts index dd3d6871e7c2..f33cbae9e006 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.logic.ts +++ b/apps/web/src/components/chat/ProviderModelPicker.logic.ts @@ -1,7 +1,10 @@ -import type { ProviderDriverKind } from "@t3tools/contracts"; +import type { ModelFavorite, ProviderDriverKind, ProviderInstanceId } from "@t3tools/contracts"; +import { AUTO_LEVEL_MODELS, isAutoModelSlug } from "@t3tools/shared/autoModel"; import type { ModelEsque } from "./providerIconUtils"; +type Favorite = typeof ModelFavorite.Type; + /** Keeps a hidden model visible while its provider is locked or turned off. */ export function retainedModelWhileProviderLocked( entry: { @@ -16,3 +19,35 @@ export function retainedModelWhileProviderLocked( if (entry.driverKind === "opencode" || entry.driverKind === "antigravity") return undefined; return entry.models.find((candidate) => candidate.slug === model) ?? { slug: model, name: model }; } + +/** + * Auto High, Medium and Low lead Favorites on every machine, from the first Claude instance that + * lists them, until the user stars an Auto level themselves. + */ +export function withPinnedAutoLevels( + favorites: ReadonlyArray, + entries: ReadonlyArray<{ + readonly instanceId: ProviderInstanceId; + readonly driverKind: ProviderDriverKind; + }>, + optionsByInstance: ReadonlyMap>, +): ReadonlyArray { + if (favorites.some((favorite) => isAutoModelSlug(favorite.model))) return favorites; + const levels = AUTO_LEVEL_MODELS.map((model) => model.slug).reverse(); + const host = entries.find( + (entry) => + entry.driverKind === "claudeAgent" && + levels.every((slug) => + (optionsByInstance.get(entry.instanceId) ?? []).some((option) => option.slug === slug), + ), + ); + if (!host) return favorites; + return [...levels.map((model) => ({ provider: host.instanceId, model })), ...favorites]; +} + +/** Favorites view order: Auto High, Medium, Low first, then the rest as sorted. */ +export function autoLevelsFirst(items: ReadonlyArray): T[] { + const levels = AUTO_LEVEL_MODELS.map((model) => model.slug).reverse(); + const auto = levels.flatMap((slug) => items.filter((item) => item.slug === slug)); + return [...auto, ...items.filter((item) => !levels.includes(item.slug))]; +} diff --git a/docs/progress.md b/docs/progress.md index 22b8a6855e87..a7a0b2a2b48b 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -45,3 +45,10 @@ - Why: preferring the emptier account started both 5-hour windows at the same time, so both ran out together. Staggered windows let one refresh while the other is in use. - Numbers: 11 routing tests (3 new), a mutation check (dropping the 90% rule fails 3 tests). - Next: watch real routing on the hub for a day of use. + +## 2026-11-13: Auto levels on every machine + +- What: every Claude provider on a fork server lists Auto Low, Medium and High as built-in models, so Auto needs no settings. The model picker pins the three levels at the top of Favorites, from the first Claude instance that lists them, until the user stars an Auto level themselves. +- Why: Tomáš wants Auto in every thread, including threads that run on his PC's own T3 server, which has none of the hub's settings. +- Numbers: 1 new server test, 3 new picker tests; server and web typecheck clean (6 min and 62 s on the hub). +- Next: Tomáš builds the fork desktop app on his PC; Auto there routes only to the providers logged in on that PC. From 852f47b514cc4cd915ffcaf9d921c233318d0b93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 14 Nov 2026 11:32:21 +0100 Subject: [PATCH 078/230] fix(shared): Auto routes to the instances that carry the Auto prompt MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since every Claude provider lists the Auto levels (#6), "lists an Auto model" no longer marks the instances launched with the Auto-mode prompt (Auto, Auto B). The plain Claude instance shares their account and usage and comes first in the registry, so Auto routed turns to it and the orchestrator never got the routing instructions. Instances whose display name starts with "Auto" now win the tie. The unused `auto` custom-model descriptor goes with the old check. Origin: Tomáš reported that Auto model routing does not work. --- docs/progress.md | 7 +++++++ packages/shared/src/autoModel.test.ts | 21 ++++++++++----------- packages/shared/src/autoModel.ts | 20 +++++--------------- 3 files changed, 22 insertions(+), 26 deletions(-) diff --git a/docs/progress.md b/docs/progress.md index a7a0b2a2b48b..3aa0ddb5c309 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -52,3 +52,10 @@ - Why: Tomáš wants Auto in every thread, including threads that run on his PC's own T3 server, which has none of the hub's settings. - Numbers: 1 new server test, 3 new picker tests; server and web typecheck clean (6 min and 62 s on the hub). - Next: Tomáš builds the fork desktop app on his PC; Auto there routes only to the providers logged in on that PC. + +## 2026-11-14: Auto routes to the Auto instances again; fork synced with upstream for hub2 + +- What: Auto prefers instances named "Auto…" (the ones launched with `auto-mode.md`) when accounts tie. The fork merged upstream main (653 commits, no conflicts) and runs on hub2 from `~/projects/t3code-auto`. +- Why: since every Claude provider lists the Auto levels (#6), the old "lists an Auto model" check matched every Claude instance. Plain `claudeAgent` shares account A's usage with `claudeAuto` and comes first in the registry, so Auto sent turns to it and the orchestrator never got the routing prompt. hub2 ran upstream nightly (DB schema 89); the fork stopped at 85, so it could not run there. +- Numbers: autoModel 12/12 (the same-account case failed before the fix), ClaudeProvider + ProviderRegistry 80/80, web Auto tests 7/7; typecheck of contracts, shared, server and web clean (21 s server on hub2). Fork build 59 s on hub2. +- Next: link hub and deploy the same branch there; rebuild the desktop app on the PC. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index ecd8389c4ba3..d18bef35e2f7 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -6,7 +6,7 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { AUTO_LEVEL_DESCRIPTOR, isAutoModelSlug, resolveAutoModelSelection } from "./autoModel.ts"; +import { AUTO_LEVEL_MODELS, isAutoModelSlug, resolveAutoModelSelection } from "./autoModel.ts"; const now = Date.parse("2026-11-12T12:00:00.000Z"); const resetsAt = "2026-11-12T15:00:00.000Z"; @@ -26,6 +26,7 @@ function claude(id: string, usedPercent: number, autoAware = true): ServerProvid return { instanceId: ProviderInstanceId.make(id), driver: ProviderDriverKind.make("claudeAgent"), + ...(autoAware ? { displayName: id.endsWith("B") ? "Auto B" : "Auto" } : {}), enabled: true, installed: true, version: null, @@ -39,16 +40,8 @@ function claude(id: string, usedPercent: number, autoAware = true): ServerProvid isCustom: false, capabilities: effortCapabilities, })), - ...(autoAware - ? [ - { - slug: "auto", - name: "Auto", - isCustom: true, - capabilities: { optionDescriptors: [AUTO_LEVEL_DESCRIPTOR] }, - }, - ] - : []), + // Every Claude provider lists the Auto levels; only "Auto" instances carry the Auto prompt. + ...AUTO_LEVEL_MODELS.map((model) => ({ ...model, isCustom: false, capabilities: {} })), ], slashCommands: [], skills: [], @@ -104,6 +97,12 @@ describe("resolveAutoModelSelection", () => { resolveAutoModelSelection({ selection: auto("medium"), providers, now })?.selection .instanceId, ).toBe("claudeAutoB"); + // Same account, so same usage: the plain instance comes first in the registry. + const sameAccount = [claude("claudeAgent", 20, false), claude("claudeAuto", 20)]; + expect( + resolveAutoModelSelection({ selection: auto("medium"), providers: sameAccount, now }) + ?.selection.instanceId, + ).toBe("claudeAuto"); }); it("keeps the thread's current model until it passes 90% used", () => { diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 312468f38d01..87278cc6c7c9 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -2,7 +2,6 @@ import { isProviderAvailable, type ModelSelection, type ProviderDriverKind, - type ProviderOptionDescriptor, type ServerProvider, } from "@t3tools/contracts"; @@ -131,18 +130,6 @@ function autoLevelOf(selection: ModelSelection): AutoLevel { return AUTO_LEVELS.find((level) => level === value) ?? DEFAULT_LEVEL; } -/** The `effort` descriptor an `auto` custom model declares, so pickers show Low/Medium/High. */ -export const AUTO_LEVEL_DESCRIPTOR: ProviderOptionDescriptor = { - id: "effort", - label: "Auto level", - type: "select", - options: [ - { id: "low", label: "Low", description: "Sonnet orchestrates; cheaper models do more" }, - { id: "medium", label: "Medium", description: "Opus orchestrates", isDefault: true }, - { id: "high", label: "High", description: "Fable orchestrates" }, - ], -}; - /** Accounts whose 5-hour use differs by less than this many points count as equally far along. */ const SESSION_BAND_PERCENT = 10; @@ -187,9 +174,12 @@ function peakUsedPercent(provider: ServerProvider): number { return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); } -/** Instances that list the `auto` model carry the Auto-mode prompt, so they win ties. */ +/** + * Instances named "Auto…" carry the Auto-mode prompt (their launch args), so they win ties. Every + * Claude provider lists the Auto levels, so listing them says nothing about the prompt. + */ function isAutoAware(provider: ServerProvider): boolean { - return provider.models.some((model) => isAutoModelSlug(model.slug)); + return /^auto\b/i.test(provider.displayName ?? ""); } function usable(provider: ServerProvider, model: string, now: number): boolean { From 0aad7123e1ced8fd76d7bd183c8874738b551ee0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 14 Nov 2026 11:55:50 +0100 Subject: [PATCH 079/230] fix(client): an Auto thread no longer shows a pending context handoff MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After the first message on Auto, the thread runs on the model Auto chose (for example Auto B / Sonnet), while the composer still holds the Auto selection on the instance it was picked from. The pending-handoff check compared the two and showed "Context handoff pending" after every turn, although the server keeps the thread's model while it fits. The check now resolves an Auto selection the way the server does, so it only shows a handoff when Auto would really move the thread to another account. Web and mobile share the check; callers pass the current minute. Origin: found while checking Auto in the real hub2 web UI for Tomáš. --- .../src/state/use-thread-composer-state.ts | 3 +- apps/web/src/components/ChatView.tsx | 1 + docs/progress.md | 7 +++ packages/client-runtime/src/handoff.test.ts | 55 +++++++++++++++---- packages/client-runtime/src/handoff.ts | 14 +++++ .../client-runtime/src/state/contextWindow.ts | 3 +- 6 files changed, 70 insertions(+), 13 deletions(-) diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 69ec0af36995..e54109a985a2 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -354,12 +354,14 @@ export function useThreadComposerState(input: { const selectedThread = selectedThreadShell; const modelSelection = selectedDraft.modelSelection ?? selectedThread?.modelSelection ?? null; const serverConfig = selectedEnvironmentRuntime?.serverConfig; + const nowMinuteMs = useNowMinuteMs(); const pendingHandoff = resolvePendingHandoff( selectedThreadProjection?.projection, isModelSelectionUnavailable(serverConfig, modelSelection, selectedThread?.projectId ?? null) ? null : modelSelection, serverConfig?.providers ?? [], + nowMinuteMs, ); const runtimeMode = selectedDraft.runtimeMode ?? selectedThread?.runtimeMode ?? null; // Plan mode is not offered to users; every send runs in build mode. @@ -480,7 +482,6 @@ export function useThreadComposerState(input: { now, }) : null; - const nowMinuteMs = useNowMinuteMs(); const compactTokens = selectedDraft.freshContext === true ? null diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index a731a5798e19..9698ff5fde89 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2523,6 +2523,7 @@ export default function ChatView(props: ChatViewProps) { serverProjection, pendingHandoffSelectionUsable ? pendingHandoffSelection : null, providerStatuses, + Date.parse(`${nowMinute}:00Z`), ); const compactThreadUnavailable = !canOperateThread || diff --git a/docs/progress.md b/docs/progress.md index 3aa0ddb5c309..b084970a4e8a 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -59,3 +59,10 @@ - Why: since every Claude provider lists the Auto levels (#6), the old "lists an Auto model" check matched every Claude instance. Plain `claudeAgent` shares account A's usage with `claudeAuto` and comes first in the registry, so Auto sent turns to it and the orchestrator never got the routing prompt. hub2 ran upstream nightly (DB schema 89); the fork stopped at 85, so it could not run there. - Numbers: autoModel 12/12 (the same-account case failed before the fix), ClaudeProvider + ProviderRegistry 80/80, web Auto tests 7/7; typecheck of contracts, shared, server and web clean (21 s server on hub2). Fork build 59 s on hub2. - Next: link hub and deploy the same branch there; rebuild the desktop app on the PC. + +## 2026-11-14: Auto threads stop showing a false "Context handoff pending" + +- What: the shared pending-handoff check (web and mobile) resolves an Auto selection the way the server does, keeping the thread's current model while it fits, before deciding a handoff is coming. +- Why: in the real hub2 UI, every Auto thread showed "Context handoff pending: Sonnet 5.5 (AB) → Auto Low (CL)" after each turn, while the server log showed the next message stay on `claudeAutoB` (sticky). +- Numbers: handoff + contextWindow tests 39/39 (the new case failed before); client-runtime, web and mobile typecheck clean. Deployed on hub2 as a web-only build (51 s), no restart. +- Next: link hub and run the same checks there; rebuild the PC desktop app. diff --git a/packages/client-runtime/src/handoff.test.ts b/packages/client-runtime/src/handoff.test.ts index d2f5fb4e7890..071aa10fccd1 100644 --- a/packages/client-runtime/src/handoff.test.ts +++ b/packages/client-runtime/src/handoff.test.ts @@ -87,6 +87,8 @@ const projection = { visibleTurnItems: [{ item: { type: "user_message" } }], } as unknown as OrchestrationV2ThreadProjection; +const now = Date.parse("2026-11-14T12:00:00.000Z"); + describe("pending context handoff", () => { it("removes the preview while the handoff starts", () => { const selection = { instanceId: to, model: "destination" }; @@ -105,10 +107,10 @@ describe("pending context handoff", () => { ], }; - expect(resolvePendingHandoff(projection, selection, providers)).not.toBeNull(); - expect(resolvePendingHandoff(starting, selection, providers)).toBeNull(); + expect(resolvePendingHandoff(projection, selection, providers, now)).not.toBeNull(); + expect(resolvePendingHandoff(starting, selection, providers, now)).toBeNull(); expect( - resolvePendingHandoff(starting, { instanceId: from, model: "source" }, providers), + resolvePendingHandoff(starting, { instanceId: from, model: "source" }, providers, now), ).toEqual({ from: [selection], to: { instanceId: from, model: "source" }, @@ -133,7 +135,7 @@ describe("pending context handoff", () => { ], }; - expect(resolvePendingHandoff(unstarted, selection, [])).toEqual({ + expect(resolvePendingHandoff(unstarted, selection, [], now)).toEqual({ from: [{ instanceId: from, model: "source" }], to: selection, }); @@ -141,28 +143,59 @@ describe("pending context handoff", () => { ); it("appears on selection, updates the destination, and disappears on returning", () => { - expect(resolvePendingHandoff(projection, { instanceId: to, model: "first" }, [])).toEqual({ + expect(resolvePendingHandoff(projection, { instanceId: to, model: "first" }, [], now)).toEqual({ from: [{ instanceId: from, model: "source" }], to: { instanceId: to, model: "first" }, }); expect( - resolvePendingHandoff(projection, { instanceId: to, model: "second" }, [])?.to.model, + resolvePendingHandoff(projection, { instanceId: to, model: "second" }, [], now)?.to.model, ).toBe("second"); - expect(resolvePendingHandoff(projection, { instanceId: from, model: "source" }, [])).toBeNull(); - expect(resolvePendingHandoff(projection, { instanceId: from, model: "other" }, [])).toBeNull(); + expect( + resolvePendingHandoff(projection, { instanceId: from, model: "source" }, [], now), + ).toBeNull(); + expect( + resolvePendingHandoff(projection, { instanceId: from, model: "other" }, [], now), + ).toBeNull(); }); it("stays hidden while the thread's timeline is empty", () => { const empty = { ...projection, visibleTurnItems: [] }; - expect(resolvePendingHandoff(empty, { instanceId: to, model: "first" }, [])).toBeNull(); + expect(resolvePendingHandoff(empty, { instanceId: to, model: "first" }, [], now)).toBeNull(); // Paging can leave a window of only tool rows after the prompt. const toolRowsOnly = { ...projection, visibleTurnItems: [{ item: { type: "command_execution" } }], } as unknown as OrchestrationV2ThreadProjection; expect( - resolvePendingHandoff(toolRowsOnly, { instanceId: to, model: "first" }, [])?.to.model, + resolvePendingHandoff(toolRowsOnly, { instanceId: to, model: "first" }, [], now)?.to.model, ).toBe("first"); }); + it("previews an Auto selection as the model Auto keeps, not as a handoff", () => { + const autoB = ProviderInstanceId.make("claudeAutoB"); + const onAutoB = { + ...projection, + runs: [{ ...projection.runs[0]!, ...run("source", 1, autoB, "claude-sonnet-5-5") }], + } as unknown as OrchestrationV2ThreadProjection; + const claude = (instanceId: ProviderInstanceId, usedPercent: number) => + ({ + instanceId, + driver: "claudeAgent", + enabled: true, + installed: true, + status: "ready", + auth: { status: "authenticated" }, + models: [{ slug: "claude-sonnet-5-5", capabilities: { optionDescriptors: [] } }], + usageLimits: { windows: [{ kind: "session", usedPercent }] }, + }) as unknown as ServerProvider; + const autoLow = { instanceId: to, model: "auto-low" }; + + expect( + resolvePendingHandoff(onAutoB, autoLow, [claude(to, 0), claude(autoB, 20)], now), + ).toBeNull(); + // Past 90% Auto moves the thread to the other account, so the handoff is real. + expect( + resolvePendingHandoff(onAutoB, autoLow, [claude(to, 0), claude(autoB, 95)], now)?.to, + ).toMatchObject({ instanceId: to, model: "claude-sonnet-5-5" }); + }); it("resumes compatible account overlays without showing a handoff", () => { const providers = [from, to].map((instanceId) => ({ instanceId, @@ -170,7 +203,7 @@ describe("pending context handoff", () => { continuation: { groupKey: "shared" }, })) as unknown as ServerProvider[]; expect( - resolvePendingHandoff(projection, { instanceId: to, model: "target" }, providers), + resolvePendingHandoff(projection, { instanceId: to, model: "target" }, providers, now), ).toBeNull(); }); }); diff --git a/packages/client-runtime/src/handoff.ts b/packages/client-runtime/src/handoff.ts index 48a122742931..d8057f946ece 100644 --- a/packages/client-runtime/src/handoff.ts +++ b/packages/client-runtime/src/handoff.ts @@ -11,6 +11,7 @@ import { getModelSelectionStringOptionValue, getProviderOptionCurrentValue, } from "@t3tools/shared/model"; +import { isAutoModelSelection, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; import { isReasoningSelect } from "./modelTraits.ts"; import type { ThreadStructure } from "./state/models.ts"; @@ -27,6 +28,7 @@ export function resolvePendingHandoff( projection: Pick | null | undefined, selection: ModelSelection | null | undefined, providers: ReadonlyArray, + now: number, ): HandoffEndpoints | null { // A thread with an empty timeline has nothing to hand off. Any loaded row // counts: paging can leave a window of only tool rows. @@ -39,6 +41,18 @@ export function resolvePendingHandoff( (run.startedAt !== null || (run.status === "starting" && run.contextHandoffId !== null)), )?.modelSelection; if (from === undefined || selection == null) return null; + // The server swaps Auto for a concrete model per message, keeping the current one while it fits. + if (isAutoModelSelection(selection)) { + const route = resolveAutoModelSelection({ + selection, + providers, + now, + current: from, + }); + return route === null + ? null + : resolvePendingHandoff(projection, route.selection, providers, now); + } const source = providers.find((provider) => provider.instanceId === from.instanceId); const target = providers.find((provider) => provider.instanceId === selection.instanceId); const needsHandoff = diff --git a/packages/client-runtime/src/state/contextWindow.ts b/packages/client-runtime/src/state/contextWindow.ts index 37374b79b1b0..eae2e4b299f4 100644 --- a/packages/client-runtime/src/state/contextWindow.ts +++ b/packages/client-runtime/src/state/contextWindow.ts @@ -315,7 +315,8 @@ export function compactBeforeSendTokens(input: { COMPACT_COMMAND_PATTERN.test(input.text) || resolveIdleCompaction(input.settings, provider.instanceId) === "off" || !provider.slashCommands.some((command) => command.name === "compact") || - resolvePendingHandoff(projection, input.selection, input.providers) !== null || + resolvePendingHandoff(projection, input.selection, input.providers, Date.parse(input.now)) !== + null || projection.runtimeRequests.some((request) => request.status === "pending") || projection.runs.some((run) => run.status === "queued" && run.queueHeld === true) || (!input.visibleTurnItems.some( From e5dcc34525ee27c336db2d5d7e63f592e8e68ada Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 14 Nov 2026 12:05:51 +0100 Subject: [PATCH 080/230] feat: threads routed by Auto stay on Auto MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The server replaces Auto with a concrete model per message and stored only that, so after the first message every client showed "Sonnet 5.5 Low" instead of "Auto Low", and a client without the fork's composer kept sending the concrete model, which ended Auto routing for the thread. The model Auto picks now carries an `auto` option with its level. The server treats such a selection as Auto again on the next command (sticky while it fits), and web and mobile show it in the composer as the Auto level it came from. The pending-handoff preview only re-resolves Auto level slugs, so a routed selection does not recurse. Origin: Tomáš saw "Sonnet 5.5 Low" instead of Auto in a thread started on Auto Low. --- .../src/state/use-thread-composer-state.ts | 4 +- apps/web/src/components/ChatView.tsx | 5 +- docs/progress.md | 8 +++ packages/client-runtime/src/handoff.ts | 4 +- packages/shared/src/autoModel.test.ts | 59 +++++++++++++++---- packages/shared/src/autoModel.ts | 38 +++++++++--- 6 files changed, 97 insertions(+), 21 deletions(-) diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index e54109a985a2..36c1b5cf686b 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -10,6 +10,7 @@ import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell"; import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints"; import { threadSteersDuringCompaction } from "@t3tools/client-runtime/state/thread-workflows"; import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff"; +import { autoLevelSelection } from "@t3tools/shared/autoModel"; import { announcedRun, isDetailBehindShell, @@ -352,7 +353,8 @@ export function useThreadComposerState(input: { const selectedDraft = useComposerDraftSettings(selectedThreadKey); const selectedThreadQueueCount = selectedThreadQueuedMessages.length; const selectedThread = selectedThreadShell; - const modelSelection = selectedDraft.modelSelection ?? selectedThread?.modelSelection ?? null; + const modelSelection = + selectedDraft.modelSelection ?? autoLevelSelection(selectedThread?.modelSelection) ?? null; const serverConfig = selectedEnvironmentRuntime?.serverConfig; const nowMinuteMs = useNowMinuteMs(); const pendingHandoff = resolvePendingHandoff( diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 9698ff5fde89..5d06d5cbaad8 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -5,6 +5,7 @@ import { ChildThreadApprovals } from "./chat/ChildThreadApprovals"; import { workspaceAreaProps } from "../lib/workspaceFocus"; import { sourceControlClients } from "@t3tools/client-runtime/source-control-clients"; import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; +import { autoLevelSelection } from "@t3tools/shared/autoModel"; import { queuedRunEditBlockedReason } from "@t3tools/client-runtime/queued-run-edit"; import { ScrollToEndButton, WorkspaceFileDropOverlay } from "./chat/TimelineOverlays"; import { usePasteToFocusComposer } from "./chat/usePasteToFocusComposer"; @@ -3763,7 +3764,9 @@ export default function ChatView(props: ChatViewProps) { activeProjectDefaultModelSelection={ activeProjectDefaultModelSelection } - activeThreadModelSelection={activeThread?.modelSelection} + activeThreadModelSelection={autoLevelSelection( + activeThread?.modelSelection, + )} activeProjectId={activeProject?.id ?? null} projectName={activeProject?.title} compactThreadUnavailable={compactThreadUnavailable} diff --git a/docs/progress.md b/docs/progress.md index b084970a4e8a..1db4eaeb2169 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -66,3 +66,11 @@ - Why: in the real hub2 UI, every Auto thread showed "Context handoff pending: Sonnet 5.5 (AB) → Auto Low (CL)" after each turn, while the server log showed the next message stay on `claudeAutoB` (sticky). - Numbers: handoff + contextWindow tests 39/39 (the new case failed before); client-runtime, web and mobile typecheck clean. Deployed on hub2 as a web-only build (51 s), no restart. - Next: link hub and run the same checks there; rebuild the PC desktop app. + +## 2026-11-14: Threads routed by Auto stay on Auto + +- What: the model Auto picks carries an `auto` option with its level. The server treats it as Auto on the next command (sticky while under 90%), and web and mobile show the thread's composer as "Auto Low · now Sonnet 5.5 (B)" instead of "Sonnet 5.5 Low". +- Why: Tomáš saw "Sonnet 5.5 Low" in a thread started on Auto Low. The server stored only the concrete model, so Auto showed only where a local draft remembered it, and clients without the fork's composer sent the concrete model, ending Auto for that thread. +- Numbers: autoModel 12/12, handoff + contextWindow 39/39 (a recursion the stamp caused was caught by the handoff test); shared, client-runtime, web, mobile and server typecheck clean. Checked in a clean incognito browser on a scratch copy of hub2's data: a thread started on Auto Low over the CLI shows Auto Low in the composer. +- Deploy: service now runs from `~/.t3/fork-current` (a symlink to the deploy checkout), so a new build goes into a fresh checkout and the restart flips the link. +- Next: hub (link it first) and a fork build of the PC desktop app; the stock app still shows the concrete model. diff --git a/packages/client-runtime/src/handoff.ts b/packages/client-runtime/src/handoff.ts index d8057f946ece..1ca0c09ed50e 100644 --- a/packages/client-runtime/src/handoff.ts +++ b/packages/client-runtime/src/handoff.ts @@ -11,7 +11,7 @@ import { getModelSelectionStringOptionValue, getProviderOptionCurrentValue, } from "@t3tools/shared/model"; -import { isAutoModelSelection, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; +import { isAutoModelSlug, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; import { isReasoningSelect } from "./modelTraits.ts"; import type { ThreadStructure } from "./state/models.ts"; @@ -42,7 +42,7 @@ export function resolvePendingHandoff( )?.modelSelection; if (from === undefined || selection == null) return null; // The server swaps Auto for a concrete model per message, keeping the current one while it fits. - if (isAutoModelSelection(selection)) { + if (isAutoModelSlug(selection.model)) { const route = resolveAutoModelSelection({ selection, providers, diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index d18bef35e2f7..e3b6e708f89d 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -6,7 +6,13 @@ import { } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; -import { AUTO_LEVEL_MODELS, isAutoModelSlug, resolveAutoModelSelection } from "./autoModel.ts"; +import { + AUTO_LEVEL_MODELS, + autoLevelSelection, + isAutoModelSelection, + isAutoModelSlug, + resolveAutoModelSelection, +} from "./autoModel.ts"; const now = Date.parse("2026-11-12T12:00:00.000Z"); const resetsAt = "2026-11-12T15:00:00.000Z"; @@ -77,7 +83,10 @@ describe("resolveAutoModelSelection", () => { ).toEqual({ instanceId: "claudeAuto", model: "claude-fable-5-2", - options: [{ id: "effort", value: "high" }], + options: [ + { id: "effort", value: "high" }, + { id: "auto", value: "high" }, + ], }); expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.model).toBe( "claude-opus-5-5", @@ -87,7 +96,10 @@ describe("resolveAutoModelSelection", () => { ).toEqual({ instanceId: "claudeAuto", model: "claude-sonnet-5-5", - options: [{ id: "effort", value: "low" }], + options: [ + { id: "effort", value: "low" }, + { id: "auto", value: "low" }, + ], }); }); @@ -126,7 +138,9 @@ describe("resolveAutoModelSelection", () => { usageLimits: undefined, } as unknown as ServerProvider; const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100), grok]; - expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection).toEqual({ + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection, + ).toMatchObject({ instanceId: "grok", model: "grok-4.7", }); @@ -199,10 +213,15 @@ describe("resolveAutoModelSelection", () => { })), } as unknown as ServerProvider; const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100), antigravity]; - expect(resolveAutoModelSelection({ selection: auto(), providers, now })?.selection).toEqual({ + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection, + ).toMatchObject({ instanceId: "antigravity", model: "claude-opus-4-6-thinking", - options: [{ id: "thinking_level", value: "medium" }], + options: [ + { id: "thinking_level", value: "medium" }, + { id: "auto", value: "medium" }, + ], }); }); @@ -237,16 +256,22 @@ describe("resolveAutoModelSelection", () => { const route = (providers: ServerProvider[]) => resolveAutoModelSelection({ selection: auto("high"), providers, now })?.selection; - expect(route([...claudeOut, gemini, grok, codex])).toEqual({ + expect(route([...claudeOut, gemini, grok, codex])).toMatchObject({ instanceId: "codex", model: "gpt-6-luna", - options: [{ id: "reasoningEffort", value: "high" }], + options: [ + { id: "reasoningEffort", value: "high" }, + { id: "auto", value: "high" }, + ], }); expect(route([...claudeOut, gemini, grok])?.instanceId).toBe("grok"); - expect(route([...claudeOut, gemini])).toEqual({ + expect(route([...claudeOut, gemini])).toMatchObject({ instanceId: "antigravity", model: "gemini-3.8-flash", - options: [{ id: "thinking_level", value: "high" }], + options: [ + { id: "thinking_level", value: "high" }, + { id: "auto", value: "high" }, + ], }); }); @@ -263,6 +288,20 @@ describe("resolveAutoModelSelection", () => { expect(pick("auto-low")).toBe("claude-sonnet-5-5"); expect(isAutoModelSlug("auto-low")).toBe(true); expect(isAutoModelSlug("auto-max")).toBe(false); + + // The routed model keeps its level, so the thread stays on Auto and clients show it. + const routed = resolveAutoModelSelection({ + selection: auto("low"), + providers, + now, + })!.selection; + expect(isAutoModelSelection(routed)).toBe(true); + expect(autoLevelSelection(routed)).toEqual({ instanceId: "claudeAuto", model: "auto-low" }); + expect( + resolveAutoModelSelection({ selection: routed, providers, now, current: routed }), + ).toMatchObject({ sticky: true, level: "low", selection: routed }); + const plain = { instanceId: ProviderInstanceId.make("claudeAuto"), model: "claude-opus-5-5" }; + expect(autoLevelSelection(plain)).toBe(plain); }); it("returns null when nothing is usable", () => { diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 87278cc6c7c9..74519c6e38e5 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -13,6 +13,8 @@ import { exhaustedUsageWindow } from "./usageLimits.ts"; * live usage limits. The level (`low` | `medium` | `high`) rides in the `effort` option. */ const AUTO_MODEL_SLUG = "auto"; +/** Stamped on the model Auto picks, holding the level, so the thread stays on Auto. */ +const AUTO_OPTION_ID = "auto"; const AUTO_LEVELS = ["low", "medium", "high"] as const; type AutoLevel = (typeof AUTO_LEVELS)[number]; const DEFAULT_LEVEL: AutoLevel = "medium"; @@ -119,11 +121,28 @@ export const AUTO_LEVEL_MODELS: ReadonlyArray<{ readonly slug: string; readonly name: `Auto ${level[0]!.toUpperCase()}${level.slice(1)}`, })); +function stampedLevel(selection: ModelSelection | null | undefined): AutoLevel | undefined { + const value = selection?.options?.find((option) => option.id === AUTO_OPTION_ID)?.value; + return AUTO_LEVELS.find((level) => level === value); +} + export function isAutoModelSelection(selection: ModelSelection | null | undefined): boolean { - return isAutoModelSlug(selection?.model); + return isAutoModelSlug(selection?.model) || stampedLevel(selection) !== undefined; +} + +/** A routed thread's model as the Auto level it came from, for pickers; others unchanged. */ +export function autoLevelSelection( + selection: T, +): T | ModelSelection { + const level = stampedLevel(selection); + return selection && level + ? { instanceId: selection.instanceId, model: `${AUTO_MODEL_SLUG}-${level}` } + : selection; } function autoLevelOf(selection: ModelSelection): AutoLevel { + const stamped = stampedLevel(selection); + if (stamped) return stamped; const fixed = AUTO_LEVELS.find((level) => selection.model === `${AUTO_MODEL_SLUG}-${level}`); if (fixed) return fixed; const value = selection.options?.find((option) => option.id === "effort")?.value; @@ -204,12 +223,15 @@ function effortOptions(provider: ServerProvider, candidate: AutoCandidate) { : undefined; } -function toSelection(provider: ServerProvider, candidate: AutoCandidate): ModelSelection { - const options = effortOptions(provider, candidate); +function toSelection( + provider: ServerProvider, + candidate: AutoCandidate, + level: AutoLevel, +): ModelSelection { return { instanceId: provider.instanceId, model: candidate.model, - ...(options ? { options } : {}), + options: [...(effortOptions(provider, candidate) ?? []), { id: AUTO_OPTION_ID, value: level }], }; } @@ -235,7 +257,7 @@ export function resolveAutoModelSelection(input: { const candidates = AUTO_CANDIDATES[level]; const current = input.current; - if (current && !isAutoModelSelection(current)) { + if (current && !isAutoModelSlug(current.model)) { const provider = input.providers.find((entry) => entry.instanceId === current.instanceId); const candidate = candidates.find( (entry) => entry.driver === provider?.driver && entry.model === current.model, @@ -246,7 +268,7 @@ export function resolveAutoModelSelection(input: { usable(provider, candidate.model, input.now) && peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT ) { - return { selection: toSelection(provider, candidate), level, sticky: true }; + return { selection: toSelection(provider, candidate, level), level, sticky: true }; } } @@ -260,7 +282,9 @@ export function resolveAutoModelSelection(input: { // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. .sort(compareInstances); const provider = instances[0]; - if (provider) return { selection: toSelection(provider, candidate), level, sticky: false }; + if (provider) { + return { selection: toSelection(provider, candidate, level), level, sticky: false }; + } } return null; } From 26923a003b2a4438ac445304662e0a61021d5acd Mon Sep 17 00:00:00 2001 From: radys-s Date: Sat, 14 Nov 2026 14:16:32 +0100 Subject: [PATCH 081/230] feat(usage): add smart reset credit advice to limits page --- .../components/usage/UsageLimitsPooled.tsx | 44 +++++++- packages/shared/src/usageLimits.test.ts | 104 +++++++++++++++++- packages/shared/src/usageLimits.ts | 2 +- packages/shared/src/usageLimitsCopy.ts | 84 ++++++++++++++ 4 files changed, 231 insertions(+), 3 deletions(-) diff --git a/apps/web/src/components/usage/UsageLimitsPooled.tsx b/apps/web/src/components/usage/UsageLimitsPooled.tsx index d0c3e5f43f99..ccf36e90e5c0 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.tsx @@ -52,6 +52,7 @@ import { formatDuration, formatResetsIn, resetCreditChoices, + suggestResetCredit, } from "@t3tools/shared/usageLimitsCopy"; import { UsagePoolChart } from "./UsagePoolChart"; import { poolHistoryKey, readPoolHistory, recordPoolReadings } from "./usagePoolHistory"; @@ -148,6 +149,7 @@ function SegmentPopover({ account, window, reset, + poolMembers, now, redeem, onRedeem, @@ -155,6 +157,7 @@ function SegmentPopover({ readonly account: LimitAccount; readonly window: LimitPoolMember["window"]; readonly reset: LimitPoolWindow["resets"][number] | undefined; + readonly poolMembers?: readonly LimitPoolMember[] | undefined; readonly now: number; readonly redeem: ReturnType | null; readonly onRedeem: (choice: ResetCreditChoice) => void; @@ -169,6 +172,7 @@ function SegmentPopover({ account.environments.length > 0 ? account.environments.map((environment) => environment.label).join(", ") : account.sourceLabel; + const suggestion = suggestResetCredit(account, window, poolMembers ?? [{ account, window }], now); const choices = redeem && account.redeem && account.limits.resetCredits?.availableCount ? resetCreditChoices(account.limits.resetCredits, account.redeem.input, now, true, m) @@ -225,6 +229,28 @@ function SegmentPopover({ ) : null}
+ {suggestion ? ( +
+
+ + + Reset advice: + + + {suggestion.actionLabel} + +
+ {suggestion.reason} +
+ ) : null} {choices.length > 0 && redeem ? (
{choices.map((choice) => ( @@ -322,6 +348,7 @@ function PoolSegment({ readonly now: number; readonly index: number; readonly showAccountName: boolean; + readonly poolMembers?: readonly LimitPoolMember[] | undefined; }) { return account.redeem ? ( @@ -364,6 +391,7 @@ function SegmentTriggers({ window, reset, redeem, + poolMembers, refillPercent, color, now, @@ -377,7 +405,7 @@ function SegmentTriggers({ readonly showAccountName: boolean; }) { const popover = use(SegmentPopoverContext) ?? undefined; - const payload: SegmentPayload = { account, window, reset, redeem }; + const payload: SegmentPayload = { account, window, reset, redeem, poolMembers }; const remaining = remainingPercent(window); const timeLeft = paceRemainingPercent(window, now); const [segmentRef, paceMark] = usePaceMark(timeLeft); @@ -581,6 +609,7 @@ function PoolBar({ now={now} index={position + 1} showAccountName={pool.columns.length > 1} + poolMembers={pool.members} /> ) : pool.kind === "monthly" && member.account.limits.zeroSpendCap ? (
+ {(() => { + const advice = pool.members + .filter((m) => m.window && (m.account.limits.resetCredits?.availableCount ?? 0) > 0) + .map((m) => suggestResetCredit(m.account, m.window!, pool.members, now)) + .find(Boolean); + return advice ? ( +
+ + {advice.actionLabel}: + {advice.reason} +
+ ) : null; + })()} {description ?

{description}

: null}
); diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index 0078c21b566b..bd616cf5865d 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -25,7 +25,7 @@ import { usesChatGptSharing, resolveNewThreadModelSelection, } from "./usageLimits.ts"; -import { collectLimitNotices } from "./usageLimitsCopy.ts"; +import { collectLimitNotices, suggestResetCredit } from "./usageLimitsCopy.ts"; const now = Date.parse("2026-09-03T12:00:00.000Z"); @@ -1837,3 +1837,105 @@ describe("ChatGPT sharing presentation", () => { ).toBe(false); }); }); + +describe("suggestResetCredit advice", () => { + const baseAccount: LimitAccount = { + key: "claude_a", + driver: ProviderDriverKind.make("claudeAgent"), + displayName: "Claude A", + email: undefined, + plan: "Max", + accentColor: undefined, + sourceLabel: "Desk", + environments: [], + limits: { + checkedAt: "2026-09-03T11:00:00.000Z", + windows: [], + resetCredits: { + availableCount: 1, + }, + }, + redeem: null, + }; + + const depletedWindow = { + id: "five_hour", + kind: "session" as const, + label: "Session", + usedPercent: 100, + windowDurationMins: 300, + resetsAt: "2026-09-03T15:00:00.000Z", + }; + + it("returns null when no reset credits are available", () => { + const acc = { + ...baseAccount, + limits: { ...baseAccount.limits, resetCredits: { availableCount: 0 } }, + }; + expect(suggestResetCredit(acc, depletedWindow, [], now)).toBeNull(); + }); + + it("suggests waiting when natural reset is within 45 minutes", () => { + const imminentWindow = { ...depletedWindow, resetsAt: "2026-09-03T12:20:00.000Z" }; // 20 mins from now + const advice = suggestResetCredit(baseAccount, imminentWindow, [], now); + expect(advice?.recommendation).toBe("wait"); + expect(advice?.actionLabel).toBe("Wait for natural reset"); + expect(advice?.reason).toContain("20m"); + }); + + it("suggests saving when account still has >20% remaining", () => { + const healthyWindow = { ...depletedWindow, usedPercent: 40 }; // 60% remaining + const advice = suggestResetCredit(baseAccount, healthyWindow, [], now); + expect(advice?.recommendation).toBe("save"); + expect(advice?.actionLabel).toBe("Save for later"); + }); + + it("suggests holding when another account in pool has healthy quota", () => { + const otherAccount: LimitAccount = { + ...baseAccount, + key: "claude_b", + }; + const otherWindow = { ...depletedWindow, usedPercent: 30 }; // 70% remaining + const advice = suggestResetCredit( + baseAccount, + depletedWindow, + [ + { account: baseAccount, window: depletedWindow }, + { account: otherAccount, window: otherWindow }, + ], + now, + ); + expect(advice?.recommendation).toBe("hold"); + expect(advice?.actionLabel).toContain("Hold off"); + expect(advice?.reason).toContain("70%"); + }); + + it("recommends using reset when depleted and next reset is hours away", () => { + const advice = suggestResetCredit( + baseAccount, + depletedWindow, + [{ account: baseAccount, window: depletedWindow }], + now, + ); + expect(advice?.recommendation).toBe("recommended"); + expect(advice?.actionLabel).toBe("Recommended to use now"); + expect(advice?.reason).toContain("in 3h"); + }); + + it("warns when reset credit expires within 24h", () => { + const expiringAccount: LimitAccount = { + ...baseAccount, + limits: { + ...baseAccount.limits, + resetCredits: { + availableCount: 1, + nextExpiresAt: "2026-09-03T18:00:00.000Z", // 6h from now + }, + }, + }; + const advice = suggestResetCredit(expiringAccount, depletedWindow, [], now); + expect(advice?.recommendation).toBe("expiring_soon"); + expect(advice?.actionLabel).toBe("Use before expiry"); + expect(advice?.reason).toContain("6h"); + }); +}); diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 693d82b95697..c46c420a226e 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -701,7 +701,7 @@ export function remainingPercent(window: ServerProviderUsageWindow): number { return Math.round(100 - Math.max(0, Math.min(100, window.usedPercent))); } -function resetMillis(window: ServerProviderUsageWindow): number | null { +export function resetMillis(window: ServerProviderUsageWindow): number | null { if (window.resetsAt === undefined) return null; const at = Date.parse(window.resetsAt); return Number.isFinite(at) ? at : null; diff --git a/packages/shared/src/usageLimitsCopy.ts b/packages/shared/src/usageLimitsCopy.ts index d772c48b29aa..9186bc1ff08b 100644 --- a/packages/shared/src/usageLimitsCopy.ts +++ b/packages/shared/src/usageLimitsCopy.ts @@ -10,11 +10,14 @@ import type { MFunctionType } from "gt-i18n/types"; import { collectExternalUsageLinks as collectExternalUsageLinksWith, cursorUsageWindowDetails as cursorUsageWindowDetailsBase, + type LimitAccount, type LimitPool, type LimitPresentations, providersWithLimits, + remainingPercent, type ResetCreditChoice, resetCountdown, + resetMillis, } from "./usageLimits.ts"; const MINUTE = 60_000; @@ -213,3 +216,84 @@ export function formatResetsIn( if (style === "refill") return resolve(msg("↻ {duration}", { duration })); return resolve(msg("resets in {duration}", { duration })); } + +export interface ResetCreditSuggestion { + readonly recommendation: "recommended" | "wait" | "save" | "hold" | "expiring_soon"; + readonly actionLabel: string; + readonly reason: string; +} + +export function suggestResetCredit( + account: LimitAccount, + window: ServerProviderUsageWindow, + poolMembers: ReadonlyArray<{ + readonly account: LimitAccount; + readonly window?: ServerProviderUsageWindow | null; + }>, + now: number, +): ResetCreditSuggestion | null { + const credits = account.limits.resetCredits; + if (!credits || credits.availableCount <= 0) return null; + + const remaining = remainingPercent(window); + const resetsAt = resetMillis(window); + const resetsInMs = resetsAt !== null ? resetsAt - now : null; + + // 1. Expiring soon: credit expires within 24 hours + const optionExpiries = (credits.options ?? []) + .filter((opt) => opt.availableCount > 0 && opt.expiresAt) + .map((opt) => Date.parse(opt.expiresAt!)) + .filter(Number.isFinite); + const nextExpires = credits.nextExpiresAt ? Date.parse(credits.nextExpiresAt) : null; + if (nextExpires && Number.isFinite(nextExpires)) { + optionExpiries.push(nextExpires); + } + const soonestExpiry = optionExpiries.length > 0 ? Math.min(...optionExpiries) : null; + if (soonestExpiry !== null) { + const timeUntilExpiry = soonestExpiry - now; + if (timeUntilExpiry > 0 && timeUntilExpiry <= 24 * 3600 * 1000) { + return { + recommendation: "expiring_soon", + actionLabel: "Use before expiry", + reason: `Banked reset credit expires in ${formatDuration(timeUntilExpiry)}. Use it before it expires.`, + }; + } + } + + // 2. Natural reset is imminent (within 45 minutes) + if (resetsInMs !== null && resetsInMs > 0 && resetsInMs <= 45 * 60 * 1000) { + return { + recommendation: "wait", + actionLabel: "Wait for natural reset", + reason: `Window resets naturally in ${formatDuration(resetsInMs)}. Save your banked credit.`, + }; + } + + // 3. This account still has plenty of quota (> 20% remaining) + if (remaining > 20) { + return { + recommendation: "save", + actionLabel: "Save for later", + reason: `${remaining}% quota remaining. Reset only when depleted.`, + }; + } + + // 4. Other account in the same pool has plenty of quota (> 25% remaining) + const otherMembers = poolMembers.filter((m) => m.account.key !== account.key && m.window); + const otherMaxRemaining = + otherMembers.length > 0 ? Math.max(...otherMembers.map((m) => remainingPercent(m.window!))) : 0; + if (otherMaxRemaining > 25) { + return { + recommendation: "hold", + actionLabel: "Hold off (other account active)", + reason: `Auto mode has another account with ${otherMaxRemaining}% quota left. Save credit until both are depleted.`, + }; + } + + // 5. Recommended: Account is depleted and next reset is far away (or not soon) + return { + recommendation: "recommended", + actionLabel: "Recommended to use now", + reason: `Quota depleted and next natural reset is ${resetsInMs !== null && resetsInMs > 0 ? `in ${formatDuration(resetsInMs)}` : "hours away"}. Good time to reset.`, + }; +} From 9edb3408e191ec0028587f8e4314c8cfe9090bd3 Mon Sep 17 00:00:00 2001 From: radys-s Date: Sat, 14 Nov 2026 21:37:35 +0100 Subject: [PATCH 082/230] feat(auto): fail over to the next subscription when one hits its limit When a run on an Auto thread fails with a usage limit or no capacity, bench that provider instance and send the thread back through Auto, which skips benched instances, so work continues on the next subscription instead of waiting hours for the reset. --- .../src/orchestration-v2/AutoCooldown.ts | 25 +++ .../AutoFailoverService.test.ts | 107 +++++++++++ .../orchestration-v2/AutoFailoverService.ts | 168 ++++++++++++++++++ .../src/orchestration-v2/Orchestrator.ts | 5 +- apps/server/src/server.ts | 6 + docs/progress.md | 8 + packages/shared/src/autoModel.test.ts | 18 ++ packages/shared/src/autoModel.ts | 16 +- 8 files changed, 350 insertions(+), 3 deletions(-) create mode 100644 apps/server/src/orchestration-v2/AutoCooldown.ts create mode 100644 apps/server/src/orchestration-v2/AutoFailoverService.test.ts create mode 100644 apps/server/src/orchestration-v2/AutoFailoverService.ts diff --git a/apps/server/src/orchestration-v2/AutoCooldown.ts b/apps/server/src/orchestration-v2/AutoCooldown.ts new file mode 100644 index 000000000000..f4eddaf6738e --- /dev/null +++ b/apps/server/src/orchestration-v2/AutoCooldown.ts @@ -0,0 +1,25 @@ +/** + * Provider instances that just failed an Auto thread with a usage limit or no capacity. The + * usage report can lag behind (or never show a gateway's 429), so Auto routing skips these until + * the cooldown ends. Lives in memory: a server restart forgets it, and the usage report takes over. + */ +const cooldowns = new Map(); + +/** Per instance; a model-scoped limit (Antigravity pools) still benches the whole instance. */ +export function markAutoCooldown(instanceId: string, untilMs: number): void { + const current = cooldowns.get(instanceId) ?? 0; + if (untilMs > current) cooldowns.set(instanceId, untilMs); +} + +export function isAutoCoolingDown(instanceId: string, nowMs: number): boolean { + const until = cooldowns.get(instanceId); + if (until === undefined) return false; + if (until > nowMs) return true; + cooldowns.delete(instanceId); + return false; +} + +/** Tests only. */ +export function clearAutoCooldowns(): void { + cooldowns.clear(); +} diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts new file mode 100644 index 000000000000..e037eb675462 --- /dev/null +++ b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts @@ -0,0 +1,107 @@ +import { + ProviderInstanceId, + RunId, + ThreadId, + type OrchestrationV2ThreadShell, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { clearAutoCooldowns, isAutoCoolingDown, markAutoCooldown } from "./AutoCooldown.ts"; +import { admitFailover, autoFailoverPlan, MAX_FAILOVERS_PER_HOUR } from "./AutoFailoverService.ts"; + +const now = Date.parse("2026-11-14T20:00:00.000Z"); +const runId = RunId.make("run:thread:t1:ordinal:3"); + +function shell(overrides: Partial> = {}): OrchestrationV2ThreadShell { + return { + id: ThreadId.make("t1"), + providerInstanceId: ProviderInstanceId.make("claudeAuto"), + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAuto"), + model: "claude-opus-5-5", + options: [ + { id: "effort", value: "medium" }, + { id: "auto", value: "medium" }, + ], + }, + latestRunId: runId, + status: "failed", + lastErrorClass: "usage_limit", + lastErrorCode: "api_error_429", + usageLimitResetAt: null, + archivedAt: null, + settledOverride: null, + pendingRuntimeRequest: null, + ...overrides, + } as unknown as OrchestrationV2ThreadShell; +} + +const plan = (s: OrchestrationV2ThreadShell) => + autoFailoverPlan({ shell: s, runId, failedInstanceId: "claudeAuto", nowMs: now }); + +describe("autoFailoverPlan", () => { + it("sends a limited Auto thread back through Auto at its level", () => { + const result = plan(shell()); + expect(result?.command).toMatchObject({ + type: "message.dispatch", + threadId: "t1", + modelSelection: { instanceId: "claudeAuto", model: "auto-medium" }, + dispatchMode: { type: "start_immediately" }, + createdBy: "agent", + creationSource: "server", + }); + expect(result?.command.commandId).toBe(`server:auto-failover:t1:${runId}`); + // No reported reset: a 30 minute bench. + expect(result?.cooldownUntilMs).toBe(now + 30 * 60_000); + }); + + it("benches the instance until the reported reset", () => { + const resetAt = "2026-11-14T23:00:00.000Z"; + expect(plan(shell({ usageLimitResetAt: resetAt }))?.cooldownUntilMs).toBe(Date.parse(resetAt)); + }); + + it("fails over on no-capacity errors for a short bench", () => { + const result = plan(shell({ lastErrorClass: "provider_error", lastErrorCode: "UNAVAILABLE" })); + expect(result?.cooldownUntilMs).toBe(now + 5 * 60_000); + }); + + it("leaves other failures, non-Auto threads and stale runs alone", () => { + expect( + plan(shell({ lastErrorClass: "provider_error", lastErrorCode: "api_error_404" })), + ).toBeNull(); + expect( + plan( + shell({ + modelSelection: { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-opus-5-5", + }, + }), + ), + ).toBeNull(); + expect(plan(shell({ latestRunId: RunId.make("run:newer") }))).toBeNull(); + expect(plan(shell({ status: "idle" }))).toBeNull(); + expect(plan(shell({ settledOverride: "settled" }))).toBeNull(); + }); +}); + +describe("admitFailover", () => { + it("caps failovers per thread per hour", () => { + const history: Array = []; + for (let i = 0; i < MAX_FAILOVERS_PER_HOUR; i++) + expect(admitFailover(history, now + i)).toBe(true); + expect(admitFailover(history, now + 10)).toBe(false); + expect(admitFailover(history, now + 61 * 60_000)).toBe(true); + }); +}); + +describe("AutoCooldown", () => { + it("benches an instance until the time passes", () => { + clearAutoCooldowns(); + markAutoCooldown("claudeAuto", now + 1000); + markAutoCooldown("claudeAuto", now + 500); + expect(isAutoCoolingDown("claudeAuto", now + 999)).toBe(true); + expect(isAutoCoolingDown("claudeAuto", now + 1000)).toBe(false); + expect(isAutoCoolingDown("claudeAutoB", now)).toBe(false); + }); +}); diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.ts b/apps/server/src/orchestration-v2/AutoFailoverService.ts new file mode 100644 index 000000000000..e5185172de09 --- /dev/null +++ b/apps/server/src/orchestration-v2/AutoFailoverService.ts @@ -0,0 +1,168 @@ +import { + CommandId, + MessageId, + type OrchestrationV2ThreadShell, + type RunId, + type ThreadId, +} from "@t3tools/contracts"; +import { routedAutoLevel } from "@t3tools/shared/autoModel"; +import * as DateTime from "effect/DateTime"; +import * as Duration from "effect/Duration"; +import * as Effect from "effect/Effect"; +import * as FiberMap from "effect/FiberMap"; +import * as Stream from "effect/Stream"; + +import { forkParked } from "../serverActivation.ts"; +import { markAutoCooldown } from "./AutoCooldown.ts"; +import * as Orchestrator from "./Orchestrator.ts"; + +/** Failures that mean "this account has no room right now", besides the usage_limit class. */ +const CAPACITY_CODES: ReadonlySet = new Set([ + "UNAVAILABLE", + "RESOURCE_EXHAUSTED", + "api_error_529", + "overloaded_error", +]); +/** A limit without a reported reset benches the instance this long. */ +const LIMIT_COOLDOWN_MS = 30 * 60_000; +/** No capacity is usually short-lived. */ +const CAPACITY_COOLDOWN_MS = 5 * 60_000; +/** A reported reset further out than this is treated as this. */ +const MAX_COOLDOWN_MS = 7 * 24 * 60 * 60_000; +/** At most this many failovers per thread per hour, so a misreported limit cannot loop. */ +export const MAX_FAILOVERS_PER_HOUR = 6; +/** The run's error item lands around the same time as the run update; let the shell catch up. */ +const SETTLE_DELAY_MS = 1_500; + +const AUTO_FAILOVER_TEXT = + "Auto moved this thread to another subscription because the last one hit its usage limit. Continue where you left off."; + +export interface AutoFailoverPlan { + readonly failedInstanceId: string; + readonly cooldownUntilMs: number; + readonly command: Extract< + Parameters[0], + { readonly type: "message.dispatch" } + >; +} + +/** + * What to do when a run on an Auto thread fails: bench the instance that failed and send the + * thread back through Auto, which then picks the next subscription in the chain. Null when the + * run did not fail for lack of room, or the thread is not on Auto, or is no longer the + * thread's latest run. + */ +export function autoFailoverPlan(input: { + readonly shell: OrchestrationV2ThreadShell; + readonly runId: RunId; + readonly failedInstanceId: string; + readonly nowMs: number; +}): AutoFailoverPlan | null { + const { shell, runId, nowMs } = input; + if ( + shell.latestRunId !== runId || + shell.status !== "failed" || + shell.archivedAt !== null || + shell.settledOverride === "settled" || + shell.pendingRuntimeRequest !== null + ) + return null; + const level = routedAutoLevel(shell.modelSelection); + if (level === undefined) return null; + const limited = shell.lastErrorClass === "usage_limit"; + const noCapacity = !limited && CAPACITY_CODES.has(shell.lastErrorCode ?? ""); + if (!limited && !noCapacity) return null; + const resetMs = shell.usageLimitResetAt ? Date.parse(shell.usageLimitResetAt) : Number.NaN; + const cooldownUntilMs = noCapacity + ? nowMs + CAPACITY_COOLDOWN_MS + : Number.isFinite(resetMs) && resetMs > nowMs + ? Math.min(resetMs, nowMs + MAX_COOLDOWN_MS) + : nowMs + LIMIT_COOLDOWN_MS; + return { + failedInstanceId: input.failedInstanceId, + cooldownUntilMs, + command: { + type: "message.dispatch", + // One failover per failed run, even across duplicate events. + commandId: CommandId.make(`server:auto-failover:${shell.id}:${runId}`), + messageId: MessageId.make(`auto-failover:${shell.id}:${runId}`), + threadId: shell.id, + // The Auto level row; routing replaces it with the next usable subscription. + modelSelection: { instanceId: shell.modelSelection.instanceId, model: `auto-${level}` }, + text: AUTO_FAILOVER_TEXT, + attachments: [], + createdBy: "agent", + creationSource: "server", + dispatchMode: { type: "start_immediately" }, + }, + }; +} + +/** Keeps the timestamps of recent failovers under the hourly cap; true when one more fits. */ +export function admitFailover(history: Array, nowMs: number): boolean { + const recent = history.filter((at) => nowMs - at < 60 * 60_000); + history.splice(0, history.length, ...recent); + if (recent.length >= MAX_FAILOVERS_PER_HOUR) return false; + history.push(nowMs); + return true; +} + +/** + * Fork feature: when a run on an Auto thread fails because its subscription hit a usage limit + * (or has no capacity), the thread moves on at once to the next subscription Auto picks, instead + * of waiting hours for that account to reset. + */ +export const make = Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const history = new Map>(); + + const failOver = Effect.fn("AutoFailoverService.failOver")( + function* (threadId: ThreadId, runId: RunId, failedInstanceId: string) { + yield* Effect.sleep(Duration.millis(SETTLE_DELAY_MS)); + const shell = yield* orchestrator.getThreadShell(threadId); + if (shell === null) return; + const nowMs = DateTime.toEpochMillis(yield* DateTime.now); + const plan = autoFailoverPlan({ shell, runId, failedInstanceId, nowMs }); + if (plan === null) return; + markAutoCooldown(plan.failedInstanceId, plan.cooldownUntilMs); + const threadHistory = history.get(threadId) ?? []; + history.set(threadId, threadHistory); + if (!admitFailover(threadHistory, nowMs)) { + yield* Effect.logWarning("auto failover skipped: hourly cap reached", { threadId }); + return; + } + yield* Effect.logInfo("auto failover", { + threadId, + runId, + failedInstanceId, + errorClass: shell.lastErrorClass, + errorCode: shell.lastErrorCode, + cooldownUntil: DateTime.formatIso(DateTime.makeUnsafe(plan.cooldownUntilMs)), + }); + yield* orchestrator.dispatch(plan.command); + }, + (effect, threadId) => + effect.pipe( + Effect.catch((cause) => + // No usable subscription left: the usage-limit recovery worker still resumes at reset. + Effect.logWarning("auto failover did not dispatch", { threadId, cause }), + ), + ), + ); + + const start = Effect.fn("AutoFailoverService.start")(function* () { + const pending = yield* FiberMap.make(); + yield* forkParked( + Stream.runForEach(orchestrator.streamDomainEvents, (event) => + event.type === "run.updated" && event.payload.status === "failed" + ? FiberMap.run( + pending, + event.threadId, + failOver(event.threadId, event.payload.id, event.payload.providerInstanceId), + ) + : Effect.void, + ), + ); + }); + return { start }; +}); diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index b8a30e277446..c21aab7da65b 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -86,6 +86,7 @@ import * as KeyedLock from "@t3tools/shared/KeyedLock"; import { modelSelectionsEqual } from "@t3tools/shared/model"; import { expandAssistantCitationsForProvider } from "@t3tools/shared/assistantCitations"; import { isAutoModelSelection, resolveAutoModelSelection } from "@t3tools/shared/autoModel"; +import { isAutoCoolingDown } from "./AutoCooldown.ts"; import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import { modelSwitchSince } from "./modelSwitch.ts"; import { contextBoundaryOrdinal, isScheduledFreshRun } from "./contextBoundary.ts"; @@ -16878,11 +16879,13 @@ const withAutoModelRouting = Effect.fn("OrchestratorV2.withAutoModelRouting")(fu ? ((yield* orchestrator.getThreadShell(threadId).pipe(Effect.orElseSucceed(() => null))) ?.modelSelection ?? null) : null; + const now = DateTime.toEpochMillis(yield* DateTime.now); const resolution = resolveAutoModelSelection({ selection, providers: Option.isSome(registry) ? yield* registry.value.getProviders : [], - now: DateTime.toEpochMillis(yield* DateTime.now), + now, current, + blocked: (instanceId) => isAutoCoolingDown(instanceId, now), }); if (resolution === null) { return yield* new OrchestratorCommandRejectedError({ diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index ab3bbeb1d186..db8ff9f4e53d 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -219,6 +219,7 @@ import * as ProjectStore from "./orchestration-v2/ProjectStore.ts"; import * as ThreadSearch from "./orchestration-v2/ThreadSearch.ts"; import * as ThreadSettlementService from "./orchestration-v2/ThreadSettlementService.ts"; import * as IdleCompactionService from "./orchestration-v2/IdleCompactionService.ts"; +import * as AutoFailoverService from "./orchestration-v2/AutoFailoverService.ts"; import * as ThreadPullRequestService from "./orchestration-v2/ThreadPullRequestService.ts"; import * as ThreadIssueService from "./orchestration-v2/ThreadIssueService.ts"; import * as RunFinalizationService from "./orchestration-v2/RunFinalizationService.ts"; @@ -634,6 +635,10 @@ const layerThreadSettlementWorker = Layer.effectDiscard( ThreadSettlementService.make.pipe(Effect.flatMap((service) => service.start())), ).pipe(Layer.provide(layerPullRequestService), Layer.provide(ProjectionStoreV2.layer)); +const layerAutoFailoverWorker = Layer.effectDiscard( + AutoFailoverService.make.pipe(Effect.flatMap((service) => service.start())), +); + const layerIdleCompactionWorker = Layer.effectDiscard( IdleCompactionService.make.pipe(Effect.flatMap((service) => service.start())), ).pipe(Layer.provide(ProjectionStoreV2.layer)); @@ -693,6 +698,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( HeldHooksWaker.layer, layerThreadSettlementWorker, layerIdleCompactionWorker, + layerAutoFailoverWorker, StorageCleanup.layer.pipe(Layer.provide(ProjectionStoreV2.layer)), DatabaseStorage.layer.pipe( Layer.provide(ProjectionMaintenance.layer), diff --git a/docs/progress.md b/docs/progress.md index 1db4eaeb2169..236f4c4d9f34 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -74,3 +74,11 @@ - Numbers: autoModel 12/12, handoff + contextWindow 39/39 (a recursion the stamp caused was caught by the handoff test); shared, client-runtime, web, mobile and server typecheck clean. Checked in a clean incognito browser on a scratch copy of hub2's data: a thread started on Auto Low over the CLI shows Auto Low in the composer. - Deploy: service now runs from `~/.t3/fork-current` (a symlink to the deploy checkout), so a new build goes into a fresh checkout and the restart flips the link. - Next: hub (link it first) and a fork build of the PC desktop app; the stock app still shows the concrete model. + +## 2026-11-14: Auto fails over to the next subscription the moment one hits its limit + +- What: `AutoFailoverService` watches failed runs. When a run on an Auto thread fails with a usage limit (`usage_limit` class: Claude 429 / 5-hour / weekly, Codex `usageLimitExceeded`, Antigravity `RESOURCE_EXHAUSTED`) or no capacity (`UNAVAILABLE`, Claude 529), it benches that provider instance (`AutoCooldown`, until the reported reset, else 30 min; 5 min for no capacity) and sends the thread back through Auto with "Continue where you left off". Auto routing (`resolveAutoModelSelection`) skips benched instances, the sticky current one included. At most 6 failovers per thread per hour. +- Why: Auto routed only when a message was sent. A limit hit mid-work left the thread failed, and the upstream recovery worker resumed it on the same account hours later, at reset. Tomáš wants Auto to chain across all subscriptions as soon as one runs out. The PC's own DB showed 28 failed runs in two days, most of them limit errors (429, quota, capacity) that should have moved on. +- Numbers: autoModel 13/13 (new blocked case), AutoFailoverService 6/6; server typecheck clean. +- Limits: the bench is in memory, so a server restart forgets it (the usage report takes over). A failure whose session error differs from the run's error item has no error class and is not failed over. +- Next: build the PC desktop app from `tomas/pc-nightly`; deploy to hub/hub2. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index e3b6e708f89d..7391bb9fa06f 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -304,6 +304,24 @@ describe("resolveAutoModelSelection", () => { expect(autoLevelSelection(plain)).toBe(plain); }); + it("skips blocked instances, the thread's current one included", () => { + const current = { instanceId: ProviderInstanceId.make("claudeAuto"), model: "claude-opus-5-5" }; + const calm = [claude("claudeAuto", 20), claude("claudeAutoB", 5)]; + const blocked = (instanceId: string) => instanceId === "claudeAuto"; + expect( + resolveAutoModelSelection({ selection: auto(), providers: calm, now, current, blocked }), + ).toMatchObject({ sticky: false, selection: { instanceId: "claudeAutoB" } }); + expect( + resolveAutoModelSelection({ + selection: auto(), + providers: calm, + now, + current, + blocked: () => true, + }), + ).toBeNull(); + }); + it("returns null when nothing is usable", () => { const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; expect(resolveAutoModelSelection({ selection: auto(), providers, now })).toBeNull(); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 74519c6e38e5..d4eaee1d0dad 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -131,6 +131,11 @@ export function isAutoModelSelection(selection: ModelSelection | null | undefine } /** A routed thread's model as the Auto level it came from, for pickers; others unchanged. */ +/** The Auto level a routed thread runs at, or undefined for a thread not on Auto. */ +export function routedAutoLevel(selection: ModelSelection | null | undefined) { + return stampedLevel(selection); +} + export function autoLevelSelection( selection: T, ): T | ModelSelection { @@ -252,9 +257,16 @@ export function resolveAutoModelSelection(input: { readonly providers: ReadonlyArray; readonly now: number; readonly current?: ModelSelection | null; + /** + * Instances (and models) that just failed with a usage limit or no capacity, which the usage + * report may not show yet. Auto skips them, the thread's current model included. + */ + readonly blocked?: (instanceId: string, model: string) => boolean; }): AutoResolution | null { const level = autoLevelOf(input.selection); const candidates = AUTO_CANDIDATES[level]; + const open = (provider: ServerProvider, model: string) => + usable(provider, model, input.now) && !input.blocked?.(provider.instanceId, model); const current = input.current; if (current && !isAutoModelSlug(current.model)) { @@ -265,7 +277,7 @@ export function resolveAutoModelSelection(input: { if ( provider && candidate && - usable(provider, candidate.model, input.now) && + open(provider, candidate.model) && peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT ) { return { selection: toSelection(provider, candidate, level), level, sticky: true }; @@ -277,7 +289,7 @@ export function resolveAutoModelSelection(input: { .filter( (provider) => provider.driver === (candidate.driver as ProviderDriverKind) && - usable(provider, candidate.model, input.now), + open(provider, candidate.model), ) // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. .sort(compareInstances); From 936afe6bf6afa00ec53b592e3d850957b1bb428d Mon Sep 17 00:00:00 2001 From: radys-s Date: Sun, 15 Nov 2026 14:59:37 +0100 Subject: [PATCH 083/230] fix(auto): return to the better model after a reset; failover follows auto-resume Review of the failover commit before it went on the PC: - A thread that failed over to a weaker model stayed there while that account was under 90% used, even after the better account reset. The sticky rule now gives way when a better candidate has room. - Failover follows the autoResumeLimitedThreads setting: off still benches the failed instance, but sends nothing on its own. - Failover skips a provider's own subagent threads, which cannot receive messages. --- .../AutoFailoverService.test.ts | 17 +++++++++++++ .../orchestration-v2/AutoFailoverService.ts | 10 +++++++- docs/progress.md | 9 +++++++ packages/shared/src/autoModel.test.ts | 22 ++++++++++++++++ packages/shared/src/autoModel.ts | 25 ++++++++++++++----- 5 files changed, 76 insertions(+), 7 deletions(-) diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts index e037eb675462..078076aca8a2 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts @@ -25,6 +25,12 @@ function shell(overrides: Partial> = {}): OrchestrationV ], }, latestRunId: runId, + lineage: { + rootThreadId: ThreadId.make("t1"), + parentThreadId: null, + relationshipToParent: null, + }, + creationSource: "user", status: "failed", lastErrorClass: "usage_limit", lastErrorCode: "api_error_429", @@ -86,6 +92,17 @@ describe("autoFailoverPlan", () => { }); describe("admitFailover", () => { + it("leaves a provider's own subagent alone, which cannot receive messages", () => { + const lineage = { + rootThreadId: ThreadId.make("t0"), + parentThreadId: ThreadId.make("t0"), + relationshipToParent: "subagent", + }; + expect(plan(shell({ lineage, creationSource: "provider" }))).toBeNull(); + // A delegate_task child takes messages like any thread. + expect(plan(shell({ lineage, creationSource: "agent" }))).not.toBeNull(); + }); + it("caps failovers per thread per hour", () => { const history: Array = []; for (let i = 0; i < MAX_FAILOVERS_PER_HOUR; i++) diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.ts b/apps/server/src/orchestration-v2/AutoFailoverService.ts index e5185172de09..b91420a90553 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.ts @@ -1,5 +1,6 @@ import { CommandId, + isProviderNativeSubagentThread, MessageId, type OrchestrationV2ThreadShell, type RunId, @@ -13,6 +14,7 @@ import * as FiberMap from "effect/FiberMap"; import * as Stream from "effect/Stream"; import { forkParked } from "../serverActivation.ts"; +import * as ServerSettings from "../serverSettings.ts"; import { markAutoCooldown } from "./AutoCooldown.ts"; import * as Orchestrator from "./Orchestrator.ts"; @@ -64,7 +66,9 @@ export function autoFailoverPlan(input: { shell.status !== "failed" || shell.archivedAt !== null || shell.settledOverride === "settled" || - shell.pendingRuntimeRequest !== null + shell.pendingRuntimeRequest !== null || + // A provider's own subagent cannot receive messages; its parent sees the failure. + isProviderNativeSubagentThread(shell) ) return null; const level = routedAutoLevel(shell.modelSelection); @@ -114,6 +118,7 @@ export function admitFailover(history: Array, nowMs: number): boolean { */ export const make = Effect.gen(function* () { const orchestrator = yield* Orchestrator.OrchestratorV2; + const settings = yield* ServerSettings.ServerSettingsService; const history = new Map>(); const failOver = Effect.fn("AutoFailoverService.failOver")( @@ -124,7 +129,10 @@ export const make = Effect.gen(function* () { const nowMs = DateTime.toEpochMillis(yield* DateTime.now); const plan = autoFailoverPlan({ shell, runId, failedInstanceId, nowMs }); if (plan === null) return; + // Bench the instance either way, so the next message the user sends routes around it. markAutoCooldown(plan.failedInstanceId, plan.cooldownUntilMs); + // The same switch as resuming at reset: off means T3 sends nothing on its own. + if (!(yield* settings.getSettings).autoResumeLimitedThreads) return; const threadHistory = history.get(threadId) ?? []; history.set(threadId, threadHistory); if (!admitFailover(threadHistory, nowMs)) { diff --git a/docs/progress.md b/docs/progress.md index 236f4c4d9f34..3b15d3cdc7c9 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -82,3 +82,12 @@ - Numbers: autoModel 13/13 (new blocked case), AutoFailoverService 6/6; server typecheck clean. - Limits: the bench is in memory, so a server restart forgets it (the usage report takes over). A failure whose session error differs from the run's error item has no error class and is not failed over. - Next: build the PC desktop app from `tomas/pc-nightly`; deploy to hub/hub2. + +## 2026-11-15: Auto failover review fixes, and a way back to the better model + +- What: (1) Auto's sticky rule now gives way when a better candidate for the level has room again. Before, a thread that failed over to a weaker model (say Grok) stayed there for good while that account was under 90% used, even after Claude reset. (2) Failover follows the `autoResumeLimitedThreads` setting: off means the failed instance is still benched (the next message the user sends routes around it), but T3 sends nothing on its own. (3) Failover skips a provider's own subagent threads, which cannot receive messages. +- Why: review of `d25e0609c7` before it went on the PC. The failover sends turns by itself, so a mistake there spends every subscription. The one-way downgrade contradicted the Auto skill, which says a provider re-enters the chain when its window resets. +- Checked and left alone: the domain event stream starts at the latest sequence, so a server restart does not replay old failed runs into failovers. A failover and the upstream reset-resume cannot both fire: the resume needs the thread's latest run to be the failed one. The return to a better model needs that account under 90%, so a thread does not hop back onto an account about to run out. +- Numbers: autoModel 14/14, AutoFailoverService 7/7, server typecheck 0 errors. +- Cost: moving back up is one more provider handoff (a thread summary). It happens once per reset, on the next message. +- Next: build the PC desktop app from `tomas/pc-nightly` and install it. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index 7391bb9fa06f..d179263a94a5 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -322,6 +322,28 @@ describe("resolveAutoModelSelection", () => { ).toBeNull(); }); + it("returns from a weaker fallback once a better model has room again", () => { + const grok = { + ...claude("grok", 0, false), + driver: ProviderDriverKind.make("grok"), + models: [{ slug: "grok-4.7", name: "Grok 4.7", isCustom: false, capabilities: null }], + usageLimits: undefined, + } as unknown as ServerProvider; + const current = { instanceId: ProviderInstanceId.make("grok"), model: "grok-4.7" }; + const resolve = (claudeUsed: number) => + resolveAutoModelSelection({ + selection: auto(), + providers: [claude("claudeAuto", claudeUsed), grok], + now, + current, + }); + // Claude is back: the thread leaves Grok. + expect(resolve(10)).toMatchObject({ sticky: false, selection: { instanceId: "claudeAuto" } }); + // Claude is nearly out or exhausted: no hop back that would fail again at once. + expect(resolve(95)).toMatchObject({ sticky: true, selection: { instanceId: "grok" } }); + expect(resolve(100)).toMatchObject({ sticky: true, selection: { instanceId: "grok" } }); + }); + it("returns null when nothing is usable", () => { const providers = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; expect(resolveAutoModelSelection({ selection: auto(), providers, now })).toBeNull(); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index d4eaee1d0dad..2ee6fa04460e 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -130,12 +130,12 @@ export function isAutoModelSelection(selection: ModelSelection | null | undefine return isAutoModelSlug(selection?.model) || stampedLevel(selection) !== undefined; } -/** A routed thread's model as the Auto level it came from, for pickers; others unchanged. */ /** The Auto level a routed thread runs at, or undefined for a thread not on Auto. */ export function routedAutoLevel(selection: ModelSelection | null | undefined) { return stampedLevel(selection); } +/** A routed thread's model as the Auto level it came from, for pickers; others unchanged. */ export function autoLevelSelection( selection: T, ): T | ModelSelection { @@ -248,9 +248,9 @@ interface AutoResolution { } /** - * Keeps the thread's model while it fits this level and is under 90% used (no account hop, no - * lost prompt cache); otherwise the first usable candidate on the best instance (see - * `compareInstances`). Null when nothing is usable. + * Keeps the thread's model while it fits this level, is under 90% used and no better candidate + * has room (no account hop, no lost prompt cache); otherwise the first usable candidate on the + * best instance (see `compareInstances`). Null when nothing is usable. */ export function resolveAutoModelSelection(input: { readonly selection: ModelSelection; @@ -271,14 +271,27 @@ export function resolveAutoModelSelection(input: { const current = input.current; if (current && !isAutoModelSlug(current.model)) { const provider = input.providers.find((entry) => entry.instanceId === current.instanceId); - const candidate = candidates.find( + const rank = candidates.findIndex( (entry) => entry.driver === provider?.driver && entry.model === current.model, ); + const candidate = candidates[rank]; + // A thread that fell back to a weaker model returns once a better one has room again. + const betterHasRoom = candidates + .slice(0, Math.max(rank, 0)) + .some((better) => + input.providers.some( + (entry) => + entry.driver === (better.driver as ProviderDriverKind) && + open(entry, better.model) && + hasRoom(entry), + ), + ); if ( provider && candidate && open(provider, candidate.model) && - peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT + hasRoom(provider) && + !betterHasRoom ) { return { selection: toSelection(provider, candidate, level), level, sticky: true }; } From 54f5e681b35d7bcc335ecfac3b63cc1b4f8ad453 Mon Sep 17 00:00:00 2001 From: radys-s Date: Sun, 15 Nov 2026 21:12:52 +0100 Subject: [PATCH 084/230] fix: Resume works on providers without native resume; limited threads move to Auto On the PC a thread stuck on Grok after Claude hit its limit: every Resume failed with "Native resume is unavailable" and the thread never moved on. - Resume on a provider without native resume starts an ordinary turn that asks the agent to continue, instead of failing. - A thread not on Auto that hits a usage limit fails over through Auto at the level its model implies. Delegated threads keep their model. --- .../AutoFailoverService.test.ts | 30 +++++++++++------- .../orchestration-v2/AutoFailoverService.ts | 20 +++++++++--- .../ProviderTurnStartService.test.ts | 22 +++++-------- .../ProviderTurnStartService.ts | 31 +++++++++---------- docs/progress.md | 8 +++++ 5 files changed, 65 insertions(+), 46 deletions(-) diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts index 078076aca8a2..f35ce55d2995 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts @@ -71,20 +71,28 @@ describe("autoFailoverPlan", () => { expect(result?.cooldownUntilMs).toBe(now + 5 * 60_000); }); - it("leaves other failures, non-Auto threads and stale runs alone", () => { + it("moves a hand-picked thread to Auto at the level its model implies", () => { + const picked = (model: string) => + shell({ modelSelection: { instanceId: ProviderInstanceId.make("grok"), model } }); + expect(plan(picked("grok-4.7"))?.command.modelSelection).toEqual({ + instanceId: "grok", + model: "auto-medium", + }); + expect(plan(picked("claude-fable-5-2"))?.command.modelSelection?.model).toBe("auto-high"); + expect(plan(picked("claude-haiku-5-5"))?.command.modelSelection?.model).toBe("auto-low"); + // A delegated thread keeps the model its parent chose. + const delegated = { + rootThreadId: ThreadId.make("t0"), + parentThreadId: ThreadId.make("t0"), + relationshipToParent: "subagent", + }; + expect(plan(shell({ ...picked("grok-4.7"), lineage: delegated }))).toBeNull(); + }); + + it("leaves other failures and stale runs alone", () => { expect( plan(shell({ lastErrorClass: "provider_error", lastErrorCode: "api_error_404" })), ).toBeNull(); - expect( - plan( - shell({ - modelSelection: { - instanceId: ProviderInstanceId.make("claudeAgent"), - model: "claude-opus-5-5", - }, - }), - ), - ).toBeNull(); expect(plan(shell({ latestRunId: RunId.make("run:newer") }))).toBeNull(); expect(plan(shell({ status: "idle" }))).toBeNull(); expect(plan(shell({ settledOverride: "settled" }))).toBeNull(); diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.ts b/apps/server/src/orchestration-v2/AutoFailoverService.ts index b91420a90553..0b491a57b9c2 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.ts @@ -1,5 +1,6 @@ import { CommandId, + isDelegatedAppThread, isProviderNativeSubagentThread, MessageId, type OrchestrationV2ThreadShell, @@ -51,8 +52,8 @@ export interface AutoFailoverPlan { /** * What to do when a run on an Auto thread fails: bench the instance that failed and send the * thread back through Auto, which then picks the next subscription in the chain. Null when the - * run did not fail for lack of room, or the thread is not on Auto, or is no longer the - * thread's latest run. + * run did not fail for lack of room, or the thread is a delegated one not on Auto, or the run is + * no longer the thread's latest. */ export function autoFailoverPlan(input: { readonly shell: OrchestrationV2ThreadShell; @@ -71,8 +72,12 @@ export function autoFailoverPlan(input: { isProviderNativeSubagentThread(shell) ) return null; - const level = routedAutoLevel(shell.modelSelection); - if (level === undefined) return null; + // A thread not on Auto (an older thread, or one where a model was picked by hand) moves to + // Auto at the level its model implies: a limit there means the picked model is out anyway. + // Delegated threads keep the model their parent chose; their parent sees the failure. + const routed = routedAutoLevel(shell.modelSelection); + if (routed === undefined && isDelegatedAppThread(shell)) return null; + const level = routed ?? impliedAutoLevel(shell.modelSelection.model); const limited = shell.lastErrorClass === "usage_limit"; const noCapacity = !limited && CAPACITY_CODES.has(shell.lastErrorCode ?? ""); if (!limited && !noCapacity) return null; @@ -102,6 +107,13 @@ export function autoFailoverPlan(input: { }; } +/** The Auto level whose orchestrator is closest to a hand-picked model. */ +function impliedAutoLevel(model: string): "low" | "medium" | "high" { + if (/fable|gpt-6\.1-sol|astra/i.test(model)) return "high"; + if (/sonnet|haiku|flash|opencode\/|luna/i.test(model)) return "low"; + return "medium"; +} + /** Keeps the timestamps of recent failovers under the hourly cap; true when one more fits. */ export function admitFailover(history: Array, nowMs: number): boolean { const recent = history.filter((at) => nowMs - at < 60 * 60_000); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index b3d39ef1c607..627c6a151ac2 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -2254,7 +2254,9 @@ effectIt.effect("sends new steering text when restarting a manual continuation", }), ); -effectIt.effect("refuses unsupported resume instead of manufacturing a user prompt", () => +// Fork: upstream failed here with "Native resume is unavailable", which left Grok, OpenCode and +// Antigravity threads stuck on Resume. The fork starts an ordinary turn that asks to continue. +effectIt.effect("asks to continue when the provider cannot resume natively", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ text: "", @@ -2263,20 +2265,10 @@ effectIt.effect("refuses unsupported resume instead of manufacturing a user prom sideChat: { contextRun: "delivered" }, }); yield* harness.start; - expect(harness.startTurn).not.toHaveBeenCalled(); - expect(harness.startRootRun).not.toHaveBeenCalled(); - expect(harness.settledRuns).toEqual(["failed"]); - expect(harness.projection().turnItems).toEqual( - expect.arrayContaining([ - expect.objectContaining({ - type: "error", - failure: expect.objectContaining({ - message: - "This provider cannot resume without a new message. Send a message to continue.", - }), - }), - ]), - ); + expect(harness.startTurn.mock.calls.map(([turn]) => turn.message.text)).toEqual([ + "Continue where you left off.", + ]); + expect(harness.settledRuns).not.toContain("failed"); }), ); diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index cf332e010d6a..d36d53f3e072 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -133,6 +133,9 @@ const isProviderAdapterOpenSessionError = Schema.is( ProviderAdapter.ProviderAdapterOpenSessionError, ); +/** Sent in place of a native resume the provider does not support. */ +const MANUAL_RESUME_CONTINUE_TEXT = "Continue where you left off."; + /** * Claude refuses these before it reads the prompt: replacing a process running background work, * launch arguments whose appended system prompt or settings cannot be read, or MCP registration @@ -942,10 +945,17 @@ export const layer: Layer.Layer< }); let effectiveHandoffs = handoffs; let resumeFellBack = false; - const userText = projectComposerContextForProvider({ - text: providerMessage.text, - records: providerMessage.context?.records ?? [], - }); + // Fork: Resume on a provider with no native resume (Grok, OpenCode, Antigravity, or a run + // that moved to another provider) used to fail with "Native resume is unavailable". It now + // starts an ordinary turn that asks the agent to continue. + const continueInstead = + manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined; + const userText = continueInstead + ? MANUAL_RESUME_CONTINUE_TEXT + : projectComposerContextForProvider({ + text: providerMessage.text, + records: providerMessage.context?.records ?? [], + }); // Native goal commands go verbatim; handoff history waits a turn. const goalDriver = session.driver === "codex" || @@ -1708,17 +1718,6 @@ export const layer: Layer.Layer< legacyInputRunIds, budget, } = handoffContext; - if (manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined) { - yield* settleStartFailure({ - signal: "resume-unsupported", - title: "Native resume is unavailable", - error: new ProviderAdapter.ProviderResumeUnsupportedError({ - driver: session.driver, - providerThreadId: providerThread.id, - }), - }); - return; - } const retryHandoff = resumedRetryHandoff ?? (yield* prepareRetryHandoff(handoffContext)); const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, @@ -2039,7 +2038,7 @@ export const layer: Layer.Layer< .filter((turn) => turn.providerThreadId === providerThread.id) .map((turn) => turn.ordinal), ) + 1, - resume: manualResume && unsentResumeMessage === undefined, + resume: manualResume && unsentResumeMessage === undefined && !continueInstead, nativeThreadHasTurns: nativeInputRunIds.size > 0 || (legacyInputRunIds.size > 0 && diff --git a/docs/progress.md b/docs/progress.md index 3b15d3cdc7c9..069401bf3429 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -91,3 +91,11 @@ - Numbers: autoModel 14/14, AutoFailoverService 7/7, server typecheck 0 errors. - Cost: moving back up is one more provider handoff (a thread summary). It happens once per reset, on the next message. - Next: build the PC desktop app from `tomas/pc-nightly` and install it. + +## 2026-11-15: Resume works on every provider; limited hand-picked threads move to Auto + +- What happened (PC, thread "Port Hub T3 App Improvements to PC"): Claude hit its 5-hour limit. The thread was not on Auto (it started on the Auto instance before Auto existed, with a plain Opus model), so no failover ran. The composer was switched to Grok and Resume pressed. Grok has no native resume, so each Resume failed at once with "Native resume is unavailable". The one "continue" that reached Grok ran a few tool calls, then hit Grok's free limit, which T3 cannot see in usage windows. Every later "continue" went to Grok again and failed. Result: about ten turns with no answer. +- Fix 1 (`ProviderTurnStartService`): Resume on a provider without native resume now starts an ordinary turn with "Continue where you left off." (plus the handoff context when the provider changed) instead of failing. Upstream's test "refuses unsupported resume" was rewritten to the new behavior. +- Fix 2 (`AutoFailoverService`): a thread not on Auto that hits a usage limit now fails over through Auto at the level its model implies (Fable/Sol/Astra high; Sonnet/Haiku/Flash/OpenCode/Luna low; else medium). Delegated threads not on Auto are left alone: their parent chose the model. +- Setup repo: `fallbackModelSelection` (Grok) is cleared by `apply-auto-settings.py`; the health check warns while it is set. +- Numbers: AutoFailoverService 8/8; ProviderTurnStartService 65/69, the same 4 failures as before the change (Windows-only git/startup tests); server typecheck 0 errors. From 46149c94904375cb6de9e0e0c6f5521b46c10b4e Mon Sep 17 00:00:00 2001 From: radys-s Date: Mon, 16 Nov 2026 08:32:10 +0100 Subject: [PATCH 085/230] fix: let a thread switch providers after a failed failover turn MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When Auto failover moved a thread to Grok and Grok hit its limit on the first turn, the thread kept Grok as its selection with no provider thread for that instance. The client only allowed a handoff from a provider thread matching the current selection, so the picker locked every other provider ("Claude is unavailable in this thread"). The server hands off from the app's own run history, so any provider thread of this app thread is enough. The empty case stays locked as before. Origin: Tomáš's screenshot in thread 'Agent Skills and Design Guide Overhaul' (2026-11-16). --- .../src/state/threadWorkflows.test.ts | 16 +++++++++++++++- .../client-runtime/src/state/threadWorkflows.ts | 12 ++++-------- 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts index 3fe571e84b5b..cace83a3ab3b 100644 --- a/packages/client-runtime/src/state/threadWorkflows.test.ts +++ b/packages/client-runtime/src/state/threadWorkflows.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vite-plus/test"; -import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts"; +import { ProviderInstanceId, type OrchestrationV2ThreadProjection } from "@t3tools/contracts"; import { canForkProjectedAssistantItem, @@ -64,6 +64,20 @@ describe("thread workflows", () => { }), ).toBe(true); expect(threadSupportsProviderHandoff({ ...projection, providerThreads: [] })).toBe(false); + // Failover moved the selection to Grok, whose first turn failed on its limit. + expect( + threadSupportsProviderHandoff({ + ...projection, + thread: { + ...projection.thread, + modelSelection: { + instanceId: ProviderInstanceId.make("grok"), + model: "grok-4.7", + }, + }, + runs: [{ ...projection.runs[0]!, status: "failed" }], + }), + ).toBe(true); }); it("sorts queued messages and gates promotion from capabilities", () => { diff --git a/packages/client-runtime/src/state/threadWorkflows.ts b/packages/client-runtime/src/state/threadWorkflows.ts index ef39233707a7..5b9a7edc84b9 100644 --- a/packages/client-runtime/src/state/threadWorkflows.ts +++ b/packages/client-runtime/src/state/threadWorkflows.ts @@ -112,14 +112,10 @@ export function threadSupportsProviderHandoff(projection: Projection | null | un if (projection.thread.historyOrigin === "v1_import" || projection.runs.length === 0) return true; // Detaching a stopped session removes it from the projection. The server still - // hands off from saved app history, which needs the source provider thread but - // not its native ref. - return projection.providerThreads.some( - (thread) => - thread.id === projection.thread.activeProviderThreadId && - thread.appThreadId === projection.thread.id && - thread.providerInstanceId === projection.thread.modelSelection.instanceId, - ); + // hands off from saved app history. A switch whose first turn failed (a limit hit + // right away) leaves the selection on an instance with no matching provider + // thread; any provider thread of this app thread is enough to hand off from. + return projection.providerThreads.some((thread) => thread.appThreadId === projection.thread.id); } export function getUserQueuedThreadRuns( From 67bfeb91bab54ace64605e00b9b7a6393153d129 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Wed, 18 Nov 2026 12:29:22 +0100 Subject: [PATCH 086/230] chore(i18n): add the fork's Usage copy to the web catalogs MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Upstream now translates the whole app and CI fails when a committed catalog drifts from the source. The fork's pooled usage view, reset advice and subscriptions list now wrap their copy in and gt(), so `vp run i18n:generate` adds those keys (English in every locale until translated) and drops "left", which the fork's pooled card replaced. Origin: Tomáš's request to bring the fork up to current upstream. --- apps/web/src/i18n/translations/de.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/en.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/es.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/fr.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/ja.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/ko.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/pt-BR.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/ru.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/sv.json | 18 +++++++++++++++++- apps/web/src/i18n/translations/zh.json | 18 +++++++++++++++++- 10 files changed, 170 insertions(+), 10 deletions(-) diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 46df7424ab0f..894f421428da 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -11861,8 +11861,20 @@ "1b16346722b65812": "{timeLeft} % des Zeitfensters übrig", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "0-$-Limit", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "Nutzung verwalten", - "a00e74aaa421c524": "übrig", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "Kein Anbieter in den ausgewählten Umgebungen meldet Abo-Limits.", "87f5d0c61b335f38": "Nutzung in ChatGPT mit deinem verbundenen Konto ansehen.", "5b4c71b36b979e80": "Kosten", @@ -11953,6 +11965,10 @@ "b11af3f3da3d494e": "Die Summen sind unvollständig, während ausgewählte Umgebungen scannen.", "8062808b87ce6032": "Modellpreise", "cf5409d12fc3f53b": "Alle Anbieter", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "Preise nicht geladen", "ed447281261f2d0e": "Nur Lesezugriff", "67633defded66bf7": "Gib eine Modell-ID ein.", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index fc971dba6e05..5b53a8964d6f 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -11869,8 +11869,20 @@ "1b16346722b65812": "{timeLeft}% of the window left", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "$0 cap", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "Manage usage", - "a00e74aaa421c524": "left", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "No provider on the selected environments reports subscription limits.", "87f5d0c61b335f38": "View usage in ChatGPT with your connected account.", "5b4c71b36b979e80": "Cost", @@ -11961,6 +11973,10 @@ "b11af3f3da3d494e": "Totals are partial while selected environments scan.", "8062808b87ce6032": "Model prices", "cf5409d12fc3f53b": "All providers", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "Prices not loaded", "ed447281261f2d0e": "Read-only access", "67633defded66bf7": "Enter a model ID.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 797888016bd4..e2b4e8cf6f2c 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -11854,8 +11854,20 @@ "1b16346722b65812": "Queda un {timeLeft}% de la ventana", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Límite de 0 $", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "Gestionar uso", - "a00e74aaa421c524": "restante", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "Ningún proveedor de los entornos seleccionados informa de límites de suscripción.", "87f5d0c61b335f38": "Consulta el uso en ChatGPT con tu cuenta conectada.", "5b4c71b36b979e80": "Coste", @@ -11946,6 +11958,10 @@ "b11af3f3da3d494e": "Los totales son parciales mientras se escanean los entornos seleccionados.", "8062808b87ce6032": "Precios de modelos", "cf5409d12fc3f53b": "Todos los proveedores", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "No se cargaron los precios", "ed447281261f2d0e": "Acceso de solo lectura", "67633defded66bf7": "Introduce un ID de modelo.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index e06cde54989b..1dc4d182e53f 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -11859,8 +11859,20 @@ "1b16346722b65812": "{timeLeft} % de la fenêtre restant", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Plafond de 0 $", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "Gérer l’utilisation", - "a00e74aaa421c524": "restant", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "Aucun fournisseur des environnements sélectionnés ne signale de limites d’abonnement.", "87f5d0c61b335f38": "Consultez l’utilisation dans ChatGPT avec votre compte connecté.", "5b4c71b36b979e80": "Coût", @@ -11951,6 +11963,10 @@ "b11af3f3da3d494e": "Les totaux sont partiels pendant l’analyse des environnements sélectionnés.", "8062808b87ce6032": "Prix des modèles", "cf5409d12fc3f53b": "Tous les fournisseurs", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "Prix non chargés", "ed447281261f2d0e": "Accès en lecture seule", "67633defded66bf7": "Saisissez un ID de modèle.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 4473bff3ddef..1ef930607954 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -11809,8 +11809,20 @@ "1b16346722b65812": "期間の残り {timeLeft}%", "7aaaff1c6484f25c": "セグメント", "8bcab2ef61de6518": "上限 $0", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "使用量を管理", - "a00e74aaa421c524": "残り", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "選択した環境には、サブスクリプションの上限を報告するプロバイダーがありません。", "87f5d0c61b335f38": "接続したアカウントで ChatGPT の使用量を表示します。", "5b4c71b36b979e80": "コスト", @@ -11901,6 +11913,10 @@ "b11af3f3da3d494e": "選択した環境のスキャン中は、合計は一部のみです。", "8062808b87ce6032": "モデルの価格", "cf5409d12fc3f53b": "すべてのプロバイダー", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "価格が読み込まれていません", "ed447281261f2d0e": "読み取り専用アクセス", "67633defded66bf7": "モデル ID を入力してください。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 68f0b2079436..33491309b1c4 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -11806,8 +11806,20 @@ "1b16346722b65812": "기간 {timeLeft}% 남음", "7aaaff1c6484f25c": "구간", "8bcab2ef61de6518": "$0 한도", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "사용량 관리", - "a00e74aaa421c524": "남음", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "선택한 환경에 구독 한도를 보고하는 제공자가 없습니다.", "87f5d0c61b335f38": "연결된 계정으로 ChatGPT에서 사용량을 확인하세요.", "5b4c71b36b979e80": "비용", @@ -11898,6 +11910,10 @@ "b11af3f3da3d494e": "선택한 환경을 스캔하는 동안에는 합계가 일부만 표시됩니다.", "8062808b87ce6032": "모델 가격", "cf5409d12fc3f53b": "모든 제공자", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "가격을 불러오지 않음", "ed447281261f2d0e": "읽기 전용 액세스", "67633defded66bf7": "모델 ID를 입력하세요.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 5a18a359ecb2..6f1202c25d32 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -11858,8 +11858,20 @@ "1b16346722b65812": "{timeLeft}% da janela restante", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Limite de $0", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "Gerenciar uso", - "a00e74aaa421c524": "restante", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "Nenhum provedor nos ambientes selecionados informa limites de assinatura.", "87f5d0c61b335f38": "Veja o uso no ChatGPT com sua conta conectada.", "5b4c71b36b979e80": "Custo", @@ -11950,6 +11962,10 @@ "b11af3f3da3d494e": "Os totais são parciais enquanto os ambientes selecionados são verificados.", "8062808b87ce6032": "Preços dos modelos", "cf5409d12fc3f53b": "Todos os provedores", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "Preços não carregados", "ed447281261f2d0e": "Acesso somente leitura", "67633defded66bf7": "Informe o ID de um modelo.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 6c7fa00a1545..54501fea12e0 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -11859,8 +11859,20 @@ "1b16346722b65812": "От окна осталось {timeLeft}%", "7aaaff1c6484f25c": "Сегмент", "8bcab2ef61de6518": "Лимит $0", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "Управление использованием", - "a00e74aaa421c524": "осталось", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "Ни один провайдер в выбранных окружениях не сообщает лимиты подписки.", "87f5d0c61b335f38": "Смотрите использование в ChatGPT через подключённый аккаунт.", "5b4c71b36b979e80": "Стоимость", @@ -11951,6 +11963,10 @@ "b11af3f3da3d494e": "Итоги неполные, пока выбранные окружения сканируются.", "8062808b87ce6032": "Цены моделей", "cf5409d12fc3f53b": "Все провайдеры", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "Цены не загружены", "ed447281261f2d0e": "Доступ только для чтения", "67633defded66bf7": "Введите ID модели.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index d02de62557d7..f7a0b7f69cd9 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -11867,8 +11867,20 @@ "1b16346722b65812": "{timeLeft} % av fönstret kvar", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Tak på 0 $", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "Hantera användning", - "a00e74aaa421c524": "kvar", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "Ingen leverantör i de valda miljöerna rapporterar abonnemangsgränser.", "87f5d0c61b335f38": "Visa användning i ChatGPT med ditt anslutna konto.", "5b4c71b36b979e80": "Kostnad", @@ -11959,6 +11971,10 @@ "b11af3f3da3d494e": "Summorna är ofullständiga medan valda miljöer genomsöks.", "8062808b87ce6032": "Modellpriser", "cf5409d12fc3f53b": "Alla leverantörer", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "Priserna har inte lästs in", "ed447281261f2d0e": "Skrivskyddad åtkomst", "67633defded66bf7": "Ange ett modell-id.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index acf5ce304537..555e167b5e00 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -11884,8 +11884,20 @@ "1b16346722b65812": "窗口剩余 {timeLeft}%", "7aaaff1c6484f25c": "分段", "8bcab2ef61de6518": "上限 $0", + "98947080075a0e9f": "of {capacity}%", + "319d956d8dc9626e": "Pool empty", + "7edac2c4173fee09": "Not by {date}", + "649af7801ecb5d6c": "Empty now", + "7b3b4057463829e0": "First empty", + "0cc4fd1cf5ac9270": "now", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "None", + "e7c90232ad94f3ca": "Next reset", + "22f3ae62c7a65e0f": "Burn, last 3h", + "737171d0d80cb0d0": "Burn, window avg", "a16b48709357a5a7": "管理用量", - "a00e74aaa421c524": "剩余", + "e20b23cc4eee52c1": "Reset advice:", + "aca138d5adaa5f69": "Subscriptions", "8bd6f07136317c8f": "选中的环境上没有提供方报告订阅限制。", "87f5d0c61b335f38": "用已连接的账户在 ChatGPT 中查看用量。", "5b4c71b36b979e80": "费用", @@ -11976,6 +11988,10 @@ "b11af3f3da3d494e": "选中的环境仍在扫描,总计暂不完整。", "8062808b87ce6032": "模型价格", "cf5409d12fc3f53b": "所有提供方", + "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", + "b05ed15d19d4a485": "Empty {time}", + "56fb015730a158bc": "projected", + "fc3a1241f943cae6": "Now", "55e99aaf3d0e6af4": "价格未加载", "ed447281261f2d0e": "只读权限", "67633defded66bf7": "请输入模型 ID。", From a618e2f3a74b58c683f6cf1e43fabc71ea7741ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Wed, 18 Nov 2026 12:47:16 +0100 Subject: [PATCH 087/230] docs: log the sync onto upstream 373ec12be6 in progress.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Records how the fork was replayed onto upstream main, which conflicts came up and how they were resolved, and how it was verified. Origin: Tomáš's request to bring the fork up to current upstream. --- docs/progress.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/progress.md b/docs/progress.md index 069401bf3429..d81fcd98b34e 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -99,3 +99,13 @@ - Fix 2 (`AutoFailoverService`): a thread not on Auto that hits a usage limit now fails over through Auto at the level its model implies (Fable/Sol/Astra high; Sonnet/Haiku/Flash/OpenCode/Luna low; else medium). Delegated threads not on Auto are left alone: their parent chose the model. - Setup repo: `fallbackModelSelection` (Grok) is cleared by `apply-auto-settings.py`; the health check warns while it is set. - Numbers: AutoFailoverService 8/8; ProviderTurnStartService 65/69, the same 4 failures as before the change (Windows-only git/startup tests); server typecheck 0 errors. + +## 2026-11-18: Fork synced onto upstream `373ec12be6` + +- What: the 18 fork commits from `1f698f01d9..bd33ae897c` were rebased onto upstream main `373ec12be6` (300 upstream commits newer). `origin/main` is recorded as an ancestor with an `-s ours` merge, as in the previous sync, so the PR merges without a force-push. +- Why: the fork was 300 commits behind upstream two days after the last sync. +- Conflicts: 3 sites in 2 files, all from upstream translating the whole app (#37893): `ProviderModelPicker.tsx` (fork's Auto trigger label vs upstream's `gt()` labels) and `UsageLimitsPooled.tsx` (imports moved to `usageLimitsCopy.ts`). Kept upstream's translated strings and the fork's Auto and pooled-view behavior. +- Adapted to upstream: reset advice (`suggestResetCredit`) moved from `usageLimits.ts` to `usageLimitsCopy.ts`, where upstream now keeps `formatDuration` and other client copy. The fork's pooled view, chart, reset advice and Subscriptions heading wrap their copy in ``/`gt()` (upstream's `no-untranslated-copy` lint), and the web catalogs gained those 17 keys. +- Numbers: `vp run check:changed` all pass (typecheck 42 packages, 492 tests in 25 files, lint, knip, format, react compiler); `vp run i18n:check` pass; `UsageLimitsPooled.browser.test.tsx` 2/2. +- Real run (worktree `.t3`, seeded copy, never `~/.t3/userdata`): Auto High/Medium/Low pinned at the top of Favorites with their routes, Usage → Limits pooled view and reset advice render, one Claude Haiku turn answered. Production build (`apps/web vp run build`, `apps/server node scripts/cli.ts build`) boots on an empty data dir. +- Next: Tomáš switches hub2 and hub to the new build. From 96342ba398280a35ddeb401be9074066a568e0d3 Mon Sep 17 00:00:00 2001 From: radys-s Date: Wed, 18 Nov 2026 12:39:59 +0100 Subject: [PATCH 088/230] feat(auto): run Auto High on Opus at Extra High effort Auto High started with Fable 5.2, which these Claude accounts cannot use, so it always fell through to Opus at plain High. Opus at the xhigh effort level now leads the high chain, Fable is out of it, and the failover heuristic no longer reads Fable as a high model. Requested by Tomas: Auto High should mean Opus at a bigger effort level until Fable is available. --- .../src/orchestration-v2/AutoFailoverService.test.ts | 2 +- apps/server/src/orchestration-v2/AutoFailoverService.ts | 2 +- docs/progress.md | 9 ++++++++- packages/shared/src/autoModel.test.ts | 8 ++++---- packages/shared/src/autoModel.ts | 3 +-- 5 files changed, 15 insertions(+), 9 deletions(-) diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts index f35ce55d2995..21bee86e34e8 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.test.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts @@ -78,7 +78,7 @@ describe("autoFailoverPlan", () => { instanceId: "grok", model: "auto-medium", }); - expect(plan(picked("claude-fable-5-2"))?.command.modelSelection?.model).toBe("auto-high"); + expect(plan(picked("gpt-6.1-sol"))?.command.modelSelection?.model).toBe("auto-high"); expect(plan(picked("claude-haiku-5-5"))?.command.modelSelection?.model).toBe("auto-low"); // A delegated thread keeps the model its parent chose. const delegated = { diff --git a/apps/server/src/orchestration-v2/AutoFailoverService.ts b/apps/server/src/orchestration-v2/AutoFailoverService.ts index 0b491a57b9c2..51531943ae2f 100644 --- a/apps/server/src/orchestration-v2/AutoFailoverService.ts +++ b/apps/server/src/orchestration-v2/AutoFailoverService.ts @@ -109,7 +109,7 @@ export function autoFailoverPlan(input: { /** The Auto level whose orchestrator is closest to a hand-picked model. */ function impliedAutoLevel(model: string): "low" | "medium" | "high" { - if (/fable|gpt-6\.1-sol|astra/i.test(model)) return "high"; + if (/gpt-6\.1-sol|astra/i.test(model)) return "high"; if (/sonnet|haiku|flash|opencode\/|luna/i.test(model)) return "low"; return "medium"; } diff --git a/docs/progress.md b/docs/progress.md index d81fcd98b34e..070a636a2827 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -100,9 +100,16 @@ - Setup repo: `fallbackModelSelection` (Grok) is cleared by `apply-auto-settings.py`; the health check warns while it is set. - Numbers: AutoFailoverService 8/8; ProviderTurnStartService 65/69, the same 4 failures as before the change (Windows-only git/startup tests); server typecheck 0 errors. +## 2026-11-18: Auto High runs Opus 5.5 at Extra High, not Fable + +- What: `AUTO_CANDIDATES.high` now starts with `claude-opus-5-5` at the `xhigh` effort level ("Extra High", one step above High), and Fable 5.2 is gone from the high chain. The Antigravity Opus, Codex Sol/Astra/Luna, Grok and Gemini fallbacks keep their `high` effort. `impliedAutoLevel` (the failover path for hand-picked threads) no longer reads Fable as a high model, since Fable now only sits in the medium chain. +- Why: Tomáš's Claude accounts have no Fable access yet, so Auto High routed to a model that was never usable there and fell through to Opus at plain High. He asked for Auto High to mean Opus at a higher effort. +- Numbers: autoModel 14/14, AutoFailoverService 8/8, claudeModelOptions 7/7. Effort levels the catalog offers for Opus 5.5: low, medium, high, xhigh, max, ultracode, ultrathink; `max` is one step above `xhigh` if he wants the ceiling. +- Next: ship on the PC fork build, then hub and hub2. + ## 2026-11-18: Fork synced onto upstream `373ec12be6` -- What: the 18 fork commits from `1f698f01d9..bd33ae897c` were rebased onto upstream main `373ec12be6` (300 upstream commits newer). `origin/main` is recorded as an ancestor with an `-s ours` merge, as in the previous sync, so the PR merges without a force-push. +- What: the 18 fork commits from `1f698f01d9..bd33ae897c` were rebased onto upstream main `373ec12be6` (300 upstream commits newer). #10 (Auto High on Opus at Extra High), merged to fork main during the sync, comes in through a normal merge. `origin/main` is recorded as an ancestor with an `-s ours` merge, as in the previous sync, so the PR merges without a force-push. - Why: the fork was 300 commits behind upstream two days after the last sync. - Conflicts: 3 sites in 2 files, all from upstream translating the whole app (#37893): `ProviderModelPicker.tsx` (fork's Auto trigger label vs upstream's `gt()` labels) and `UsageLimitsPooled.tsx` (imports moved to `usageLimitsCopy.ts`). Kept upstream's translated strings and the fork's Auto and pooled-view behavior. - Adapted to upstream: reset advice (`suggestResetCredit`) moved from `usageLimits.ts` to `usageLimitsCopy.ts`, where upstream now keeps `formatDuration` and other client copy. The fork's pooled view, chart, reset advice and Subscriptions heading wrap their copy in ``/`gt()` (upstream's `no-untranslated-copy` lint), and the web catalogs gained those 17 keys. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index d179263a94a5..3eea2812219c 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -23,7 +23,7 @@ const effortCapabilities = { id: "effort", label: "Effort", type: "select" as const, - options: ["low", "medium", "high"].map((id) => ({ id, label: id })), + options: ["low", "medium", "high", "xhigh"].map((id) => ({ id, label: id })), }, ], }; @@ -82,9 +82,9 @@ describe("resolveAutoModelSelection", () => { resolveAutoModelSelection({ selection: auto("high"), providers, now })?.selection, ).toEqual({ instanceId: "claudeAuto", - model: "claude-fable-5-2", + model: "claude-opus-5-5", options: [ - { id: "effort", value: "high" }, + { id: "effort", value: "xhigh" }, { id: "auto", value: "high" }, ], }); @@ -283,7 +283,7 @@ describe("resolveAutoModelSelection", () => { providers, now, })?.selection.model; - expect(pick("auto-high")).toBe("claude-fable-5-2"); + expect(pick("auto-high")).toBe("claude-opus-5-5"); expect(pick("auto-medium")).toBe("claude-opus-5-5"); expect(pick("auto-low")).toBe("claude-sonnet-5-5"); expect(isAutoModelSlug("auto-low")).toBe(true); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 2ee6fa04460e..2d31d95c4739 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -59,8 +59,7 @@ const opencode = (model: string, effort: string): AutoCandidate => ({ */ const AUTO_CANDIDATES: Readonly>> = { high: [ - claude("claude-fable-5-2", "high"), - claude("claude-opus-5-5", "high"), + claude("claude-opus-5-5", "xhigh"), antigravity("claude-opus-4-6-thinking", "high"), codex("gpt-6.1-sol", "high"), codex("gpt-6-astra", "high"), From d69328753deb0e18c128e036f5c9ba308fbb767c Mon Sep 17 00:00:00 2001 From: radys-s Date: Wed, 18 Nov 2026 18:40:43 +0100 Subject: [PATCH 089/230] feat(auto): run Auto High on Opus at max effort MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Tomáš asked for the highest available effort after Auto High was set to Extra High; \max\ is one step above \xhigh\ for Opus 5.5. The routing test now pins \max\ for the high level. --- packages/shared/src/autoModel.test.ts | 4 ++-- packages/shared/src/autoModel.ts | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index 3eea2812219c..ff03d6791dc9 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -23,7 +23,7 @@ const effortCapabilities = { id: "effort", label: "Effort", type: "select" as const, - options: ["low", "medium", "high", "xhigh"].map((id) => ({ id, label: id })), + options: ["low", "medium", "high", "xhigh", "max"].map((id) => ({ id, label: id })), }, ], }; @@ -84,7 +84,7 @@ describe("resolveAutoModelSelection", () => { instanceId: "claudeAuto", model: "claude-opus-5-5", options: [ - { id: "effort", value: "xhigh" }, + { id: "effort", value: "max" }, { id: "auto", value: "high" }, ], }); diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 2d31d95c4739..b88b26456a67 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -59,7 +59,7 @@ const opencode = (model: string, effort: string): AutoCandidate => ({ */ const AUTO_CANDIDATES: Readonly>> = { high: [ - claude("claude-opus-5-5", "xhigh"), + claude("claude-opus-5-5", "max"), antigravity("claude-opus-4-6-thinking", "high"), codex("gpt-6.1-sol", "high"), codex("gpt-6-astra", "high"), From 67a634d5c7fc7a2eed4f3aa1923d5dff38ea8acb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Wed, 18 Nov 2026 19:07:48 +0100 Subject: [PATCH 090/230] fix(server): tell Auto-routed Claude turns their level MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Since Auto High runs Opus 5.5 at Extra High (#10), the Auto orchestrator prompt (auto-mode.md), which derives the routing level from the model name, made every Auto High thread route itself as medium. The model had no way to see the level Auto picked. A Claude turn whose selection carries Auto's `auto` stamp now ends its system prompt with `Auto level: `. Hand-picked models are unchanged. The level is part of the compiled selection and its identity, and a level change cannot be applied live, so switching Auto Medium to Auto High on the same model reopens the process with resume instead of keeping a stale line. Requested by Tomáš: Auto High threads routed as medium. --- apps/server/src/claudeModelOptions.ts | 6 ++ .../Adapters/ClaudeAdapterV2.test.ts | 68 +++++++++++++++++++ .../Adapters/ClaudeAdapterV2.ts | 11 ++- docs/progress.md | 9 +++ 4 files changed, 92 insertions(+), 2 deletions(-) diff --git a/apps/server/src/claudeModelOptions.ts b/apps/server/src/claudeModelOptions.ts index c3376ef7ed8d..dc1a073e6347 100644 --- a/apps/server/src/claudeModelOptions.ts +++ b/apps/server/src/claudeModelOptions.ts @@ -5,6 +5,7 @@ import { getProviderOptionDescriptors, resolvePromptInjectedEffort, } from "@t3tools/shared/model"; +import { routedAutoLevel } from "@t3tools/shared/autoModel"; import { BUNDLED_CLAUDE_MODEL_CATALOG, @@ -26,6 +27,8 @@ export interface CompiledClaudeModelSelection { readonly settings: Readonly>; /** The alias of a custom model named like one, which Claude Code would otherwise expand. */ readonly pinnedAlias: string | undefined; + /** The level Auto routed this selection at; undefined for a hand-picked model. */ + readonly autoLevel: string | undefined; readonly queryIdentity: string; } @@ -65,17 +68,20 @@ export function compileClaudeModelSelection( resolveClaudeModelSlug(catalog, selection.model) === apiModelId ? apiModelId : undefined; + const autoLevel = routedAutoLevel(selection); return { apiModelId, effort, promptEffort, settings, pinnedAlias, + autoLevel, queryIdentity: JSON.stringify({ apiModelId, effort: effort ?? null, settings, pinnedAlias: pinnedAlias ?? null, + autoLevel: autoLevel ?? null, }), }; } diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index fe7559f603aa..22da7fe07e05 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -7817,6 +7817,74 @@ describe("ClaudeAdapterV2 background wake turns", () => { ), ); + it.effect( + "tells an Auto-routed turn its level and reopens the process when the level changes", + () => + Effect.gen(function* () { + const harness = yield* makeWakeHarnessWithOptions({ freshQueueOnReopen: true }); + const now = yield* DateTime.now; + const opus = { + instanceId: ClaudeAdapterV2.CLAUDE_DEFAULT_INSTANCE_ID, + model: "claude-opus-5-5", + } satisfies ModelSelection; + const routed = (level: string, effort: string) => + ({ + ...opus, + options: [ + { id: "effort", value: effort }, + { id: "auto", value: level }, + ], + }) satisfies ModelSelection; + const appendText = () => + (harness.getOpenedOptions()?.systemPrompt as { readonly append?: string } | undefined) + ?.append ?? ""; + const runTurn = Effect.fnUntraced(function* (ordinal: number, selection: ModelSelection) { + yield* harness.runtime.startTurn( + makeClaudeTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(`attempt-auto-level:${ordinal}`), + text: `Request ${ordinal}`, + attachments: [], + providerTurnOrdinal: ordinal, + modelSelection: selection, + }), + ); + yield* harness.offerAndWait(turnOneResult); + yield* Queue.take(harness.terminalReceipts); + return harness.getOpenedOptions(); + }); + + const handPicked = yield* runTurn(1, { + ...opus, + options: [{ id: "effort", value: "medium" }], + }); + assert.notInclude(appendText(), "Auto level:"); + + const medium = yield* runTurn(2, routed("medium", "medium")); + assert.notStrictEqual(medium, handPicked); + assert.isTrue(appendText().endsWith("\n\nAuto level: medium")); + + // Only the effort differs between these levels, which would otherwise change live. + const high = yield* runTurn(3, routed("high", "xhigh")); + assert.notStrictEqual(high, medium); + assert.isTrue(appendText().endsWith("\n\nAuto level: high")); + assert.deepEqual(harness.liveSelectionChanges, []); + + assert.strictEqual(yield* runTurn(4, routed("high", "xhigh")), high); + }).pipe( + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // regression: #34549 a model change sent with a steer was shown but never applied to the turn. it.effect("applies a model change sent with a steer to the running turn", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 6f62baaa5083..5fcfc913d867 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2086,7 +2086,10 @@ export const layerQueryRunner: Layer.Layer< type ClaudeFlagSettings = Parameters[0]; -/** Thinking requires a new process. Clearing effort also requires one to reload user settings instead of model defaults. */ +/** + * Thinking requires a new process. Clearing effort also requires one to reload user settings + * instead of model defaults. The Auto level is in the system prompt, which only a new process reads. + */ function canApplyClaudeSelectionLive( live: CompiledClaudeModelSelection, next: CompiledClaudeModelSelection, @@ -2094,7 +2097,8 @@ function canApplyClaudeSelectionLive( return ( live.settings.alwaysThinkingEnabled === next.settings.alwaysThinkingEnabled && (next.effort !== undefined || live.effort === undefined) && - live.pinnedAlias === next.pinnedAlias + live.pinnedAlias === next.pinnedAlias && + live.autoLevel === next.autoLevel ); } @@ -2366,6 +2370,9 @@ export function makeClaudeQueryOptions(input: { ? `\n${T3_CODE_DEVICE_TOOL_INSTRUCTIONS_WITH_TOOL_SEARCH}\n` : "")), ...launchAppendSystemPrompt, + ...(compiledSelection.autoLevel === undefined + ? [] + : [`Auto level: ${compiledSelection.autoLevel}`]), ].join("\n\n"), }, ...(deviceInstructions || input.onStop !== undefined diff --git a/docs/progress.md b/docs/progress.md index 070a636a2827..c3425129e2df 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -116,3 +116,12 @@ - Numbers: `vp run check:changed` all pass (typecheck 42 packages, 492 tests in 25 files, lint, knip, format, react compiler); `vp run i18n:check` pass; `UsageLimitsPooled.browser.test.tsx` 2/2. - Real run (worktree `.t3`, seeded copy, never `~/.t3/userdata`): Auto High/Medium/Low pinned at the top of Favorites with their routes, Usage → Limits pooled view and reset advice render, one Claude Haiku turn answered. Production build (`apps/web vp run build`, `apps/server node scripts/cli.ts build`) boots on an empty data dir. - Next: Tomáš switches hub2 and hub to the new build. + +## 2026-11-18: Auto-routed Claude turns see their level in the system prompt + +- What: when Auto routed a Claude turn, the system prompt ends with one line, `Auto level: `, taken from the `auto` option the router stamps on the selection. Hand-picked models get nothing new. The level is part of the compiled Claude selection, so a level change on a live session (say Auto Medium → Auto High, where only the effort moves on the same Opus 5.5) is no longer applied live: the next turn reopens the process with resume, as a thinking change already does. A level change while a background shell runs is refused the same way. +- Why: since #10, Auto High runs Opus 5.5 at Extra High. `~/.agents/auto-mode.md` told the orchestrator to read its level from its model name (Opus → medium), so every Auto High thread routed itself as medium and could not see the level Auto picked. +- Providers: Claude only. Only the Claude Auto instances (`claudeAuto`, `claudeAutoB`) carry `auto-mode.md`; Codex, Grok, OpenCode and Antigravity have no Auto orchestrator prompt to correct. +- Numbers: the new adapter test failed on base (live effort change, no reopen) and passes; ClaudeAdapterV2 + claudeModelOptions 475/475. Real run on the worktree's seeded `.t3`: one Auto Low thread over the CLI (Sonnet 5.5 at low, Auto's first Low candidate) quoted `Auto level: low` from its system prompt. +- `~/.agents`: `auto-mode.md` and the `auto` skill read the level from that line and fall back to the model name only without it. +- Next: deploy on hub2 and the PC; copy the `~/.agents` change into `radys-s/t3-setup-improvements` for hub. From 2deb4aa67f5e28ae269f6aca775864f4aec327ec Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 10:13:01 +0100 Subject: [PATCH 091/230] fix(shared): a Claude one-model weekly limit blocks only that model MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude reports a weekly allowance for one model as a `seven_day_` window (claudeUsageLimits.ts) without `modelIds`, so exhaustedUsageWindow treated a spent Fable-only allowance as exhausting every model on that account. The server's hub pool check (`windowLimitsModel`) already reads these windows per model. The per-window rule moves into `usageWindowLimitsModel`, which exhaustedUsageWindow now uses and Auto's weekly pace will reuse, so both decide the same way which windows limit a model. The other drivers' rules are unchanged. Origin: weekly-first Auto routing (Tomáš, 2026-11-19), which needs model-scoped weekly windows to count only for their own model. --- packages/shared/src/usageLimits.test.ts | 2 + packages/shared/src/usageLimits.ts | 91 ++++++++++++++----------- 2 files changed, 54 insertions(+), 39 deletions(-) diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index bd616cf5865d..cd47f96a8bcd 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -126,6 +126,8 @@ describe("new thread model fallback", () => { ).toBeDefined(); }); it.each([ + ["claudeAgent", ["seven_day_fable"], "claude-opus-5-5", false, undefined, undefined], + ["claudeAgent", ["seven_day_fable"], "claude-fable-5-2", true, undefined, undefined], ["cursor", ["autoPercentUsed"], "claude-opus-5-5", false, undefined, undefined], ["cursor", ["autoPercentUsed"], "composer-2.5", false, undefined, undefined], ["cursor", ["autoPercentUsed", "apiPercentUsed"], "composer-2.5", true, undefined, undefined], diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index c46c420a226e..2df18df8b4ad 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -23,56 +23,69 @@ import { isLocalLoopbackHost, isWildcardHost } from "./hostClassification.ts"; const MINUTE = 60_000; +/** Whether `window` limits `model`; a window for some models or one pool limits only those. */ +function usageWindowLimitsModel( + provider: ServerProvider, + window: ServerProviderUsageWindow, + model: string, +): boolean { + if (window.modelIds !== undefined && !window.modelIds.includes(model)) return false; + if (window.providerIds !== undefined && !window.providerIds.includes(model.split("/")[0] ?? "")) { + return false; + } + switch (provider.driver) { + case "claudeAgent": + // Claude names a one-model weekly allowance `seven_day_` (see claudeUsageLimits.ts). + return ( + !window.id.startsWith("seven_day_") || + model + .toLowerCase() + .replace(/[^a-z0-9]+/g, "_") + .includes(window.id.slice("seven_day_".length)) + ); + case "antigravity": { + const family = model.match(/^(gemini|claude|gpt)-/)?.[1]; + const pool = window.id.match(/^(gemini|claude|gpt|3p)-/)?.[1]; + return ( + pool === undefined || + family === undefined || + pool === family || + (pool === "3p" && (family === "claude" || family === "gpt")) + ); + } + case "codex": + // Seat-based plans spend credits only past their plan windows, so the credit cap blocks only plans without them. + return ( + window.id !== "individual" || + !(provider.usageLimits?.windows ?? []).some( + (entry) => entry.id === "primary" || entry.id === "secondary", + ) + ); + case "opencode": + return !window.id.startsWith("go_") || model.startsWith("opencode-go/"); + default: + return true; + } +} + export function exhaustedUsageWindow( provider: ServerProvider | undefined, now: number, model?: string, ) { - const windows = provider?.usageLimits?.windows ?? []; - const exhausted = windows.filter( + if (!provider) return undefined; + const exhausted = (provider.usageLimits?.windows ?? []).filter( (window) => (window.usedPercent ?? 0) >= 100 && - (model === undefined || window.modelIds === undefined || window.modelIds.includes(model)) && - (model === undefined || - window.providerIds === undefined || - window.providerIds.includes(model.split("/")[0] ?? "")) && + (model === undefined || usageWindowLimitsModel(provider, window, model)) && (!window.resetsAt || !Number.isFinite(Date.parse(window.resetsAt)) || Date.parse(window.resetsAt) > now), ); - if (model === undefined) return exhausted[0]; - switch (provider?.driver) { - case "cursor": { - const api = exhausted.find((window) => window.id === "apiPercentUsed"); - const auto = exhausted.find((window) => window.id === "autoPercentUsed"); - return /^(auto|default|grok|composer)/.test(model) ? auto && api : api; - } - case "antigravity": { - const family = model.match(/^(gemini|claude|gpt)-/)?.[1]; - return exhausted.find((window) => { - const pool = window.id.match(/^(gemini|claude|gpt|3p)-/)?.[1]; - return ( - pool === undefined || - family === undefined || - pool === family || - (pool === "3p" && (family === "claude" || family === "gpt")) - ); - }); - } - case "codex": { - // Seat-based plans spend credits only past their plan windows, so the credit cap blocks only plans without them. - const hasPlanWindows = windows.some( - (window) => window.id === "primary" || window.id === "secondary", - ); - return exhausted.find((window) => window.id !== "individual" || !hasPlanWindows); - } - case "opencode": - return exhausted.find( - (window) => !window.id.startsWith("go_") || model.startsWith("opencode-go/"), - ); - default: - return exhausted[0]; - } + if (model === undefined || provider.driver !== "cursor") return exhausted[0]; + const api = exhausted.find((window) => window.id === "apiPercentUsed"); + const auto = exhausted.find((window) => window.id === "autoPercentUsed"); + return /^(auto|default|grok|composer)/.test(model) ? auto && api : api; } export function resolveNewThreadModelSelection(input: { From 53cecb88d0c4c4078669bb6d875274e463c31b10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 10:14:39 +0100 Subject: [PATCH 092/230] test(web): check the Auto route per level with Auto Low Since #10 and #12 Auto High runs Opus 5.5 instead of Fable 5.2, so this test failed on main: it still expected Auto High to name Fable. Auto High and Auto Medium now both name Opus, so the second level check uses Auto Low (Sonnet 5.5), which still shows a level picking a different model. Origin: the weekly-first Auto routing brief requires the autoRoute tests to pass; this one already failed on fork main 04d5047a05. --- apps/web/src/components/chat/autoRoute.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/apps/web/src/components/chat/autoRoute.test.ts b/apps/web/src/components/chat/autoRoute.test.ts index 85ae44be3be8..d49bf6bf86b3 100644 --- a/apps/web/src/components/chat/autoRoute.test.ts +++ b/apps/web/src/components/chat/autoRoute.test.ts @@ -57,8 +57,8 @@ describe("describeAutoRoute", () => { expect(medium?.driverKind).toBe("claudeAgent"); expect(medium?.label).toMatch(/^.*Opus 5\.5 \(B\)$/); - const high = describeAutoRoute({ entries, options: [{ id: "effort", value: "high" }], now }); - expect(high?.label).toMatch(/Fable 5\.2 \(B\)$/); + const low = describeAutoRoute({ entries, options: [{ id: "effort", value: "low" }], now }); + expect(low?.label).toMatch(/Sonnet 5\.5 \(B\)$/); }); it("names another provider when both Claude accounts are used up", () => { From 1f5b76ceb6d6252777085e514b2cc627f35cb207 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 10:29:09 +0100 Subject: [PATCH 093/230] feat(auto): rank accounts by weekly pace MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auto ranked two accounts with room by their 5-hour windows and used the weekly window only as a tie-break. The weekly quota is the scarce one: what is left at the weekly reset is lost, and an account that runs dry early blocks a whole day. On 2026-11-19 07:15 CET Claude A had 32% left for 52.8 h and Claude B 60% for 149.8 h, and the 5-hour stagger chose. Among accounts with room, Auto now goes first to the higher weekly pace: weekly % left per hour until that window resets (A 0.61%/h, B 0.40%/h, so A). Paces within 15% tie, and then the old order decides: the further along 5-hour window, then the sooner weekly reset. An account without weekly data ranks after one with it. Weekly windows count only for the models they limit, through `usageWindowLimitsModel`. Auto-aware instances first, the 90% guard and the sticky rule are unchanged. Origin: Tomáš, 2026-11-19: "focus mainly on the weekly limit, by how depleted it is, with the rules we agreed" (brief: ~/.agents/prompts/t3-auto-weekly-routing.md). --- docs/progress.md | 8 +++ packages/shared/src/autoModel.test.ts | 79 +++++++++++++++++++++++++-- packages/shared/src/autoModel.ts | 58 +++++++++++++++----- packages/shared/src/usageLimits.ts | 2 +- 4 files changed, 127 insertions(+), 20 deletions(-) diff --git a/docs/progress.md b/docs/progress.md index c3425129e2df..f8e10439d896 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -125,3 +125,11 @@ - Numbers: the new adapter test failed on base (live effort change, no reopen) and passes; ClaudeAdapterV2 + claudeModelOptions 475/475. Real run on the worktree's seeded `.t3`: one Auto Low thread over the CLI (Sonnet 5.5 at low, Auto's first Low candidate) quoted `Auto level: low` from its system prompt. - `~/.agents`: `auto-mode.md` and the `auto` skill read the level from that line and fall back to the model name only without it. - Next: deploy on hub2 and the PC; copy the `~/.agents` change into `radys-s/t3-setup-improvements` for hub. + +## 2026-11-19: Auto ranks accounts by weekly pace + +- What: among accounts with room, Auto now goes first to the one with the higher weekly pace: weekly % left divided by the hours until that weekly window resets, the burn rate that spends the quota exactly at its reset. Paces within 15% of each other tie, and then the old order decides (the further along 5-hour window, so windows still stagger, then the sooner weekly reset). An account without weekly data ranks after accounts that have it. A one-model weekly window counts only for its model: the per-window check moved out of `exhaustedUsageWindow` into `usageWindowLimitsModel`, which Auto's pace reuses and which now reads Claude's `seven_day_` windows the way the server's hub pool check already did, so a spent Fable-only allowance no longer blocks Opus on that account. Unchanged: Auto-aware instances first, the 90% guard, the sticky rule and the return to a better model. +- Why: Tomáš asked Auto to "focus mainly on the weekly limit, by how depleted it is". The weekly quota is the scarce one: what is left at the weekly reset is lost, and an account that runs dry early blocks a whole day. On 2026-11-19 07:15 CET Claude A had 32% left for 52.8 h (0.61%/h) and Claude B 60% for 149.8 h (0.40%/h), and the 5-hour stagger, not the weekly state, chose between them. +- Numbers: autoModel 17/17 (the 2026-11-19 example, the no-weekly-data case and the one-model-window case failed on base), usageLimits 99/99 (the new Claude row failed on base), AutoFailoverService 8/8, handoff 17/17, codexUsageLimits 20/20, autoRoute 2/2 (it already failed on fork main: it still expected Fable for Auto High). `vp run check:changed`: format, lint, knip, typecheck (36 packages) and 120 tests in 4 files pass. Real run on the worktree's seeded `.t3` with the two Auto instances: Usage → Limits showed A at 27% weekly left for 2d 2h (0.54%/h) and B at 60% for 6d 3h (0.41%/h), and the picker named A for every level (Auto High · Opus 5.5 (A)). The old rule also picks A right now (A's 5-hour window 39% used, B's 1%), so this run shows the wiring, and the unit tests cover where the rules differ. +- `~/.agents`: the `auto` skill drops "Never move work between Claude A and Claude B because of limits" and says Auto picks the account by weekly pace. +- Next: backlog 2 (model-aware room) can build `hasRoom` on `usageWindowLimitsModel`; today a one-model window at 90% still marks the whole account as out of room. Deploy on Tomáš's word. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index ff03d6791dc9..453d074b1d53 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -4,6 +4,7 @@ import { type ModelSelection, type ServerProvider, } from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; import { describe, expect, it } from "vite-plus/test"; import { @@ -16,6 +17,7 @@ import { const now = Date.parse("2026-11-12T12:00:00.000Z"); const resetsAt = "2026-11-12T15:00:00.000Z"; +const inHours = (hours: number) => DateTime.formatIso(DateTime.makeUnsafe(now + hours * 3_600_000)); const effortCapabilities = { optionDescriptors: [ @@ -57,13 +59,18 @@ function claude(id: string, usedPercent: number, autoAware = true): ServerProvid } as unknown as ServerProvider; } -function withWeekly(provider: ServerProvider, usedPercent: number, weeklyResetsAt: string) { +function withWeekly( + provider: ServerProvider, + usedPercent: number, + weeklyResetsAt: string, + id = "seven_day", +) { return { ...provider, usageLimits: { windows: [ ...(provider.usageLimits?.windows ?? []), - { id: "seven_day", kind: "weekly", label: "Weekly", usedPercent, resetsAt: weeklyResetsAt }, + { id, kind: "weekly", label: "Weekly", usedPercent, resetsAt: weeklyResetsAt }, ], }, } as unknown as ServerProvider; @@ -75,6 +82,9 @@ const auto = (level?: string): ModelSelection => ({ ...(level ? { options: [{ id: "effort", value: level }] } : {}), }); +const routeTo = (providers: ReadonlyArray) => + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId; + describe("resolveAutoModelSelection", () => { it("maps each level to its orchestrator model and effort, medium by default", () => { const providers = [claude("claudeAuto", 10)]; @@ -128,6 +138,16 @@ describe("resolveAutoModelSelection", () => { expect( resolveAutoModelSelection({ selection: auto(), providers: busy, now, current }), ).toMatchObject({ sticky: false, selection: { instanceId: "claudeAutoB" } }); + + // A higher weekly pace elsewhere does not move a thread whose account still has room. + const onB = { instanceId: ProviderInstanceId.make("claudeAutoB"), model: "claude-opus-5-5" }; + const urgentA = [ + withWeekly(claude("claudeAuto", 10), 68, inHours(52.8)), + withWeekly(claude("claudeAutoB", 45), 40, inHours(149.8)), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers: urgentA, now, current: onB }), + ).toMatchObject({ sticky: true, selection: { instanceId: "claudeAutoB" } }); }); it("steps down to other subscriptions when both Claude accounts are exhausted", () => { @@ -156,6 +176,55 @@ describe("resolveAutoModelSelection", () => { expect( resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, ).toBe("claudeAuto"); + // Weekly paces within 15% count as equal: B's 0.54%/h does not beat A's 0.5%/h. + const closePaces = [ + withWeekly(claude("claudeAutoB", 10), 46, inHours(100)), + withWeekly(claude("claudeAuto", 50), 50, inHours(100)), + ]; + expect(routeTo(closePaces)).toBe("claudeAuto"); + }); + + it("spends first the account whose weekly quota would be lost at its reset", () => { + // 2026-11-19 07:15 CET: A has 32% left for 52.8 h (0.61%/h), B 60% for 149.8 h (0.40%/h). + // B's 5-hour window is further along, but A's quota is gone in two days. + const route = (aWeeklyUsed: number) => + routeTo([ + withWeekly(claude("claudeAutoB", 45), 40, inHours(149.8)), + withWeekly(claude("claudeAuto", 10), aWeeklyUsed, inHours(52.8)), + ]); + expect(route(68)).toBe("claudeAuto"); + // With 15% left (0.28%/h), A has less to lose and waits; at 97% it has no room at all. + expect(route(85)).toBe("claudeAutoB"); + expect(route(97)).toBe("claudeAutoB"); + }); + + it("ranks an account without weekly data after one with it", () => { + // A's 5-hour window is further along, but A's weekly use is unknown, not 0%. + const providers = [ + claude("claudeAuto", 50), + withWeekly(claude("claudeAutoB", 10), 40, inHours(100)), + ]; + expect(routeTo(providers)).toBe("claudeAutoB"); + }); + + it("counts a one-model weekly window only for that model", () => { + // A's nearly spent Opus allowance resets late, so A has little Opus quota to lose. B's nearly + // spent allowance is Fable's, which does not slow B's Opus pace. + const providers = [ + withWeekly( + withWeekly(claude("claudeAuto", 50), 20, inHours(30)), + 85, + inHours(140), + "seven_day_opus", + ), + withWeekly( + withWeekly(claude("claudeAutoB", 10), 50, inHours(100)), + 85, + inHours(140), + "seven_day_fable", + ), + ]; + expect(routeTo(providers)).toBe("claudeAutoB"); }); it("switches to the other account once a 5-hour or weekly window is 90% used", () => { @@ -181,11 +250,11 @@ describe("resolveAutoModelSelection", () => { ).toBe("claudeAuto"); }); - it("with similar 5-hour use, spends the account whose weekly limit resets first", () => { - // B's window is slightly further along, but A's unused weekly quota is gone tomorrow. + it("with similar weekly pace and 5-hour use, spends the account whose weekly limit resets first", () => { + // Both paces are 0.42%/h and B's window is slightly further along, but A resets a day sooner. const providers = [ withWeekly(claude("claudeAutoB", 30), 40, "2026-11-18T12:00:00.000Z"), - withWeekly(claude("claudeAuto", 25), 40, "2026-11-13T12:00:00.000Z"), + withWeekly(claude("claudeAuto", 25), 50, "2026-11-17T12:00:00.000Z"), ]; expect( resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index b88b26456a67..2b82dee5dbe4 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -5,7 +5,7 @@ import { type ServerProvider, } from "@t3tools/contracts"; -import { exhaustedUsageWindow } from "./usageLimits.ts"; +import { exhaustedUsageWindow, usageWindowLimitsModel } from "./usageLimits.ts"; /** * "Auto" is a custom model (slug `auto`) on any provider instance. Picking it never reaches @@ -155,37 +155,67 @@ function autoLevelOf(selection: ModelSelection): AutoLevel { /** Accounts whose 5-hour use differs by less than this many points count as equally far along. */ const SESSION_BAND_PERCENT = 10; +/** Weekly paces within this share of each other count as equal. */ +const PACE_BAND = 0.15; +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; function sessionUsedPercent(provider: ServerProvider): number { const windows = (provider.usageLimits?.windows ?? []).filter((w) => w.kind === "session"); return Math.max(0, ...windows.map((w) => w.usedPercent ?? 0)); } +/** Weekly windows with a known reset that limit `model`; a one-model window counts only for it. */ +function weeklyWindows(provider: ServerProvider, model: string) { + return (provider.usageLimits?.windows ?? []).filter( + (w) => + w.kind === "weekly" && + Number.isFinite(Date.parse(w.resetsAt ?? "")) && + usageWindowLimitsModel(provider, w, model), + ); +} + +/** + * Weekly % left per hour until that window resets: the burn rate that spends the quota exactly + * at its reset, when whatever is left is lost. The tightest window decides; undefined without + * weekly data. + */ +function weeklyPace(provider: ServerProvider, model: string, now: number): number | undefined { + const paces = weeklyWindows(provider, model).map( + (w) => (100 - w.usedPercent) / (Math.max(Date.parse(w.resetsAt!) - now, MINUTE) / HOUR), + ); + return paces.length > 0 ? Math.min(...paces) : undefined; +} + /** When the soonest weekly window resets; unused weekly quota is lost then. */ -function weeklyResetAt(provider: ServerProvider): number { - const resets = (provider.usageLimits?.windows ?? []) - .filter((w) => w.kind === "weekly" && w.resetsAt !== undefined) - .map((w) => Date.parse(w.resetsAt!)) - .filter(Number.isFinite); - return resets.length > 0 ? Math.min(...resets) : Infinity; +function weeklyResetAt(provider: ServerProvider, model: string): number { + return Math.min(...weeklyWindows(provider, model).map((w) => Date.parse(w.resetsAt!))); +} + +/** The higher pace first; paces within 15% tie, and an account without weekly data goes last. */ +function comparePace(a: number | undefined, b: number | undefined): number { + if (a === undefined || b === undefined) return Number(a === undefined) - Number(b === undefined); + return Math.abs(a - b) > PACE_BAND * Math.max(a, b) ? b - a : 0; } /** - * Best instance first: Auto-aware, then accounts under 90% everywhere. Among those, the further - * along 5-hour window, so windows stagger (one refreshes while the other runs); within 10 - * points, the sooner weekly reset. Past 90% everywhere, the most left. + * Best instance for `model` first: Auto-aware, then accounts under 90% everywhere. Among those, + * the higher weekly pace, so the quota a reset would waste is spent first. With similar paces, + * the further along 5-hour window, so windows stagger (one refreshes while the other runs); + * within 10 points, the sooner weekly reset. Past 90% everywhere, the most left. */ -function compareInstances(a: ServerProvider, b: ServerProvider): number { +function compareInstances(a: ServerProvider, b: ServerProvider, model: string, now: number) { const aware = Number(isAutoAware(b)) - Number(isAutoAware(a)); if (aware !== 0) return aware; const room = Number(hasRoom(b)) - Number(hasRoom(a)); if (room !== 0) return room; if (!hasRoom(a)) return peakUsedPercent(a) - peakUsedPercent(b); + const pace = comparePace(weeklyPace(a, model, now), weeklyPace(b, model, now)); + if (pace !== 0) return pace; const session = sessionUsedPercent(b) - sessionUsedPercent(a); if (Math.abs(session) >= SESSION_BAND_PERCENT) return session; - const weekly = weeklyResetAt(a) - weeklyResetAt(b); + const weekly = weeklyResetAt(a, model) - weeklyResetAt(b, model); if (Number.isFinite(weekly) && weekly !== 0) return weekly; - if (weekly === Infinity || weekly === -Infinity) return weekly > 0 ? 1 : -1; return session || peakUsedPercent(a) - peakUsedPercent(b); } @@ -304,7 +334,7 @@ export function resolveAutoModelSelection(input: { open(provider, candidate.model), ) // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. - .sort(compareInstances); + .sort((a, b) => compareInstances(a, b, candidate.model, input.now)); const provider = instances[0]; if (provider) { return { selection: toSelection(provider, candidate, level), level, sticky: false }; diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 2df18df8b4ad..a0375c7c865e 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -24,7 +24,7 @@ import { isLocalLoopbackHost, isWildcardHost } from "./hostClassification.ts"; const MINUTE = 60_000; /** Whether `window` limits `model`; a window for some models or one pool limits only those. */ -function usageWindowLimitsModel( +export function usageWindowLimitsModel( provider: ServerProvider, window: ServerProviderUsageWindow, model: string, From af698c642b9f1043ad7c09b603398e1c272c11b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 10:37:07 +0100 Subject: [PATCH 094/230] fix(auto): a weekly window with no reset counts as a fresh week Claude's get_usage types `resets_at` as nullable, and a window that has not started (an account right after its weekly reset) can report usage without a reset. The weekly pace skipped such a window, so the fresh account ranked as having no weekly data and lost to every account with a reset, even a slower one. Nothing then used it, so its week never started. Such a window now resets a full window length from now (100% left over a week is about 0.6%/h). A window with neither a reset nor a length is still skipped, and an account without any weekly window still ranks after those with one. Origin: read-only review of the weekly-pace routing (finding S1). --- docs/progress.md | 4 ++-- packages/shared/src/autoModel.test.ts | 20 +++++++++++++++++ packages/shared/src/autoModel.ts | 31 ++++++++++++++++----------- 3 files changed, 40 insertions(+), 15 deletions(-) diff --git a/docs/progress.md b/docs/progress.md index f8e10439d896..f25a8eeaa73e 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -128,8 +128,8 @@ ## 2026-11-19: Auto ranks accounts by weekly pace -- What: among accounts with room, Auto now goes first to the one with the higher weekly pace: weekly % left divided by the hours until that weekly window resets, the burn rate that spends the quota exactly at its reset. Paces within 15% of each other tie, and then the old order decides (the further along 5-hour window, so windows still stagger, then the sooner weekly reset). An account without weekly data ranks after accounts that have it. A one-model weekly window counts only for its model: the per-window check moved out of `exhaustedUsageWindow` into `usageWindowLimitsModel`, which Auto's pace reuses and which now reads Claude's `seven_day_` windows the way the server's hub pool check already did, so a spent Fable-only allowance no longer blocks Opus on that account. Unchanged: Auto-aware instances first, the 90% guard, the sticky rule and the return to a better model. +- What: among accounts with room, Auto now goes first to the one with the higher weekly pace: weekly % left divided by the hours until that weekly window resets, the burn rate that spends the quota exactly at its reset. Paces within 15% of each other tie, and then the old order decides (the further along 5-hour window, so windows still stagger, then the sooner weekly reset). An account without weekly data ranks after accounts that have it; a weekly window that reports no reset has not started, so it counts as a full window from now (a fresh week, about 0.6%/h). A one-model weekly window counts only for its model: the per-window check moved out of `exhaustedUsageWindow` into `usageWindowLimitsModel`, which Auto's pace reuses and which now reads Claude's `seven_day_` windows the way the server's hub pool check already did, so a spent Fable-only allowance no longer blocks Opus on that account. Unchanged: Auto-aware instances first, the 90% guard, the sticky rule and the return to a better model. - Why: Tomáš asked Auto to "focus mainly on the weekly limit, by how depleted it is". The weekly quota is the scarce one: what is left at the weekly reset is lost, and an account that runs dry early blocks a whole day. On 2026-11-19 07:15 CET Claude A had 32% left for 52.8 h (0.61%/h) and Claude B 60% for 149.8 h (0.40%/h), and the 5-hour stagger, not the weekly state, chose between them. -- Numbers: autoModel 17/17 (the 2026-11-19 example, the no-weekly-data case and the one-model-window case failed on base), usageLimits 99/99 (the new Claude row failed on base), AutoFailoverService 8/8, handoff 17/17, codexUsageLimits 20/20, autoRoute 2/2 (it already failed on fork main: it still expected Fable for Auto High). `vp run check:changed`: format, lint, knip, typecheck (36 packages) and 120 tests in 4 files pass. Real run on the worktree's seeded `.t3` with the two Auto instances: Usage → Limits showed A at 27% weekly left for 2d 2h (0.54%/h) and B at 60% for 6d 3h (0.41%/h), and the picker named A for every level (Auto High · Opus 5.5 (A)). The old rule also picks A right now (A's 5-hour window 39% used, B's 1%), so this run shows the wiring, and the unit tests cover where the rules differ. +- Numbers: autoModel 17/17 (the 2026-11-19 example, the no-weekly-data case, the unstarted-window case and the one-model-window case failed on base), usageLimits 99/99 (the new Claude row failed on base), AutoFailoverService 8/8, handoff 17/17, codexUsageLimits 20/20, autoRoute 2/2 (it already failed on fork main: it still expected Fable for Auto High). `vp run check:changed`: format, lint, knip, typecheck (36 packages) and 120 tests in 4 files pass. Real run on the worktree's seeded `.t3` with the two Auto instances: Usage → Limits showed A at 27% weekly left for 2d 2h (0.54%/h) and B at 60% for 6d 3h (0.41%/h), and the picker named A for every level (Auto High · Opus 5.5 (A)). The old rule also picks A right now (A's 5-hour window 39% used, B's 1%), so this run shows the wiring, and the unit tests cover where the rules differ. - `~/.agents`: the `auto` skill drops "Never move work between Claude A and Claude B because of limits" and says Auto picks the account by weekly pace. - Next: backlog 2 (model-aware room) can build `hasRoom` on `usageWindowLimitsModel`; today a one-model window at 90% still marks the whole account as out of room. Deploy on Tomáš's word. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index 453d074b1d53..a543672bbcee 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -205,6 +205,26 @@ describe("resolveAutoModelSelection", () => { withWeekly(claude("claudeAutoB", 10), 40, inHours(100)), ]; expect(routeTo(providers)).toBe("claudeAutoB"); + + // A weekly window that has not started reports no reset; it runs a full week from now + // (0.6%/h), so the fresh account beats A's 0.47%/h. + const unstarted = { + ...claude("claudeAutoB", 0), + usageLimits: { + windows: [ + { + id: "seven_day", + kind: "weekly", + label: "Weekly", + usedPercent: 0, + windowDurationMins: 10_080, + }, + ], + }, + } as unknown as ServerProvider; + expect(routeTo([withWeekly(claude("claudeAuto", 50), 30, inHours(150)), unstarted])).toBe( + "claudeAutoB", + ); }); it("counts a one-model weekly window only for that model", () => { diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 2b82dee5dbe4..64d8d766ad29 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -165,14 +165,19 @@ function sessionUsedPercent(provider: ServerProvider): number { return Math.max(0, ...windows.map((w) => w.usedPercent ?? 0)); } -/** Weekly windows with a known reset that limit `model`; a one-model window counts only for it. */ -function weeklyWindows(provider: ServerProvider, model: string) { - return (provider.usageLimits?.windows ?? []).filter( - (w) => - w.kind === "weekly" && - Number.isFinite(Date.parse(w.resetsAt ?? "")) && - usageWindowLimitsModel(provider, w, model), - ); +/** + * Weekly windows that limit `model` (a one-model window counts only for it) and when each + * resets. A window that has not started reports no reset; it would run its full length from now. + */ +function weeklyWindows(provider: ServerProvider, model: string, now: number) { + return (provider.usageLimits?.windows ?? []).flatMap((w) => { + if (w.kind !== "weekly" || !usageWindowLimitsModel(provider, w, model)) return []; + const resetsAt = + w.resetsAt === undefined + ? now + (w.windowDurationMins ?? Number.NaN) * MINUTE + : Date.parse(w.resetsAt); + return Number.isFinite(resetsAt) ? [{ usedPercent: w.usedPercent, resetsAt }] : []; + }); } /** @@ -181,15 +186,15 @@ function weeklyWindows(provider: ServerProvider, model: string) { * weekly data. */ function weeklyPace(provider: ServerProvider, model: string, now: number): number | undefined { - const paces = weeklyWindows(provider, model).map( - (w) => (100 - w.usedPercent) / (Math.max(Date.parse(w.resetsAt!) - now, MINUTE) / HOUR), + const paces = weeklyWindows(provider, model, now).map( + (w) => (100 - w.usedPercent) / (Math.max(w.resetsAt - now, MINUTE) / HOUR), ); return paces.length > 0 ? Math.min(...paces) : undefined; } /** When the soonest weekly window resets; unused weekly quota is lost then. */ -function weeklyResetAt(provider: ServerProvider, model: string): number { - return Math.min(...weeklyWindows(provider, model).map((w) => Date.parse(w.resetsAt!))); +function weeklyResetAt(provider: ServerProvider, model: string, now: number): number { + return Math.min(...weeklyWindows(provider, model, now).map((w) => w.resetsAt)); } /** The higher pace first; paces within 15% tie, and an account without weekly data goes last. */ @@ -214,7 +219,7 @@ function compareInstances(a: ServerProvider, b: ServerProvider, model: string, n if (pace !== 0) return pace; const session = sessionUsedPercent(b) - sessionUsedPercent(a); if (Math.abs(session) >= SESSION_BAND_PERCENT) return session; - const weekly = weeklyResetAt(a, model) - weeklyResetAt(b, model); + const weekly = weeklyResetAt(a, model, now) - weeklyResetAt(b, model, now); if (Number.isFinite(weekly) && weekly !== 0) return weekly; return session || peakUsedPercent(a) - peakUsedPercent(b); } From 442e543c87b10b877c2de2245ace2c6e21ddb1a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 10:39:22 +0100 Subject: [PATCH 095/230] docs(auto): say when a weekly window has no reset A weekly window can lack a reset because it has not started yet, but also when a stream update reached the server before any usage probe. The comment named only the first case. Origin: read-only review of the weekly-pace routing, round 2 (nit S4). --- packages/shared/src/autoModel.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 64d8d766ad29..bdf7948a4a79 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -167,7 +167,8 @@ function sessionUsedPercent(provider: ServerProvider): number { /** * Weekly windows that limit `model` (a one-model window counts only for it) and when each - * resets. A window that has not started reports no reset; it would run its full length from now. + * resets. A window with no reported reset, such as one that has not started, counts as a full + * window from now. */ function weeklyWindows(provider: ServerProvider, model: string, now: number) { return (provider.usageLimits?.windows ?? []).flatMap((w) => { From b100088af3e41aa830f2cb2177a735061175a8a4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 12:20:17 +0100 Subject: [PATCH 096/230] refactor(server): reuse upstream's RESUME_PROMPT for the Resume fallback Upstream 245c579807 (#38847) added RESUME_PROMPT, "Continue where you left off.", to the module that already held the fork's MANUAL_RESUME_CONTINUE_TEXT with the same text. Resume on a provider without native resume now sends upstream's constant, so the two cannot drift and the fork carries a smaller diff against upstream. Origin: review finding on the sync onto upstream aced664ed9. --- apps/server/src/orchestration-v2/ProviderTurnStartService.ts | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index d36d53f3e072..557335053eea 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -133,9 +133,6 @@ const isProviderAdapterOpenSessionError = Schema.is( ProviderAdapter.ProviderAdapterOpenSessionError, ); -/** Sent in place of a native resume the provider does not support. */ -const MANUAL_RESUME_CONTINUE_TEXT = "Continue where you left off."; - /** * Claude refuses these before it reads the prompt: replacing a process running background work, * launch arguments whose appended system prompt or settings cannot be read, or MCP registration @@ -951,7 +948,7 @@ export const layer: Layer.Layer< const continueInstead = manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined; const userText = continueInstead - ? MANUAL_RESUME_CONTINUE_TEXT + ? RESUME_PROMPT : projectComposerContextForProvider({ text: providerMessage.text, records: providerMessage.context?.records ?? [], From a5ae311f8f25f5f1d994437506565dcdcb71be85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 12:29:45 +0100 Subject: [PATCH 097/230] docs: log the sync onto upstream aced664ed9 in progress.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Records how the fork was replayed onto upstream main, which conflicts came up and how they were resolved, what was adapted, what the review found, and how it was verified. Origin: Tomáš's request to bring the fork up to current upstream. --- docs/progress.md | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/docs/progress.md b/docs/progress.md index f25a8eeaa73e..849ac36e0b6a 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -133,3 +133,15 @@ - Numbers: autoModel 17/17 (the 2026-11-19 example, the no-weekly-data case, the unstarted-window case and the one-model-window case failed on base), usageLimits 99/99 (the new Claude row failed on base), AutoFailoverService 8/8, handoff 17/17, codexUsageLimits 20/20, autoRoute 2/2 (it already failed on fork main: it still expected Fable for Auto High). `vp run check:changed`: format, lint, knip, typecheck (36 packages) and 120 tests in 4 files pass. Real run on the worktree's seeded `.t3` with the two Auto instances: Usage → Limits showed A at 27% weekly left for 2d 2h (0.54%/h) and B at 60% for 6d 3h (0.41%/h), and the picker named A for every level (Auto High · Opus 5.5 (A)). The old rule also picks A right now (A's 5-hour window 39% used, B's 1%), so this run shows the wiring, and the unit tests cover where the rules differ. - `~/.agents`: the `auto` skill drops "Never move work between Claude A and Claude B because of limits" and says Auto picks the account by weekly pace. - Next: backlog 2 (model-aware room) can build `hasRoom` on `usageWindowLimitsModel`; today a one-model window at 90% still marks the whole account as out of room. Deploy on Tomáš's word. + +## 2026-11-19: Fork synced onto upstream `aced664ed9` + +- What: the 28 fork commits since the last sync were cherry-picked onto upstream main `aced664ed9` (175 upstream commits newer, 699 files changed): the 20 commits of the 2026-11-18 sync (its 18 replayed fork commits, its i18n catalog commit and its progress entry; first parent of `373ec12be6..1eafff1cc9^2`), then #10, #12, #13 and #15. Fork main also holds the pre-sync originals of older fork commits (they come in through the second parents of #9 and #11); those were left out, so nothing is applied twice. The fork main that was replayed (`1a2d9afd88`) is recorded as an ancestor with an `-s ours` merge, as in the last two syncs, so the PR merges without a force-push. #14 (fork CI on GitHub-hosted runners), merged to fork main during the sync, comes in through a normal merge: it only changes `ci.yml` and `mobile-fingerprint-check.yml`, which upstream did not touch. +- Why: the fork was 175 commits behind upstream a day after the last sync. +- Conflicts: 2. `Orchestrator.ts` imports: upstream's `assistantCitations` import next to the fork's `autoModel` and `ProviderRegistry` imports; kept both. `docs/progress.md` on #10: took fork main's text as of #11, which had resolved the same conflict. The other 22 files both sides changed merged cleanly. +- Adapted to upstream: upstream's Resume fix (#38847) added `RESUME_PROMPT` to `ProviderTurnStartService.ts` with the same text as the fork's `MANUAL_RESUME_CONTINUE_TEXT`; the fork's Resume on providers without native resume now sends upstream's constant. The two paths never meet: the fork's forces `resume: false`. Nothing else needed changes: for each file, the lines the fork adds and removes are the same on the new base as on the old one, and apart from that swap `git diff origin/main HEAD` holds exactly upstream's changes. `OrchestratorV2Shape` did not change upstream, so Auto routing still wraps every command. +- Upstream change that touches Auto: a steer the agent never read is now sent again once its run ends (`requeueUnreadSteers`), on that run's model and without Auto routing. If the run failed on a usage limit, the steer waits for that account like any message queued before the failure, and failover still moves the thread: the queue holds runs for a limited instance, and the thread keeps the failed run as its latest. Before the sync such a steer was never sent. +- Numbers: `vp run check:changed` (56 files since upstream/main, #14 included) all pass: typecheck 42 packages, 986 tests in 27 files, lint, knip, format, react compiler. `vp run i18n:check` pass. Focused: autoModel 17/17, usageLimits 99/99, AutoFailoverService 8/8, ProviderTurnStartService 88/88; with the 3 Orchestrator test files, ClaudeAdapterV2 and ProviderRegistry, 809/809 in 9 files. +- Real run (worktree `.t3`, seeded from a read-only copy of the live database, settings with only the two Auto instances): Auto High · Opus 5.5 (B), Auto Medium · Opus 5.5 (B) and Auto Low · Sonnet 5.5 (B) pinned at the top of Favorites. Usage → Limits showed the Subscriptions table (A: 9% of the 5-hour window left, 21% weekly; B: 81% and 57%) and the pooled Claude view with its reset advice. B is the route because A's 5-hour window is past the 90% guard. One Claude Haiku 5.5 turn answered "OK". +- Review: one read-only review of the resolutions found no bugs. Taken: the `RESUME_PROMPT` swap. Checked and set aside: the claim that a re-sent steer starts on the limited account and stops failover (`usageLimitHoldsQueue` keeps it queued; upstream's "keeps queued user selections and pauses only the limited provider" test pins that). +- Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Open, not part of the sync: queued messages and re-sent steers stay on the account that failed instead of following an Auto failover, and the fork's 17 Usage keys are still English in the 9 non-English web catalogs (since the 2026-11-18 sync). From 3a1389afe87980a58fc49bbde8a619c811c1aa75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 14:02:14 +0100 Subject: [PATCH 098/230] fix(shared): Auto room check counts only the windows that limit the model MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Auto room checking (hasRoom, peakUsedPercent) previously checked all windows on an instance regardless of model, so a one-model window (such as seven_day_ for Fable) or an extra-usage spend window at 90% marked the whole account full for all models. Missing usage data also read as 0% empty, pulling sticky threads away and winning tie-breaks. Only active windows limiting the candidate model (via usageWindowLimitsModel) now count for room and session usage, ignoring expired windows. Claude's monthly spend is excluded while plan windows have room. Unknown usage ranks after known accounts with room, cannot steal sticky threads, and an account without a session window ranks after one with a known session. autoModel tests: 24/24. check:changed: clean. Origin: Tomáš, Auto room check problem brief. --- docs/progress.md | 8 + packages/shared/src/autoModel.test.ts | 229 ++++++++++++++++++++++++++ packages/shared/src/autoModel.ts | 101 +++++++++--- 3 files changed, 318 insertions(+), 20 deletions(-) diff --git a/docs/progress.md b/docs/progress.md index 849ac36e0b6a..9023870e6ba8 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -145,3 +145,11 @@ - Real run (worktree `.t3`, seeded from a read-only copy of the live database, settings with only the two Auto instances): Auto High · Opus 5.5 (B), Auto Medium · Opus 5.5 (B) and Auto Low · Sonnet 5.5 (B) pinned at the top of Favorites. Usage → Limits showed the Subscriptions table (A: 9% of the 5-hour window left, 21% weekly; B: 81% and 57%) and the pooled Claude view with its reset advice. B is the route because A's 5-hour window is past the 90% guard. One Claude Haiku 5.5 turn answered "OK". - Review: one read-only review of the resolutions found no bugs. Taken: the `RESUME_PROMPT` swap. Checked and set aside: the claim that a re-sent steer starts on the limited account and stops failover (`usageLimitHoldsQueue` keeps it queued; upstream's "keeps queued user selections and pauses only the limited provider" test pins that). - Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Open, not part of the sync: queued messages and re-sent steers stay on the account that failed instead of following an Auto failover, and the fork's 17 Usage keys are still English in the 9 non-English web catalogs (since the 2026-11-18 sync). + +## 2026-11-19: Auto room check counts only windows that limit the model + +- What: `hasRoom` and `peakUsedPercent` in Auto routing (`autoModel.ts`) are now model-aware: they only consider active windows that limit the candidate model, determined via `usageWindowLimitsModel`, and ignore expired windows whose reset time has passed. Claude's extra-usage spend window (`monthly_spend`) does not count for room while plan windows have room. Unknown usage (missing report, window without `usedPercent`, or missing session window) no longer masquerades as 0% used: accounts with unknown usage rank after accounts with known room and before accounts past 90%, do not pull sticky threads back via `betterHasRoom`, and an account without a session window ranks after one with a known session. +- Why: Auto previously computed `peakUsedPercent` across all windows of an instance regardless of model, so a model-specific window (e.g. Claude's `seven_day_` for Fable at 90%, or Antigravity's Gemini session pool at 90%, or Claude's extra-usage spend at 90%) marked the entire account full for all models including Opus. Furthermore, missing usage data read as 0% empty, making unprobed instances look fresh, win "most left" tie-breaks, and incorrectly steal sticky threads through `betterHasRoom`. +- Numbers: autoModel 24/24 tests pass (8 new tests failed on base covering model-specific windows, Antigravity pools, monthly spend, expired windows, unknown usage ranking, missing session window, sticky retention, and past-90% ordering). `vp run check:changed` passes clean: format, lint, knip 1/2 and 2/2, typecheck (36 packages), 26 tests in 2 files. +- What worked: real run on dev server seeded from read-only live data (`.t3/userdata`), where Auto Low cleanly dispatched and answered "Auto (low)\n\nOK" on Claude Sonnet 5.5. +- Next: read-only review with Claude B, then PR to radys-s/t3code main. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index a543672bbcee..0f82efe06892 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -76,6 +76,57 @@ function withWeekly( } as unknown as ServerProvider; } +function withWindow(provider: ServerProvider, window: Record) { + return { + ...provider, + usageLimits: { + windows: [...(provider.usageLimits?.windows ?? []), window], + }, + } as unknown as ServerProvider; +} + +const antigravityProvider = (id: string, geminiSession: number, claudeSession: number) => + ({ + ...claude(id, 0, false), + displayName: "Auto", + driver: ProviderDriverKind.make("antigravity"), + models: [ + { + slug: "claude-opus-4-6-thinking", + name: "Claude Opus 4.6", + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "thinking_level", + label: "Thinking", + type: "select" as const, + options: [{ id: "medium", label: "medium" }], + }, + ], + }, + }, + ], + usageLimits: { + windows: [ + { + id: "gemini-5h", + kind: "session", + label: "Gemini session", + usedPercent: geminiSession, + resetsAt, + }, + { + id: "claude-5h", + kind: "session", + label: "Claude session", + usedPercent: claudeSession, + resetsAt, + }, + ], + }, + }) as unknown as ServerProvider; + const auto = (level?: string): ModelSelection => ({ instanceId: ProviderInstanceId.make("claudeAuto"), model: "auto", @@ -247,6 +298,175 @@ describe("resolveAutoModelSelection", () => { expect(routeTo(providers)).toBe("claudeAutoB"); }); + it("checks room only against windows that limit the candidate model", () => { + const weeklyReset = inHours(48); + const a = withWindow(withWeekly(claude("claudeAuto", 50), 20, weeklyReset), { + id: "seven_day_fable", + kind: "weekly", + label: "Weekly · Fable", + usedPercent: 95, + resetsAt: weeklyReset, + }); + const b = withWeekly(claude("claudeAutoB", 10), 20, weeklyReset); + expect(routeTo([a, b])).toBe("claudeAuto"); + + const grok = { + ...claude("grok", 10, false), + driver: ProviderDriverKind.make("grok"), + models: [{ slug: "grok-4.7", name: "Grok 4.7", isCustom: false, capabilities: null }], + } as unknown as ServerProvider; + const current = { instanceId: ProviderInstanceId.make("grok"), model: "grok-4.7" }; + expect( + resolveAutoModelSelection({ selection: auto(), providers: [grok, a], now, current }), + ).toMatchObject({ sticky: false, selection: { instanceId: "claudeAuto" } }); + }); + + it("checks room only against the Antigravity pool that limits the model", () => { + const out = [claude("claudeAuto", 100), claude("claudeAutoB", 100)]; + expect( + routeTo([ + ...out, + antigravityProvider("antigravityA", 92, 50), + antigravityProvider("antigravityB", 10, 10), + ]), + ).toBe("antigravityA"); + }); + + it("does not count Claude's extra-usage spend window for room", () => { + const a = withWindow(withWeekly(claude("claudeAuto", 50), 20, inHours(48)), { + id: "monthly_spend", + kind: "monthly", + label: "Monthly spend", + usedPercent: 95, + }); + const b = withWeekly(claude("claudeAutoB", 10), 20, inHours(48)); + expect(routeTo([a, b])).toBe("claudeAuto"); + }); + + it("ignores a window whose reset has already passed when checking room", () => { + const a = { + ...claude("claudeAuto", 0), + usageLimits: { + windows: [ + { + id: "five_hour", + kind: "session", + label: "Session", + usedPercent: 95, + resetsAt: inHours(-1), + }, + { + id: "seven_day", + kind: "weekly", + label: "Weekly", + usedPercent: 0, + resetsAt: inHours(168), + }, + ], + }, + } as unknown as ServerProvider; + const b = withWeekly(claude("claudeAutoB", 10), 40, inHours(168)); + expect(routeTo([a, b])).toBe("claudeAuto"); + }); + + it("ranks unknown usage after an account with known room", () => { + const known = withWeekly(claude("claudeAuto", 0), 30, inHours(100)); + // Grok's credits response omits creditUsagePercent on a unified-billing subscription; its + // reader currently turns that into a fabricated 0%. Without a reading it is unknown, not empty. + const unknown = { + ...claude("claudeAutoB", 0), + usageLimits: { + windows: [ + { + id: "subscription", + kind: "weekly", + label: "Weekly", + resetsAt: inHours(100), + windowDurationMins: 10_080, + }, + ], + }, + } as unknown as ServerProvider; + expect(routeTo([known, unknown])).toBe("claudeAuto"); + expect(routeTo([unknown, known])).toBe("claudeAuto"); + + const noReport = { + ...claude("claudeAutoB", 0), + usageLimits: undefined, + } as unknown as ServerProvider; + expect(routeTo([known, noReport])).toBe("claudeAuto"); + expect(routeTo([noReport, known])).toBe("claudeAuto"); + expect(routeTo([noReport, claude("claudeAuto", 95)])).toBe("claudeAutoB"); + expect(routeTo([unknown, claude("claudeAuto", 95)])).toBe("claudeAutoB"); + expect(routeTo([noReport])).toBe("claudeAutoB"); + }); + + it("ranks an account with no session window after one with a known session", () => { + const noSession = { + ...claude("claudeAutoB", 0), + usageLimits: { + windows: [ + { + id: "seven_day", + kind: "weekly", + label: "Weekly", + usedPercent: 30, + resetsAt: inHours(100), + }, + ], + }, + } as unknown as ServerProvider; + const known = withWeekly(claude("claudeAuto", 0), 30, inHours(100)); + expect(routeTo([noSession, known])).toBe("claudeAuto"); + }); + + it("does not let unknown usage pull a sticky thread off a known account", () => { + const openCode = { + ...claude("openCode", 10, false), + driver: ProviderDriverKind.make("opencode"), + models: [ + { + slug: "opencode/big-pickle", + name: "Big Pickle", + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "variant", + label: "Variant", + type: "select" as const, + options: [{ id: "medium", label: "medium" }], + }, + ], + }, + }, + ], + } as unknown as ServerProvider; + const grok = { + ...claude("grok", 0, false), + driver: ProviderDriverKind.make("grok"), + models: [{ slug: "grok-4.7", name: "Grok 4.7", isCustom: false, capabilities: null }], + usageLimits: { + windows: [ + { + id: "subscription", + kind: "weekly", + label: "Weekly", + resetsAt: inHours(100), + windowDurationMins: 10_080, + }, + ], + }, + } as unknown as ServerProvider; + const current = { + instanceId: ProviderInstanceId.make("openCode"), + model: "opencode/big-pickle", + }; + expect( + resolveAutoModelSelection({ selection: auto(), providers: [grok, openCode], now, current }), + ).toMatchObject({ sticky: true, selection: { instanceId: "openCode" } }); + }); + it("switches to the other account once a 5-hour or weekly window is 90% used", () => { const sessionFull = [claude("claudeAuto", 92), claude("claudeAutoB", 0)]; expect( @@ -268,6 +488,15 @@ describe("resolveAutoModelSelection", () => { expect( resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, ).toBe("claudeAuto"); + // Fable's allowance does not limit Opus, so A's highest relevant window is its 92% session. + const fableFull = withWindow(claude("claudeAuto", 92), { + id: "seven_day_fable", + kind: "weekly", + label: "Weekly · Fable", + usedPercent: 98, + resetsAt: inHours(48), + }); + expect(routeTo([fableFull, claude("claudeAutoB", 97)])).toBe("claudeAuto"); }); it("with similar weekly pace and 5-hour use, spends the account whose weekly limit resets first", () => { diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index bdf7948a4a79..cf778b1eedaa 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -160,9 +160,34 @@ const PACE_BAND = 0.15; const MINUTE = 60_000; const HOUR = 60 * MINUTE; -function sessionUsedPercent(provider: ServerProvider): number { - const windows = (provider.usageLimits?.windows ?? []).filter((w) => w.kind === "session"); - return Math.max(0, ...windows.map((w) => w.usedPercent ?? 0)); +function roomWindows(provider: ServerProvider, model: string, now: number) { + const windows = (provider.usageLimits?.windows ?? []).filter((w) => { + if (!usageWindowLimitsModel(provider, w, model)) return false; + if (w.resetsAt && Number.isFinite(Date.parse(w.resetsAt)) && Date.parse(w.resetsAt) <= now) { + return false; + } + return true; + }); + // Claude's monthly spend caps only extra usage past the plan windows, so it does not count while those windows have room. + const planWindows = windows.filter((w) => w.id !== "monthly_spend"); + const planHasRoom = + planWindows.length > 0 && + planWindows.every( + (w) => typeof w.usedPercent === "number" && w.usedPercent < STICKY_MAX_USED_PERCENT, + ); + return planHasRoom ? planWindows : windows; +} + +function sessionUsedPercent( + provider: ServerProvider, + model: string, + now: number, +): number | undefined { + const windows = roomWindows(provider, model, now).filter( + (w) => + w.kind === "session" && typeof w.usedPercent === "number" && Number.isFinite(w.usedPercent), + ); + return windows.length > 0 ? Math.max(...windows.map((w) => w.usedPercent!)) : undefined; } /** @@ -172,12 +197,21 @@ function sessionUsedPercent(provider: ServerProvider): number { */ function weeklyWindows(provider: ServerProvider, model: string, now: number) { return (provider.usageLimits?.windows ?? []).flatMap((w) => { - if (w.kind !== "weekly" || !usageWindowLimitsModel(provider, w, model)) return []; + if ( + w.kind !== "weekly" || + !usageWindowLimitsModel(provider, w, model) || + typeof w.usedPercent !== "number" || + !Number.isFinite(w.usedPercent) + ) { + return []; + } const resetsAt = w.resetsAt === undefined ? now + (w.windowDurationMins ?? Number.NaN) * MINUTE : Date.parse(w.resetsAt); - return Number.isFinite(resetsAt) ? [{ usedPercent: w.usedPercent, resetsAt }] : []; + return Number.isFinite(resetsAt) && resetsAt > now + ? [{ usedPercent: w.usedPercent, resetsAt }] + : []; }); } @@ -204,33 +238,59 @@ function comparePace(a: number | undefined, b: number | undefined): number { return Math.abs(a - b) > PACE_BAND * Math.max(a, b) ? b - a : 0; } +/** The further along session first; sessions within 10 points tie, and an account without a session window goes last. */ +function compareSession(a: number | undefined, b: number | undefined): number { + if (a === undefined || b === undefined) return Number(a === undefined) - Number(b === undefined); + return Math.abs(b - a) >= SESSION_BAND_PERCENT ? b - a : 0; +} + +function roomRank(provider: ServerProvider, model: string, now: number): number { + const peak = peakUsedPercent(provider, model, now); + if (peak === undefined) return 1; + return peak < STICKY_MAX_USED_PERCENT ? 0 : 2; +} + /** - * Best instance for `model` first: Auto-aware, then accounts under 90% everywhere. Among those, - * the higher weekly pace, so the quota a reset would waste is spent first. With similar paces, - * the further along 5-hour window, so windows stagger (one refreshes while the other runs); - * within 10 points, the sooner weekly reset. Past 90% everywhere, the most left. + * Auto-aware first, then room under 90% everywhere; unknown usage ranks after known accounts with room. + * Higher weekly pace first, then further-along session (no session window goes last), then sooner weekly reset. + * Past 90% everywhere, the most left. */ function compareInstances(a: ServerProvider, b: ServerProvider, model: string, now: number) { const aware = Number(isAutoAware(b)) - Number(isAutoAware(a)); if (aware !== 0) return aware; - const room = Number(hasRoom(b)) - Number(hasRoom(a)); + const room = roomRank(a, model, now) - roomRank(b, model, now); if (room !== 0) return room; - if (!hasRoom(a)) return peakUsedPercent(a) - peakUsedPercent(b); + if (roomRank(a, model, now) === 2) { + return (peakUsedPercent(a, model, now) ?? 0) - (peakUsedPercent(b, model, now) ?? 0); + } const pace = comparePace(weeklyPace(a, model, now), weeklyPace(b, model, now)); if (pace !== 0) return pace; - const session = sessionUsedPercent(b) - sessionUsedPercent(a); - if (Math.abs(session) >= SESSION_BAND_PERCENT) return session; + const sessionA = sessionUsedPercent(a, model, now); + const sessionB = sessionUsedPercent(b, model, now); + const session = compareSession(sessionA, sessionB); + if (session !== 0) return session; const weekly = weeklyResetAt(a, model, now) - weeklyResetAt(b, model, now); if (Number.isFinite(weekly) && weekly !== 0) return weekly; - return session || peakUsedPercent(a) - peakUsedPercent(b); + const rawSession = sessionA !== undefined && sessionB !== undefined ? sessionB - sessionA : 0; + return ( + rawSession || (peakUsedPercent(a, model, now) ?? 0) - (peakUsedPercent(b, model, now) ?? 0) + ); } -function hasRoom(provider: ServerProvider): boolean { - return peakUsedPercent(provider) < STICKY_MAX_USED_PERCENT; +function hasRoom(provider: ServerProvider, model: string, now: number): boolean { + const peak = peakUsedPercent(provider, model, now); + return peak !== undefined && peak < STICKY_MAX_USED_PERCENT; } -function peakUsedPercent(provider: ServerProvider): number { - return Math.max(0, ...(provider.usageLimits?.windows ?? []).map((w) => w.usedPercent ?? 0)); +function peakUsedPercent(provider: ServerProvider, model: string, now: number): number | undefined { + const windows = roomWindows(provider, model, now); + if ( + windows.length === 0 || + windows.some((w) => typeof w.usedPercent !== "number" || !Number.isFinite(w.usedPercent)) + ) { + return undefined; + } + return Math.max(...windows.map((w) => w.usedPercent!)); } /** @@ -318,14 +378,15 @@ export function resolveAutoModelSelection(input: { (entry) => entry.driver === (better.driver as ProviderDriverKind) && open(entry, better.model) && - hasRoom(entry), + hasRoom(entry, better.model, input.now), ), ); if ( provider && candidate && open(provider, candidate.model) && - hasRoom(provider) && + (hasRoom(provider, candidate.model, input.now) || + peakUsedPercent(provider, candidate.model, input.now) === undefined) && !betterHasRoom ) { return { selection: toSelection(provider, candidate, level), level, sticky: true }; From 7e0ac55b520412062bf228bcf3839cf4ef660f20 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 15:57:58 +0100 Subject: [PATCH 099/230] fix(shared): a known window past 90% outranks unknown usage in Auto room Review of the room check found two cases where it still misroutes. An account with one window missing usedPercent and another known at 95% ranked as unknown, ahead of known past-90 accounts, and kept its sticky threads. Claude's monthly_spend window counted again once the plan windows passed 90%, so a 99% spend cap broke the "most left" order. peakUsedPercent now returns the known peak when it is past 90% even if other windows are unknown, and monthly_spend is dropped whenever the account has plan windows. Also reverts an unrequested change that dropped expired weekly windows from the pace. Origin: own review of 3a1389afe8 for the Auto room check brief. --- docs/progress.md | 5 +++-- packages/shared/src/autoModel.test.ts | 15 +++++++++++++++ packages/shared/src/autoModel.ts | 27 ++++++++++----------------- 3 files changed, 28 insertions(+), 19 deletions(-) diff --git a/docs/progress.md b/docs/progress.md index 9023870e6ba8..56c0c93229f0 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -148,8 +148,9 @@ ## 2026-11-19: Auto room check counts only windows that limit the model -- What: `hasRoom` and `peakUsedPercent` in Auto routing (`autoModel.ts`) are now model-aware: they only consider active windows that limit the candidate model, determined via `usageWindowLimitsModel`, and ignore expired windows whose reset time has passed. Claude's extra-usage spend window (`monthly_spend`) does not count for room while plan windows have room. Unknown usage (missing report, window without `usedPercent`, or missing session window) no longer masquerades as 0% used: accounts with unknown usage rank after accounts with known room and before accounts past 90%, do not pull sticky threads back via `betterHasRoom`, and an account without a session window ranks after one with a known session. +- What: `hasRoom` and `peakUsedPercent` in Auto routing (`autoModel.ts`) are now model-aware: they only consider active windows that limit the candidate model, determined via `usageWindowLimitsModel`, and ignore expired windows whose reset time has passed. Claude's extra-usage spend window (`monthly_spend`) does not count for room when the account has plan windows; the plan windows decide. Unknown usage (missing report, window without `usedPercent`, or missing session window) no longer masquerades as 0% used: accounts with unknown usage rank after accounts with known room and before accounts past 90%, do not pull sticky threads back via `betterHasRoom`, and an account without a session window ranks after one with a known session. - Why: Auto previously computed `peakUsedPercent` across all windows of an instance regardless of model, so a model-specific window (e.g. Claude's `seven_day_` for Fable at 90%, or Antigravity's Gemini session pool at 90%, or Claude's extra-usage spend at 90%) marked the entire account full for all models including Opus. Furthermore, missing usage data read as 0% empty, making unprobed instances look fresh, win "most left" tie-breaks, and incorrectly steal sticky threads through `betterHasRoom`. - Numbers: autoModel 24/24 tests pass (8 new tests failed on base covering model-specific windows, Antigravity pools, monthly spend, expired windows, unknown usage ranking, missing session window, sticky retention, and past-90% ordering). `vp run check:changed` passes clean: format, lint, knip 1/2 and 2/2, typecheck (36 packages), 26 tests in 2 files. - What worked: real run on dev server seeded from read-only live data (`.t3/userdata`), where Auto Low cleanly dispatched and answered "Auto (low)\n\nOK" on Claude Sonnet 5.5. -- Next: read-only review with Claude B, then PR to radys-s/t3code main. +- Review: own read-only review found two bugs, both fixed with a failing assertion first: an account with one unknown window and a known window past 90% ranked as unknown (ahead of known past-90 accounts, and kept sticky threads); `monthly_spend` counted again once plan windows passed 90%, which broke the "most left" order. Also reverted an unrequested change that dropped expired weekly windows from the pace. +- Next: Tomáš merges the PR, then switches the hubs to the new build. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index 0f82efe06892..0fe3cef4d400 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -341,6 +341,13 @@ describe("resolveAutoModelSelection", () => { }); const b = withWeekly(claude("claudeAutoB", 10), 20, inHours(48)); expect(routeTo([a, b])).toBe("claudeAuto"); + const spentPastPlan = withWindow(claude("claudeAuto", 92), { + id: "monthly_spend", + kind: "monthly", + label: "Monthly spend", + usedPercent: 99, + }); + expect(routeTo([claude("claudeAutoB", 95), spentPastPlan])).toBe("claudeAuto"); }); it("ignores a window whose reset has already passed when checking room", () => { @@ -399,6 +406,14 @@ describe("resolveAutoModelSelection", () => { expect(routeTo([noReport, claude("claudeAuto", 95)])).toBe("claudeAutoB"); expect(routeTo([unknown, claude("claudeAuto", 95)])).toBe("claudeAutoB"); expect(routeTo([noReport])).toBe("claudeAutoB"); + // A known window past 90% outranks an unknown one: the account has no room. + const partlyUnknown = withWindow(claude("claudeAutoB", 95), { + id: "seven_day", + kind: "weekly", + label: "Weekly", + resetsAt: inHours(100), + }); + expect(routeTo([partlyUnknown, claude("claudeAuto", 92)])).toBe("claudeAuto"); }); it("ranks an account with no session window after one with a known session", () => { diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index cf778b1eedaa..51aeeeee85b3 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -168,14 +168,9 @@ function roomWindows(provider: ServerProvider, model: string, now: number) { } return true; }); - // Claude's monthly spend caps only extra usage past the plan windows, so it does not count while those windows have room. + // Claude's monthly spend caps only extra usage past the plan windows, so the plan windows decide. const planWindows = windows.filter((w) => w.id !== "monthly_spend"); - const planHasRoom = - planWindows.length > 0 && - planWindows.every( - (w) => typeof w.usedPercent === "number" && w.usedPercent < STICKY_MAX_USED_PERCENT, - ); - return planHasRoom ? planWindows : windows; + return planWindows.length > 0 ? planWindows : windows; } function sessionUsedPercent( @@ -209,9 +204,7 @@ function weeklyWindows(provider: ServerProvider, model: string, now: number) { w.resetsAt === undefined ? now + (w.windowDurationMins ?? Number.NaN) * MINUTE : Date.parse(w.resetsAt); - return Number.isFinite(resetsAt) && resetsAt > now - ? [{ usedPercent: w.usedPercent, resetsAt }] - : []; + return Number.isFinite(resetsAt) ? [{ usedPercent: w.usedPercent, resetsAt }] : []; }); } @@ -284,13 +277,13 @@ function hasRoom(provider: ServerProvider, model: string, now: number): boolean function peakUsedPercent(provider: ServerProvider, model: string, now: number): number | undefined { const windows = roomWindows(provider, model, now); - if ( - windows.length === 0 || - windows.some((w) => typeof w.usedPercent !== "number" || !Number.isFinite(w.usedPercent)) - ) { - return undefined; - } - return Math.max(...windows.map((w) => w.usedPercent!)); + const known = windows.flatMap((w) => + typeof w.usedPercent === "number" && Number.isFinite(w.usedPercent) ? [w.usedPercent] : [], + ); + if (known.length === 0) return undefined; + const peak = Math.max(...known); + // Unknown only while no known window is already past 90%. + return known.length === windows.length || peak >= STICKY_MAX_USED_PERCENT ? peak : undefined; } /** From dcb696c907585998088c0aa9cdae8e77af882caf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 16:04:21 +0100 Subject: [PATCH 100/230] fix(shared): Claude's spend cap limits no model while plan windows exist Read-only review of the room check found that monthly_spend at 100% still made exhaustedUsageWindow block a Claude account whose plan windows had room, although the spend cap applies only to extra usage. The rule now lives in usageWindowLimitsModel, as Codex's credit cap does, so room and exhaustion follow it and the special case in Auto routing goes away. The review also showed that usedPercent is required by the contract and that Grok's missing percentage is a real 0%, so the "window without usedPercent" handling was dead code. It is removed, and the unknown-usage tests use cases that can actually happen: no report, no window that limits the model. Origin: review of 3a1389afe8 on the second Claude account. --- docs/progress.md | 4 +- packages/shared/src/autoModel.test.ts | 36 ++++++------------ packages/shared/src/autoModel.ts | 55 +++++++++------------------ packages/shared/src/usageLimits.ts | 6 +++ 4 files changed, 37 insertions(+), 64 deletions(-) diff --git a/docs/progress.md b/docs/progress.md index 56c0c93229f0..58c98dbaea99 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -148,9 +148,9 @@ ## 2026-11-19: Auto room check counts only windows that limit the model -- What: `hasRoom` and `peakUsedPercent` in Auto routing (`autoModel.ts`) are now model-aware: they only consider active windows that limit the candidate model, determined via `usageWindowLimitsModel`, and ignore expired windows whose reset time has passed. Claude's extra-usage spend window (`monthly_spend`) does not count for room when the account has plan windows; the plan windows decide. Unknown usage (missing report, window without `usedPercent`, or missing session window) no longer masquerades as 0% used: accounts with unknown usage rank after accounts with known room and before accounts past 90%, do not pull sticky threads back via `betterHasRoom`, and an account without a session window ranks after one with a known session. +- What: `hasRoom` and `peakUsedPercent` in Auto routing (`autoModel.ts`) are now model-aware: they only consider active windows that limit the candidate model, determined via `usageWindowLimitsModel`, and ignore expired windows whose reset time has passed. Claude's extra-usage spend window (`monthly_spend`) limits no model when the account has plan windows (`usageWindowLimitsModel`, like Codex's credit cap), so it neither counts for room nor blocks the account at 100% (`exhaustedUsageWindow` was wrong there too). Unknown usage (no report, no window that limits the model, or no session window) no longer masquerades as 0% used: accounts with unknown usage rank after accounts with known room and before accounts past 90%, do not pull sticky threads back via `betterHasRoom`, and an account without a session window ranks after one with a known session. - Why: Auto previously computed `peakUsedPercent` across all windows of an instance regardless of model, so a model-specific window (e.g. Claude's `seven_day_` for Fable at 90%, or Antigravity's Gemini session pool at 90%, or Claude's extra-usage spend at 90%) marked the entire account full for all models including Opus. Furthermore, missing usage data read as 0% empty, making unprobed instances look fresh, win "most left" tie-breaks, and incorrectly steal sticky threads through `betterHasRoom`. - Numbers: autoModel 24/24 tests pass (8 new tests failed on base covering model-specific windows, Antigravity pools, monthly spend, expired windows, unknown usage ranking, missing session window, sticky retention, and past-90% ordering). `vp run check:changed` passes clean: format, lint, knip 1/2 and 2/2, typecheck (36 packages), 26 tests in 2 files. - What worked: real run on dev server seeded from read-only live data (`.t3/userdata`), where Auto Low cleanly dispatched and answered "Auto (low)\n\nOK" on Claude Sonnet 5.5. -- Review: own read-only review found two bugs, both fixed with a failing assertion first: an account with one unknown window and a known window past 90% ranked as unknown (ahead of known past-90 accounts, and kept sticky threads); `monthly_spend` counted again once plan windows passed 90%, which broke the "most left" order. Also reverted an unrequested change that dropped expired weekly windows from the pace. +- Review: own review plus a read-only review on the second Claude account. Fixed, each with a failing assertion first: `monthly_spend` counted again once plan windows passed 90%, and at 100% it blocked an account whose plan had room. Removed dead code: the contract requires `usedPercent`, and Grok's missing percentage is a real 0%, so "a window without `usedPercent`" cannot happen; the tests now use reachable unknown cases. Reverted an unrequested change that dropped expired weekly windows from the pace. Open: providers that never report a window for the model (OpenCode free models, no-usage providers) are always unknown, so a thread that fell back below them never returns through `betterHasRoom`; and an account whose windows have all reset reads as unknown until the next probe. - Next: Tomáš merges the PR, then switches the hubs to the new build. diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index 0fe3cef4d400..115cd940572a 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -348,6 +348,13 @@ describe("resolveAutoModelSelection", () => { usedPercent: 99, }); expect(routeTo([claude("claudeAutoB", 95), spentPastPlan])).toBe("claudeAuto"); + const spendCapped = withWindow(claude("claudeAuto", 20), { + id: "monthly_spend", + kind: "monthly", + label: "Monthly spend", + usedPercent: 100, + }); + expect(routeTo([spendCapped])).toBe("claudeAuto"); }); it("ignores a window whose reset has already passed when checking room", () => { @@ -378,18 +385,17 @@ describe("resolveAutoModelSelection", () => { it("ranks unknown usage after an account with known room", () => { const known = withWeekly(claude("claudeAuto", 0), 30, inHours(100)); - // Grok's credits response omits creditUsagePercent on a unified-billing subscription; its - // reader currently turns that into a fabricated 0%. Without a reading it is unknown, not empty. + // Only a Fable allowance is reported, so nothing says how much Opus room is left. const unknown = { ...claude("claudeAutoB", 0), usageLimits: { windows: [ { - id: "subscription", + id: "seven_day_fable", kind: "weekly", - label: "Weekly", + label: "Weekly · Fable", + usedPercent: 10, resetsAt: inHours(100), - windowDurationMins: 10_080, }, ], }, @@ -406,14 +412,6 @@ describe("resolveAutoModelSelection", () => { expect(routeTo([noReport, claude("claudeAuto", 95)])).toBe("claudeAutoB"); expect(routeTo([unknown, claude("claudeAuto", 95)])).toBe("claudeAutoB"); expect(routeTo([noReport])).toBe("claudeAutoB"); - // A known window past 90% outranks an unknown one: the account has no room. - const partlyUnknown = withWindow(claude("claudeAutoB", 95), { - id: "seven_day", - kind: "weekly", - label: "Weekly", - resetsAt: inHours(100), - }); - expect(routeTo([partlyUnknown, claude("claudeAuto", 92)])).toBe("claudeAuto"); }); it("ranks an account with no session window after one with a known session", () => { @@ -461,17 +459,7 @@ describe("resolveAutoModelSelection", () => { ...claude("grok", 0, false), driver: ProviderDriverKind.make("grok"), models: [{ slug: "grok-4.7", name: "Grok 4.7", isCustom: false, capabilities: null }], - usageLimits: { - windows: [ - { - id: "subscription", - kind: "weekly", - label: "Weekly", - resetsAt: inHours(100), - windowDurationMins: 10_080, - }, - ], - }, + usageLimits: undefined, } as unknown as ServerProvider; const current = { instanceId: ProviderInstanceId.make("openCode"), diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index 51aeeeee85b3..fcf7b2e86036 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -160,29 +160,20 @@ const PACE_BAND = 0.15; const MINUTE = 60_000; const HOUR = 60 * MINUTE; -function roomWindows(provider: ServerProvider, model: string, now: number) { - const windows = (provider.usageLimits?.windows ?? []).filter((w) => { - if (!usageWindowLimitsModel(provider, w, model)) return false; - if (w.resetsAt && Number.isFinite(Date.parse(w.resetsAt)) && Date.parse(w.resetsAt) <= now) { - return false; - } - return true; - }); - // Claude's monthly spend caps only extra usage past the plan windows, so the plan windows decide. - const planWindows = windows.filter((w) => w.id !== "monthly_spend"); - return planWindows.length > 0 ? planWindows : windows; +/** Used % of each window that limits `model` and has not reset yet. */ +function roomPercents(provider: ServerProvider, model: string, now: number, kind?: string) { + return (provider.usageLimits?.windows ?? []).flatMap((w) => + usageWindowLimitsModel(provider, w, model) && + (kind === undefined || w.kind === kind) && + !(w.resetsAt && Date.parse(w.resetsAt) <= now) + ? [w.usedPercent] + : [], + ); } -function sessionUsedPercent( - provider: ServerProvider, - model: string, - now: number, -): number | undefined { - const windows = roomWindows(provider, model, now).filter( - (w) => - w.kind === "session" && typeof w.usedPercent === "number" && Number.isFinite(w.usedPercent), - ); - return windows.length > 0 ? Math.max(...windows.map((w) => w.usedPercent!)) : undefined; +function sessionUsedPercent(provider: ServerProvider, model: string, now: number) { + const percents = roomPercents(provider, model, now, "session"); + return percents.length > 0 ? Math.max(...percents) : undefined; } /** @@ -192,14 +183,7 @@ function sessionUsedPercent( */ function weeklyWindows(provider: ServerProvider, model: string, now: number) { return (provider.usageLimits?.windows ?? []).flatMap((w) => { - if ( - w.kind !== "weekly" || - !usageWindowLimitsModel(provider, w, model) || - typeof w.usedPercent !== "number" || - !Number.isFinite(w.usedPercent) - ) { - return []; - } + if (w.kind !== "weekly" || !usageWindowLimitsModel(provider, w, model)) return []; const resetsAt = w.resetsAt === undefined ? now + (w.windowDurationMins ?? Number.NaN) * MINUTE @@ -275,15 +259,10 @@ function hasRoom(provider: ServerProvider, model: string, now: number): boolean return peak !== undefined && peak < STICKY_MAX_USED_PERCENT; } -function peakUsedPercent(provider: ServerProvider, model: string, now: number): number | undefined { - const windows = roomWindows(provider, model, now); - const known = windows.flatMap((w) => - typeof w.usedPercent === "number" && Number.isFinite(w.usedPercent) ? [w.usedPercent] : [], - ); - if (known.length === 0) return undefined; - const peak = Math.max(...known); - // Unknown only while no known window is already past 90%. - return known.length === windows.length || peak >= STICKY_MAX_USED_PERCENT ? peak : undefined; +/** Undefined when no window that limits `model` reports usage: unknown, not empty. */ +function peakUsedPercent(provider: ServerProvider, model: string, now: number) { + const percents = roomPercents(provider, model, now); + return percents.length > 0 ? Math.max(...percents) : undefined; } /** diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index a0375c7c865e..e7fd93c36839 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -35,6 +35,12 @@ export function usageWindowLimitsModel( } switch (provider.driver) { case "claudeAgent": + // Monthly spend caps only extra usage past the plan windows, so it blocks only accounts without them. + if (window.id === "monthly_spend") { + return !(provider.usageLimits?.windows ?? []).some( + (entry) => entry.id === "five_hour" || entry.id === "seven_day", + ); + } // Claude names a one-model weekly allowance `seven_day_` (see claudeUsageLimits.ts). return ( !window.id.startsWith("seven_day_") || From 63a27c96d7aadddc1380228534ac197fd660f388 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 17:07:44 +0100 Subject: [PATCH 101/230] fix(grok): unified-billing accounts report unknown usage, not 0% MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit On unified-billing xAI accounts, GET /v1/billing?format=credits carries the weekly period and isUnifiedBillingUser: true but never creditUsagePercent, even while Grok refuses turns with "usage limit reached". The reader turned the missing percentage into 0%, so Usage showed Grok as unused and Auto kept routing turns to it. Read isUnifiedBillingUser and, for those accounts, report no window instead of inventing 0%. Auto already treats an account with no window as unknown: after accounts with known room, before accounts past 90%, and never pulling a thread back. Accounts that do get a percentage keep it, and non-unified accounts keep upstream's rule that a missing percentage on a complete period means 0% (#17061). The subscription format's monthlyLimit is 0 on these accounts, so it gives no percentage to fall back to. Origin: Tomáš's report "grok doesn't work or shows wrong quota numbers". --- apps/server/src/provider/GrokProvider.test.ts | 20 ++++++++++++++++++- docs/progress.md | 10 ++++++++++ .../provider-grok/src/server/usageLimits.ts | 11 ++++++++-- 3 files changed, 38 insertions(+), 3 deletions(-) diff --git a/apps/server/src/provider/GrokProvider.test.ts b/apps/server/src/provider/GrokProvider.test.ts index 3f28649f498b..7b9ee76cc340 100644 --- a/apps/server/src/provider/GrokProvider.test.ts +++ b/apps/server/src/provider/GrokProvider.test.ts @@ -534,7 +534,13 @@ describe("Grok usage limits", () => { }); it("does not invent allowance or reset dates when billing omits them", () => { - for (const response of [{}, { config: {} }, { config: { creditUsagePercent: NaN } }]) { + for (const response of [ + {}, + { config: {} }, + { config: { creditUsagePercent: NaN } }, + // Unified billing omits the percentage even when Grok refuses turns at its limit. + { config: { currentPeriod: weeklyPeriod, isUnifiedBillingUser: true } }, + ]) { const limits = grokUsageResponseToLimits(response, checkedAt); expect(limits.windows).toEqual([]); expect(limits.unavailable).toBeUndefined(); @@ -542,6 +548,18 @@ describe("Grok usage limits", () => { expect( grokUsageResponseToLimits({ config: { creditUsagePercent: 0 } }, checkedAt).windows, ).toEqual([{ id: "subscription", kind: "other", label: "Subscription", usedPercent: 0 }]); + expect( + grokUsageResponseToLimits( + { + config: { + creditUsagePercent: 37, + currentPeriod: weeklyPeriod, + isUnifiedBillingUser: true, + }, + }, + checkedAt, + ).windows[0]?.usedPercent, + ).toBe(37); expect( grokUsageResponseToLimits( { diff --git a/docs/progress.md b/docs/progress.md index 58c98dbaea99..0ea518b0c038 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -154,3 +154,13 @@ - What worked: real run on dev server seeded from read-only live data (`.t3/userdata`), where Auto Low cleanly dispatched and answered "Auto (low)\n\nOK" on Claude Sonnet 5.5. - Review: own review plus a read-only review on the second Claude account. Fixed, each with a failing assertion first: `monthly_spend` counted again once plan windows passed 90%, and at 100% it blocked an account whose plan had room. Removed dead code: the contract requires `usedPercent`, and Grok's missing percentage is a real 0%, so "a window without `usedPercent`" cannot happen; the tests now use reachable unknown cases. Reverted an unrequested change that dropped expired weekly windows from the pace. Open: providers that never report a window for the model (OpenCode free models, no-usage providers) are always unknown, so a thread that fell back below them never returns through `betterHasRoom`; and an account whose windows have all reset reads as unknown until the next probe. - Next: Tomáš merges the PR, then switches the hubs to the new build. + +## 2026-11-19: Grok usage is unknown on unified-billing accounts, not 0% + +- What: the Grok usage reader (`grokUsageResponseToLimits`, used by the Grok provider and the CLIProxyAPI usage source) no longer turns a missing `creditUsagePercent` into 0% when the billing response says `isUnifiedBillingUser: true`. Such an account now reports no window. Since #17, Auto reads that as unknown: it ranks after accounts with known room and before accounts past 90%, and it cannot pull a thread back through `betterHasRoom`. Usage → Limits shows "No limits reported." Unchanged: an account that gets a percentage keeps it, and a non-unified account still reads a missing percentage on a complete weekly or monthly period as 0% (upstream #17061). +- Why: Tomáš reported "grok doesn't work or shows wrong quota numbers". On his account `GET /v1/billing?format=credits`, the only billing call the Grok CLI makes, returns the weekly period (2026-11-15 → 11-22), `onDemandCap`, `onDemandUsed` and `prepaidBalance` at 0, and `isUnifiedBillingUser: true`, but no `creditUsagePercent`, even while Grok stops turns with "usage limit reached". T3 showed 0% used, so Auto treated Grok as wide open and kept sending it turns. +- Not used: `?format=subscription` gives `monthlyLimit.val` 0 and `used.val` 1922 for November. A zero limit gives no percentage (0 may mean "no cap" as well as "no allowance"), and it is a monthly figure, not the weekly window that refuses turns. +- Numbers: the new row in `GrokProvider.test.ts` failed on base (a 0% weekly window) and passes; GrokProvider 28/28, cliproxyApi 39/39. `vp run check:changed`: lint, knip, graphql, typecheck (10 packages) and 30 tests in 2 files pass; format passed after `vp fmt` re-wrapped the new test assertion. +- Runtime: the fixed `readGrokAccount` against hub2's live Grok login returned `windows: []`. +- Open: unknown Grok is still picked when it is the first usable candidate in a chain. After "usage limit reached" Grok gives no reset time, so Auto benches it for 30 minutes (`LIMIT_COOLDOWN_MS`) and then tries it again. Using the billing period end as the reset would stop those retries until the week ends. +- Next: Tomáš merges the PR, then switches the hubs to the new build. diff --git a/packages/provider-grok/src/server/usageLimits.ts b/packages/provider-grok/src/server/usageLimits.ts index d7e97518761f..1e714f9df1c7 100644 --- a/packages/provider-grok/src/server/usageLimits.ts +++ b/packages/provider-grok/src/server/usageLimits.ts @@ -29,6 +29,7 @@ export const GrokUsageResponse = Schema.Struct({ config: Schema.optional( Schema.Struct({ creditUsagePercent: Schema.optional(Schema.Number), + isUnifiedBillingUser: Schema.optional(Schema.Boolean), currentPeriod: Schema.optional( Schema.Struct({ type: Schema.optional(Schema.String), @@ -73,8 +74,14 @@ export function grokUsageResponseToLimits( const end = parsePeriodBoundary(period?.end); const windowDurationMins = Math.round((end - start) / 60_000); let usedPercent = response.config?.creditUsagePercent; - if (usedPercent === undefined && (kind === "weekly" || kind === "monthly") && start < end) { - // Grok omits a zero percentage while retaining the complete subscription period. + // Grok omits a zero percentage while retaining the complete subscription period. Unified + // billing omits it at any usage, so there a missing percentage is unknown, not zero. + if ( + usedPercent === undefined && + !response.config?.isUnifiedBillingUser && + (kind === "weekly" || kind === "monthly") && + start < end + ) { usedPercent = 0; } if (usedPercent === undefined || !Number.isFinite(usedPercent)) { From e40222101d11ec8cde799b64d3c623400851412a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 17:10:13 +0100 Subject: [PATCH 102/230] docs: Grok shows no limits on unified-billing accounts The usage guide said Grok reports its remaining allowance after `grok login`. Since the previous commit, accounts on xAI's unified billing show no limits, because xAI's billing response carries no usage percentage for them. Say so, so "No limits reported." is not a surprise. Origin: same report as the previous commit ("grok doesn't work or shows wrong quota numbers"); AGENTS.md asks docs to stay accurate. --- docs/user/usage.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/user/usage.md b/docs/user/usage.md index 5160becc2156..c11fc578a1dd 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -169,8 +169,9 @@ Sign-in and API keys report limits only with Cursor's default API endpoint. If y Cursor endpoint, use an explicit `CURSOR_AUTH_TOKEN` for limits. Grok reports the remaining subscription allowance and reset time for its current billing period -after signing in with `grok login`. Explicit `XAI_API_KEY` connections and custom authentication -or endpoint configurations do not report subscription limits. +after signing in with `grok login`. Accounts on xAI's unified billing show no limits, because xAI +does not report how much of their allowance is used. Explicit `XAI_API_KEY` connections and custom +authentication or endpoint configurations do not report subscription limits. Muse Code reports its session and weekly windows and its tier once the Muse CLI has run in a thread. Until then it shows no limits. Readings are not kept across a server restart. From 7c344307b521a684244be5d5d5ff8b29d392715a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 17:12:06 +0100 Subject: [PATCH 103/230] chore(grok): word the unified-billing comment to what was observed The comment said unified billing omits the percentage "at any usage", but that rests on one account checked at its limit; say "even at the limit". Drop the test comment that repeated the source comment. Origin: read-only review of the unified-billing quota fix (two nits). --- apps/server/src/provider/GrokProvider.test.ts | 1 - packages/provider-grok/src/server/usageLimits.ts | 2 +- 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/apps/server/src/provider/GrokProvider.test.ts b/apps/server/src/provider/GrokProvider.test.ts index 7b9ee76cc340..f88964369b53 100644 --- a/apps/server/src/provider/GrokProvider.test.ts +++ b/apps/server/src/provider/GrokProvider.test.ts @@ -538,7 +538,6 @@ describe("Grok usage limits", () => { {}, { config: {} }, { config: { creditUsagePercent: NaN } }, - // Unified billing omits the percentage even when Grok refuses turns at its limit. { config: { currentPeriod: weeklyPeriod, isUnifiedBillingUser: true } }, ]) { const limits = grokUsageResponseToLimits(response, checkedAt); diff --git a/packages/provider-grok/src/server/usageLimits.ts b/packages/provider-grok/src/server/usageLimits.ts index 1e714f9df1c7..6da757bdb1aa 100644 --- a/packages/provider-grok/src/server/usageLimits.ts +++ b/packages/provider-grok/src/server/usageLimits.ts @@ -75,7 +75,7 @@ export function grokUsageResponseToLimits( const windowDurationMins = Math.round((end - start) / 60_000); let usedPercent = response.config?.creditUsagePercent; // Grok omits a zero percentage while retaining the complete subscription period. Unified - // billing omits it at any usage, so there a missing percentage is unknown, not zero. + // billing omits it even at the limit, so there a missing percentage is unknown, not zero. if ( usedPercent === undefined && !response.config?.isUnifiedBillingUser && From 9a5230d0f6cf0fc1ca1c5369b03271e29dfd4881 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 18:59:34 +0100 Subject: [PATCH 104/230] fix(client-runtime): keep Resume on providers without native resume Upstream #39229 hides Resume when the run's provider session reports supportsNativeResume: false (ACP, so Grok, Kiro, fx and ACP Registry, plus Pi and Muse) and no message is left unsent, because upstream's server fails such a resume with "Native resume is unavailable". The fork's server sends "Continue where you left off." instead (2026-11-15, the Grok incident), so hiding the button would drop that fork feature on exactly the providers it was built for. deriveResumableRunId goes back to offering Resume for every interrupted or usage-limited run; the capability flag and the adapters stay as upstream has them. Upstream's test row for a provider without native resume now expects Resume; it failed on the merge and passes here. Origin: semantic conflict found while syncing the fork with upstream 8edefc8818. --- .../src/state/threadExecution.test.ts | 3 +- .../src/state/threadExecution.ts | 28 ++----------------- 2 files changed, 4 insertions(+), 27 deletions(-) diff --git a/packages/client-runtime/src/state/threadExecution.test.ts b/packages/client-runtime/src/state/threadExecution.test.ts index b03236959d78..3a021d5f0f2f 100644 --- a/packages/client-runtime/src/state/threadExecution.test.ts +++ b/packages/client-runtime/src/state/threadExecution.test.ts @@ -199,11 +199,12 @@ describe("thread execution presentation", () => { }); it.each([ + // Fork: the server continues such a run with a prompt (ProviderTurnStartService). { name: "a provider without native resume", nativeResume: false, delivered: true, - resumes: false, + resumes: true, }, { name: "an undelivered message", nativeResume: false, delivered: false, resumes: true }, { name: "a provider with native resume", nativeResume: true, delivered: true, resumes: true }, diff --git a/packages/client-runtime/src/state/threadExecution.ts b/packages/client-runtime/src/state/threadExecution.ts index de0c2672cbde..e9a43bd13816 100644 --- a/packages/client-runtime/src/state/threadExecution.ts +++ b/packages/client-runtime/src/state/threadExecution.ts @@ -35,7 +35,6 @@ import { resolveSelectableModel, withLegacyUltracodeEffort, } from "@t3tools/shared/model"; -import { unsentManualContinuationSource } from "@t3tools/shared/orchestrationV2ManualContinuation"; import { formatDuration } from "@t3tools/shared/orchestrationTiming"; import * as DateTime from "effect/DateTime"; @@ -318,10 +317,7 @@ export function formatProviderSubagentStatus( /** The run a manual continuation resumes; the server holds the queue until it does. */ export function deriveResumableRunId( - projection: Pick< - ThreadStructure, - "runs" | "turnItems" | "attempts" | "providerTurns" | "providerThreads" | "providerSessions" - >, + projection: Pick, runtime: Pick | null, ): RunId | null { const run = latestExecutedRun(projection.runs); @@ -330,31 +326,11 @@ export function deriveResumableRunId( (run?.status === "failed" && runtime?.lastErrorClass === "usage_limit" && latestRootProviderFailure(run, projection.turnItems)?.class === "usage_limit"); + // Fork: offered without native resume too; the server then sends a continue prompt. if (!resumable) return null; - // Without native resume the server can only resend a message the provider never received. - if ( - runProviderSession(projection, run)?.capabilities.turns.supportsNativeResume === false && - unsentManualContinuationSource({ manualContinuationOfRunId: run.id }, projection) === undefined - ) { - return null; - } return run.id; } -function runProviderSession( - projection: Pick, - run: ThreadStructure["runs"][number], -) { - const sessionId = projection.providerThreads.find( - (thread) => thread.id === run.providerThreadId, - )?.providerSessionId; - return sessionId == null - ? projection.providerSessions.findLast( - (session) => session.providerInstanceId === run.providerInstanceId, - ) - : projection.providerSessions.find((session) => session.id === sessionId); -} - /** * Whether Resume can start: the run's continuation, else the held queue. The server refuses that * continuation while any request is pending, so the queue must not be released in its place. From 48e0ed0397425acf33f34bdfce012a6a2d0d8143 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 19:27:16 +0100 Subject: [PATCH 105/230] test(client-runtime): give the Auto handoff fixture real usage window ids "previews an Auto selection as the model Auto keeps, not as a handoff" has failed on fork main since #17 with "Cannot read properties of undefined (reading 'startsWith')": #17 made hasRoom read only the windows that limit the model, through usageWindowLimitsModel, which reads window.id. The fixture's windows had no id or label, which the contract requires (ServerProviderUsageWindow), so they could never come from a real provider. #17's checks ran only autoModel and usageLimits, so this test was not run there. Origin: check:changed against upstream/main during the upstream sync. --- packages/client-runtime/src/handoff.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/packages/client-runtime/src/handoff.test.ts b/packages/client-runtime/src/handoff.test.ts index 071aa10fccd1..a6054f21aa6e 100644 --- a/packages/client-runtime/src/handoff.test.ts +++ b/packages/client-runtime/src/handoff.test.ts @@ -184,7 +184,9 @@ describe("pending context handoff", () => { status: "ready", auth: { status: "authenticated" }, models: [{ slug: "claude-sonnet-5-5", capabilities: { optionDescriptors: [] } }], - usageLimits: { windows: [{ kind: "session", usedPercent }] }, + usageLimits: { + windows: [{ id: "five_hour", kind: "session", label: "Session", usedPercent }], + }, }) as unknown as ServerProvider; const autoLow = { instanceId: to, model: "auto-low" }; From 604e4220942b443bb21e44fa9f07088161430854 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 19:28:06 +0100 Subject: [PATCH 106/230] chore(server): name the sessions that continue Resume with a prompt The fork's comments listed OpenCode among the providers without native resume, but both OpenCode adapters implement resumeTurn (and upstream #39229 now flags them supportsNativeResume: true), so an OpenCode Resume resumes natively. The comments now name the sessions the prompt path serves and drop the history. Origin: read-only review of the upstream sync. --- .../src/orchestration-v2/ProviderTurnStartService.test.ts | 3 +-- apps/server/src/orchestration-v2/ProviderTurnStartService.ts | 5 ++--- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 16d8927e69b2..858e49b541cb 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -2255,8 +2255,7 @@ effectIt.effect("sends new steering text when restarting a manual continuation", }), ); -// Fork: upstream failed here with "Native resume is unavailable", which left Grok, OpenCode and -// Antigravity threads stuck on Resume. The fork starts an ordinary turn that asks to continue. +// Fork: upstream refuses this resume ("Native resume is unavailable"); the fork asks to continue. effectIt.effect("asks to continue when the provider cannot resume natively", () => Effect.gen(function* () { const harness = makeLocalCommandHarness({ diff --git a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts index 274d74e26fcc..f06a6b47b3c2 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -970,9 +970,8 @@ export const layer: Layer.Layer< }); let effectiveHandoffs = handoffs; let resumeFellBack = false; - // Fork: Resume on a provider with no native resume (Grok, OpenCode, Antigravity, or a run - // that moved to another provider) used to fail with "Native resume is unavailable". It now - // starts an ordinary turn that asks the agent to continue. + // Fork: a session without native resume (Grok and the other ACP agents, Pi, Muse, + // Antigravity) continues with a prompt instead of failing with "Native resume is unavailable". const continueInstead = manualResume && unsentResumeMessage === undefined && session.resumeTurn === undefined; const userText = continueInstead From d79c16ec54c3328d42313fabec83694765088ed5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 19:42:07 +0100 Subject: [PATCH 107/230] docs: record the upstream 8edefc8818 sync MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds the docs/progress.md entry for the merge of upstream 8edefc8818: the semantic conflict on Resume, the fixture found on the way, the check numbers and the real run. Origin: Tomáš asked for a progress entry with the sync. --- docs/progress.md | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/docs/progress.md b/docs/progress.md index 0ea518b0c038..794c022123e2 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -164,3 +164,18 @@ - Runtime: the fixed `readGrokAccount` against hub2's live Grok login returned `windows: []`. - Open: unknown Grok is still picked when it is the first usable candidate in a chain. After "usage limit reached" Grok gives no reset time, so Auto benches it for 30 minutes (`LIMIT_COOLDOWN_MS`) and then tries it again. Using the billing period end as the reset would stop those retries until the week ends. - Next: Tomáš merges the PR, then switches the hubs to the new build. + +## 2026-11-19: Fork synced with upstream `8edefc8818` by a merge + +- What: upstream main `8edefc8818`, 41 commits newer than the last sync base `aced664ed9`, was merged into fork main `fefb7f24a7` with a real merge (`6e4ad0e032`). Fork main stays an ancestor, so the PR merges without a force-push and the fork's commits keep their ids. The last three syncs replayed the fork commits onto upstream and recorded fork main with an `-s ours` merge; with 41 commits and no textual conflicts, a merge is the smaller change. +- Why: fork main was 41 upstream commits behind after #16. +- Conflicts: none in the text. Seven files changed on both sides and git merged them: `ClaudeAdapterV2.ts`, `Orchestrator.ts`, `ProviderTurnStartService.ts` and its test, `ProviderRegistry.test.ts`, `ChatView.tsx` and `packages/shared/package.json`. +- Semantic conflict: upstream #39229 hides Resume when the run's provider session reports `supportsNativeResume: false` (ACP, so Grok, Kiro, fx and ACP Registry, plus Pi and Muse) and no message is left unsent, because upstream's server refuses such a resume. The fork's server sends "Continue where you left off." instead (2026-11-15), so `deriveResumableRunId` offers Resume for every interrupted or usage-limited run again. Upstream's capability flag and adapter values stay. Sessions recorded before this build carry no flag, so the gate would first have shown on new Grok sessions. +- Fork behavior kept: per file, the lines the fork adds and removes in `git diff upstream/main...origin/main` (old base) and `git diff upstream/main...HEAD` (new base) are the same for 59 of 61 files; the other two are the Resume fix. +- Checked and left alone: #39103 (a turn start reads fewer subagents, transfers and messages; the unsent message and the handoffs the resume prompt needs are still read), #39114 (`modelsRetained` keeps a failed check's models in the picker; Auto's `usable()` never read provider status), #39049 (released sessions), #39132 (fresh runs retire side-chat handoffs). +- Found on the way: `handoff.test.ts` "previews an Auto selection as the model Auto keeps, not as a handoff" has failed on fork main since #17 (a `TypeError` reading `window.id`). Its usage windows lacked the `id` and `label` the contract requires, and #17's checks ran only autoModel and usageLimits. The fixture now has them. Comments in `ProviderTurnStartService` listed OpenCode among the providers without native resume; both OpenCode adapters resume natively. +- Numbers: `vp run check:changed` against fork main (157 files, at `9a5230d0f6`): unused patches, format, lint, knip, graphql, typecheck (42 packages) and react compiler pass; tests 3705/3706 in 79 files. The one failure, upstream's `ChatView.browser.test.tsx` retention test ("lets go of the thread structures it has replaced", #36390), hit its 15 s timeout under that load and passes alone. `vp run check:changed upstream/main` (the fork's 61 files, at `604e422094`): all pass, 1062 tests in 29 files. `vp run i18n:check` pass. Focused: ClaudeAdapterV2 470/470, ProviderTurnStartService 90/90, ProviderRegistry 94/94, the 3 Orchestrator files 34/34, AutoFailoverService 8/8, GrokProvider 28/28, autoModel 24/24, usageLimits 99/99, usagePoolProjection 7/7, handoff 17/17, threadExecution 37/37 (its no-native-resume row failed on the merge). +- Real run (worktree `.t3` seeded from a read-only snapshot of the live database, settings with only the two Auto instances and `autoResumeLimitedThreads` off): migration `100_TurnStartReadIndexes` applied to the snapshot, and the server started with no errors in its log. One Auto Low turn in a scratch project, sent over the CLI, went to Auto B on Sonnet 5.5 and answered "OK" with `Auto level: low` from its system prompt. +- Review: one read-only review on the second Claude account found no bugs. Taken: the OpenCode comment. Left: upstream's Resume test table now expects Resume in every row; keeping upstream's rows keeps later syncs simple. +- Switching the hubs: migration `100_TurnStartReadIndexes` adds three partial indexes. The Node pins did not change. +- Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Not checked in a browser: the Resume button on a stopped Grok run. From cb47dcb35b8d065bded1d5f7286a3fc39157da2f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 21:06:17 +0100 Subject: [PATCH 108/230] fix(web,mobile): say that "Resume after usage limits" also moves Auto threads The switch also gates Auto failover (AutoFailoverService sends nothing while it is off), but its description only mentioned resuming at reset. It was off on both hubs, so a limited Auto thread sat idle for 50 minutes instead of moving to the next subscription. Rewrite the description on web and mobile, add failover search terms, update the user doc sentence, and translate the new strings in every locale. --- .../src/features/settings/ThreadSettingsSections.tsx | 2 +- apps/mobile/src/i18n/translations/de.json | 2 +- apps/mobile/src/i18n/translations/en.json | 2 +- apps/mobile/src/i18n/translations/es.json | 2 +- apps/mobile/src/i18n/translations/fr.json | 2 +- apps/mobile/src/i18n/translations/ja.json | 2 +- apps/mobile/src/i18n/translations/ko.json | 2 +- apps/mobile/src/i18n/translations/pt-BR.json | 2 +- apps/mobile/src/i18n/translations/ru.json | 2 +- apps/mobile/src/i18n/translations/sv.json | 2 +- apps/mobile/src/i18n/translations/zh.json | 2 +- apps/web/src/components/settings/SettingsPanels.tsx | 2 +- apps/web/src/components/settings/settingsSearch.ts | 6 +++++- apps/web/src/i18n/translations/de.json | 6 +++--- apps/web/src/i18n/translations/en.json | 6 +++--- apps/web/src/i18n/translations/es.json | 6 +++--- apps/web/src/i18n/translations/fr.json | 6 +++--- apps/web/src/i18n/translations/ja.json | 6 +++--- apps/web/src/i18n/translations/ko.json | 6 +++--- apps/web/src/i18n/translations/pt-BR.json | 6 +++--- apps/web/src/i18n/translations/ru.json | 6 +++--- apps/web/src/i18n/translations/sv.json | 6 +++--- apps/web/src/i18n/translations/zh.json | 6 +++--- docs/progress.md | 8 ++++++++ docs/user/thread-sidebar.md | 2 ++ 25 files changed, 57 insertions(+), 43 deletions(-) diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx index a23f0c98932e..6094e83261b3 100644 --- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx +++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx @@ -138,7 +138,7 @@ export function AutoSettleSettingsRows(props: { icon="clock" label={gt("Resume after usage limits")} subtitle={gt( - "Automatically resume threads when their usage limits reset. You can cancel auto-resume in each thread.", + "Continue threads after a usage limit: threads on Auto move to the next subscription with room, other threads resume when their limit resets. You can cancel auto-resume in each thread.", )} value={uniformMobileSetting(displayTargets, "autoResumeLimitedThreads")} disabled={disabledFor("autoResumeLimitedThreads")} diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index cabb9a34dbe9..87ca4977fe5c 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -3706,7 +3706,7 @@ "67937aa49179285e": "Auf einem Mac neue Worktrees aus einem im T3-Home-Ordner zwischengespeicherten Checkout klonen, statt jede Datei zu schreiben. Verwendet den normalen Git-Checkout, wenn das nicht geht. Beim Ausschalten wird der Cache gelöscht.", "d6ada5ec242e37ff": "Nutzungslimits", "62127e7b5c0f57a3": "Nach Nutzungslimits fortsetzen", - "4df30d44eb0b0728": "Threads automatisch fortsetzen, wenn ihre Nutzungslimits zurückgesetzt werden. Du kannst das automatische Fortsetzen in jedem Thread abbrechen.", + "4e8a6e262304c240": "Threads nach einem Nutzungslimit fortsetzen: Threads auf Auto wechseln zum nächsten Abo mit freiem Kontingent, andere Threads werden fortgesetzt, wenn ihr Limit zurückgesetzt wird. Du kannst das automatische Fortsetzen in jedem Thread abbrechen.", "20e3a8aab5f9426a": "Bis zum Zurücksetzen der Limits zurückstellen", "0769f91ca46e3003": "Threads zurückstellen, bis ihre Nutzungslimits zurückgesetzt werden. Aktiviere automatisches Fortsetzen, damit der Agent nach dem Zurücksetzen weiterarbeitet.", "7c27e91e75cce7a3": "Automatisch erledigen", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index fa572328fc87..4aaea24593ea 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -3707,7 +3707,7 @@ "67937aa49179285e": "On a Mac, clone new worktrees from a checkout cached in the T3 home folder instead of writing every file. Uses Git’s normal checkout when it can’t. Turning it off deletes the cache.", "d6ada5ec242e37ff": "Usage limits", "62127e7b5c0f57a3": "Resume after usage limits", - "4df30d44eb0b0728": "Automatically resume threads when their usage limits reset. You can cancel auto-resume in each thread.", + "4e8a6e262304c240": "Continue threads after a usage limit: threads on Auto move to the next subscription with room, other threads resume when their limit resets. You can cancel auto-resume in each thread.", "20e3a8aab5f9426a": "Snooze until limits reset", "0769f91ca46e3003": "Snooze threads until their usage limits reset. Enable auto-resume to continue the agent after the reset.", "7c27e91e75cce7a3": "Auto-settle", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index aaeb8230bc83..e3328a4a7876 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -3701,7 +3701,7 @@ "67937aa49179285e": "En un Mac, clona los nuevos worktrees desde un checkout en caché en la carpeta de inicio de T3 en lugar de escribir cada archivo. Usa el checkout normal de Git cuando no puede. Al desactivarlo se elimina la caché.", "d6ada5ec242e37ff": "Límites de uso", "62127e7b5c0f57a3": "Reanudar tras los límites de uso", - "4df30d44eb0b0728": "Reanuda automáticamente los hilos cuando se restablecen sus límites de uso. Puedes cancelar la reanudación automática en cada hilo.", + "4e8a6e262304c240": "Continúa los hilos tras un límite de uso: los hilos en Auto pasan a la siguiente suscripción con margen y los demás se reanudan cuando se restablece su límite. Puedes cancelar la reanudación automática en cada hilo.", "20e3a8aab5f9426a": "Posponer hasta que se restablezcan los límites", "0769f91ca46e3003": "Pospone los hilos hasta que se restablezcan sus límites de uso. Activa la reanudación automática para que el agente continúe tras el restablecimiento.", "7c27e91e75cce7a3": "Resolver automáticamente", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 371ab3d7532d..eba6f1dc0292 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -3701,7 +3701,7 @@ "67937aa49179285e": "Sur Mac, clone les nouveaux worktrees depuis une copie en cache dans le dossier T3 home au lieu d’écrire chaque fichier. Utilise le checkout Git normal quand ce n’est pas possible. La désactivation supprime le cache.", "d6ada5ec242e37ff": "Limites d’utilisation", "62127e7b5c0f57a3": "Reprendre après les limites d’utilisation", - "4df30d44eb0b0728": "Reprend automatiquement les fils quand leurs limites d’utilisation sont réinitialisées. Vous pouvez annuler la reprise automatique dans chaque fil.", + "4e8a6e262304c240": "Poursuivre les fils après une limite d’utilisation : les fils en Auto passent à l’abonnement suivant qui a de la marge, les autres reprennent quand leur limite est réinitialisée. Vous pouvez annuler la reprise automatique dans chaque fil.", "20e3a8aab5f9426a": "Reporter jusqu’à la réinitialisation des limites", "0769f91ca46e3003": "Reporte les fils jusqu’à la réinitialisation de leurs limites d’utilisation. Activez la reprise automatique pour que l’agent continue après la réinitialisation.", "7c27e91e75cce7a3": "Clôture automatique", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index 32b5c4d8f974..4ebb2744caa4 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -3698,7 +3698,7 @@ "67937aa49179285e": "Mac では、すべてのファイルを書き込む代わりに、T3 ホームフォルダーにキャッシュしたチェックアウトから新しいワークツリーを複製します。できない場合は Git の通常のチェックアウトを使います。オフにするとキャッシュは削除されます。", "d6ada5ec242e37ff": "使用量の上限", "62127e7b5c0f57a3": "使用量の上限後に再開", - "4df30d44eb0b0728": "使用量の上限がリセットされたら、スレッドを自動的に再開します。自動再開は各スレッドでキャンセルできます。", + "4e8a6e262304c240": "使用量の上限に達したスレッドを続行します。Auto のスレッドは余裕のある次のサブスクリプションに移り、それ以外のスレッドは上限のリセット時に再開します。自動再開は各スレッドでキャンセルできます。", "20e3a8aab5f9426a": "上限がリセットされるまでスヌーズ", "0769f91ca46e3003": "使用量の上限がリセットされるまでスレッドをスヌーズします。リセット後にエージェントを続行するには、自動再開を有効にしてください。", "7c27e91e75cce7a3": "自動で対応済みにする", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index 0cd8713696dc..6708b677c628 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -3702,7 +3702,7 @@ "67937aa49179285e": "Mac에서 모든 파일을 쓰는 대신 T3 홈 폴더에 캐시된 체크아웃에서 새 워크트리를 복제합니다. 불가능하면 Git의 일반 체크아웃을 사용합니다. 끄면 캐시가 삭제됩니다.", "d6ada5ec242e37ff": "사용량 한도", "62127e7b5c0f57a3": "사용량 한도 후 재개", - "4df30d44eb0b0728": "사용량 한도가 초기화되면 스레드를 자동으로 재개합니다. 각 스레드에서 자동 재개를 취소할 수 있습니다.", + "4e8a6e262304c240": "사용량 한도 후 스레드를 계속합니다. Auto 스레드는 여유가 있는 다음 구독으로 옮겨지고, 다른 스레드는 한도가 초기화되면 다시 시작됩니다. 각 스레드에서 자동 재개를 취소할 수 있습니다.", "20e3a8aab5f9426a": "한도가 초기화될 때까지 다시 알림", "0769f91ca46e3003": "사용량 한도가 초기화될 때까지 스레드를 미룹니다. 초기화 후 에이전트를 계속하려면 자동 재개를 사용하세요.", "7c27e91e75cce7a3": "자동 정리", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index caac483484c2..fa9ebcc94bc1 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -3701,7 +3701,7 @@ "67937aa49179285e": "No Mac, clona novos worktrees a partir de um checkout em cache na pasta T3 home em vez de gravar cada arquivo. Usa o checkout normal do Git quando não consegue. Desativar exclui o cache.", "d6ada5ec242e37ff": "Limites de uso", "62127e7b5c0f57a3": "Retomar após limites de uso", - "4df30d44eb0b0728": "Retoma as threads automaticamente quando os limites de uso delas forem redefinidos. Você pode cancelar a retomada automática em cada thread.", + "4e8a6e262304c240": "Continue as threads após um limite de uso: threads no Auto passam para a próxima assinatura com margem, e as outras são retomadas quando o limite delas é redefinido. Você pode cancelar a retomada automática em cada thread.", "20e3a8aab5f9426a": "Adiar até os limites serem redefinidos", "0769f91ca46e3003": "Adia as threads até os limites de uso delas serem redefinidos. Ative a retomada automática para continuar o agente após a redefinição.", "7c27e91e75cce7a3": "Concluir automaticamente", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index d5439f969813..94fdb61258f7 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -3755,7 +3755,7 @@ "67937aa49179285e": "На Mac клонировать новые рабочие деревья из копии, закешированной в домашней папке T3, вместо записи каждого файла. Если это невозможно, используется обычный checkout Git. При выключении кеш удаляется.", "d6ada5ec242e37ff": "Лимиты использования", "62127e7b5c0f57a3": "Возобновление после лимитов", - "4df30d44eb0b0728": "Автоматически возобновлять треды при сбросе лимитов использования. Автовозобновление можно отменить в каждом треде.", + "4e8a6e262304c240": "Продолжать треды после лимита использования: треды на Auto переходят на следующую подписку с запасом, остальные возобновляются после сброса лимита. Автовозобновление можно отменить в каждом треде.", "20e3a8aab5f9426a": "Отложить до сброса лимитов", "0769f91ca46e3003": "Откладывать треды до сброса лимитов использования. Включите автовозобновление, чтобы агент продолжил после сброса.", "7c27e91e75cce7a3": "Авторазбор", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index 7a634bcab134..7f627398641d 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -3707,7 +3707,7 @@ "67937aa49179285e": "På en Mac klonas nya worktrees från en utcheckning som cachas i T3-hemmappen i stället för att varje fil skrivs. Använder Gits vanliga utcheckning när det inte går. Om du stänger av det tas cachen bort.", "d6ada5ec242e37ff": "Användningsgränser", "62127e7b5c0f57a3": "Återuppta efter användningsgränser", - "4df30d44eb0b0728": "Återuppta trådar automatiskt när deras användningsgränser återställs. Du kan avbryta automatisk återupptagning i varje tråd.", + "4e8a6e262304c240": "Fortsätt trådar efter en användningsgräns: trådar på Auto flyttas till nästa prenumeration med utrymme, andra trådar återupptas när gränsen återställs. Du kan avbryta automatisk återupptagning i varje tråd.", "20e3a8aab5f9426a": "Snooza tills gränserna återställs", "0769f91ca46e3003": "Snooza trådar tills deras användningsgränser återställs. Aktivera automatisk återupptagning för att fortsätta agenten efter återställningen.", "7c27e91e75cce7a3": "Markera som klar automatiskt", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 98b946c76f02..bf718f146624 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -3703,7 +3703,7 @@ "67937aa49179285e": "在 Mac 上,从缓存在 T3 主目录中的工作副本克隆新的工作树,无需逐个写入每个文件。无法使用时改为 Git 的常规检出。关闭后会删除缓存。", "d6ada5ec242e37ff": "用量限制", "62127e7b5c0f57a3": "用量限制解除后继续", - "4df30d44eb0b0728": "用量限制重置后自动继续会话。你可以在每个会话中取消自动继续。", + "4e8a6e262304c240": "达到用量限制后继续会话:使用 Auto 的会话会切换到下一个仍有余量的订阅,其他会话会在限制重置后继续。你可以在每个会话中取消自动继续。", "20e3a8aab5f9426a": "暂缓到用量限制重置", "0769f91ca46e3003": "将会话暂缓到用量限制重置。开启自动继续后,智能体会在重置后接着工作。", "7c27e91e75cce7a3": "自动收尾", diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index e0a12417848f..6f22e75624bc 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -1991,7 +1991,7 @@ export function ThreadsSettingsPanel() { serverScoped {...setting("auto-resume-limited-threads")} description={gt( - "Automatically resume threads when their usage limits reset. You can cancel auto-resume in each thread.", + "Continue threads after a usage limit: threads on Auto move to the next subscription with room, other threads resume when their limit resets. You can cancel auto-resume in each thread.", )} settingKeys={["autoResumeLimitedThreads"]} control={ diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index b02f8d2f0b0c..69252eff2837 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -479,7 +479,11 @@ export const SETTINGS_SEARCH_ITEMS = [ id: "auto-resume-limited-threads", title: msg("Resume after usage limits"), to: "/settings/threads", - searchTerms: [msg("usage quota rate limit reset recover continue")], + searchTerms: [ + msg( + "usage quota rate limit reset recover continue auto failover switch subscription account", + ), + ], }, { id: "working-shelf", diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 894f421428da..ac9db8e0bef7 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -4084,6 +4084,7 @@ "66be4fb43249bbd2": "{used} von {max} Tokens", "ee3ae58c8b38a425": "{left} % übrig", "ebb26f93fb83a71b": "{label}: {left} % übrig", + "1b16346722b65812": "{timeLeft} % des Zeitfensters übrig", "728c6cc1431e76c8": "Wird in {duration} zurückgesetzt · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Die Zwischenablage-API ist beim Kopieren der Admin-Anfrage nicht verfügbar.", @@ -9826,7 +9827,7 @@ "6fc9e5e722cf3c73": "Klone landen unter github.com/owner/repo im Ordner oben, wie bei ghq.", "bee548d674abd0d2": "In Host-Ordner klonen auf Standard zurücksetzen", "ef27c4211844aef9": "Zurückstellen", - "4df30d44eb0b0728": "Threads automatisch fortsetzen, wenn ihre Nutzungslimits zurückgesetzt werden. Du kannst das automatische Fortsetzen in jedem Thread abbrechen.", + "4e8a6e262304c240": "Threads nach einem Nutzungslimit fortsetzen: Threads auf Auto wechseln zum nächsten Abo mit freiem Kontingent, andere Threads werden fortgesetzt, wenn ihr Limit zurückgesetzt wird. Du kannst das automatische Fortsetzen in jedem Thread abbrechen.", "0769f91ca46e3003": "Threads zurückstellen, bis ihre Nutzungslimits zurückgesetzt werden. Aktiviere automatisches Fortsetzen, damit der Agent nach dem Zurücksetzen weiterarbeitet.", "7c27e91e75cce7a3": "Automatisch erledigen", "cf6c5aa9b63957e6": "Einen Thread erledigen, wenn sein Pull Request gemergt wird. Geschlossene Pull Requests werden weiterhin automatisch erledigt.", @@ -11458,7 +11459,7 @@ "c437e0f28c6d4a4b": "projekte sortieren seitenleiste manuell erstellt zuletzt", "cb309dc06cf679ae": "zurückstellen vorlagen zeiten später heute abend morgen nächste woche erinnern", "6751449c6188912d": "nutzung kontingent rate limit zurücksetzen aufwecken wiederherstellen fortsetzen", - "0aedae6a82c09429": "nutzung kontingent rate limit zurücksetzen wiederherstellen fortsetzen", + "5190923c9a9d6a2e": "nutzung kontingent rate limit zurücksetzen wiederherstellen fortsetzen auto failover wechseln abo konto", "85dbcfec2d41f534": "ausblenden einklappen laufende überwachende threads posteingang seitenleiste in arbeit ablage", "405a2295152c9d77": "beta ordner projektbaum klassische seitenleiste", "de42c4690914cee4": "beta schlichte seitenleiste ordner zeilen mehrzeilig branch pull request details", @@ -11858,7 +11859,6 @@ "0bd938825ffcf992": "+{percent} % des Kontingents", "09c0e00d7fb55402": "Reset-Guthaben wird verwendet…", "4df3ff1be768a7ab": "{name}: {remaining} % übrig", - "1b16346722b65812": "{timeLeft} % des Zeitfensters übrig", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "0-$-Limit", "98947080075a0e9f": "of {capacity}%", diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 5b53a8964d6f..97c4f2a525ae 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -4083,6 +4083,7 @@ "66be4fb43249bbd2": "{used} of {max} tokens", "ee3ae58c8b38a425": "{left}% left", "ebb26f93fb83a71b": "{label}: {left}% left", + "1b16346722b65812": "{timeLeft}% of the window left", "728c6cc1431e76c8": "Resets in {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Clipboard API is unavailable while copying admin request.", @@ -9835,7 +9836,7 @@ "6fc9e5e722cf3c73": "Clones go to github.com/owner/repo under the folder above, like ghq.", "bee548d674abd0d2": "Reset clone into host folders to default", "ef27c4211844aef9": "Snooze", - "4df30d44eb0b0728": "Automatically resume threads when their usage limits reset. You can cancel auto-resume in each thread.", + "4e8a6e262304c240": "Continue threads after a usage limit: threads on Auto move to the next subscription with room, other threads resume when their limit resets. You can cancel auto-resume in each thread.", "0769f91ca46e3003": "Snooze threads until their usage limits reset. Enable auto-resume to continue the agent after the reset.", "7c27e91e75cce7a3": "Auto-settle", "cf6c5aa9b63957e6": "Settle a thread when its pull request merges. Closed pull requests still settle automatically.", @@ -11466,7 +11467,7 @@ "c437e0f28c6d4a4b": "sort projects sidebar manual created recent", "cb309dc06cf679ae": "snooze presets times later tonight tomorrow next week remind", "6751449c6188912d": "usage quota rate limit reset wake recover continue", - "0aedae6a82c09429": "usage quota rate limit reset recover continue", + "5190923c9a9d6a2e": "usage quota rate limit reset recover continue auto failover switch subscription account", "85dbcfec2d41f534": "hide fold running monitoring threads inbox sidebar shelf", "405a2295152c9d77": "beta folders project tree classic sidebar", "de42c4690914cee4": "beta boring sidebar folder rows multiline branch pull request details", @@ -11866,7 +11867,6 @@ "0bd938825ffcf992": "+{percent}% of pool", "09c0e00d7fb55402": "Using reset credit…", "4df3ff1be768a7ab": "{name}: {remaining}% left", - "1b16346722b65812": "{timeLeft}% of the window left", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "$0 cap", "98947080075a0e9f": "of {capacity}%", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index e2b4e8cf6f2c..49e2dc82b08d 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -4081,6 +4081,7 @@ "66be4fb43249bbd2": "{used} de {max} tokens", "ee3ae58c8b38a425": "{left} % restante", "ebb26f93fb83a71b": "{label}: {left} % restante", + "1b16346722b65812": "Queda un {timeLeft}% de la ventana", "728c6cc1431e76c8": "Se restablece en {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "La API del portapapeles no está disponible al copiar la solicitud de administrador.", @@ -9823,7 +9824,7 @@ "6fc9e5e722cf3c73": "Los clones van a github.com/owner/repo dentro de la carpeta de arriba, como en ghq.", "bee548d674abd0d2": "Restablecer clonar en carpetas del host al valor predeterminado", "ef27c4211844aef9": "Posponer", - "4df30d44eb0b0728": "Reanuda automáticamente los hilos cuando se restablecen sus límites de uso. Puedes cancelar la reanudación automática en cada hilo.", + "4e8a6e262304c240": "Continúa los hilos tras un límite de uso: los hilos en Auto pasan a la siguiente suscripción con margen y los demás se reanudan cuando se restablece su límite. Puedes cancelar la reanudación automática en cada hilo.", "0769f91ca46e3003": "Pospone los hilos hasta que se restablezcan sus límites de uso. Activa la reanudación automática para que el agente continúe tras el restablecimiento.", "7c27e91e75cce7a3": "Resolver automáticamente", "cf6c5aa9b63957e6": "Resuelve un hilo cuando se fusiona su pull request. Las pull requests cerradas se siguen resolviendo automáticamente.", @@ -11451,7 +11452,7 @@ "c437e0f28c6d4a4b": "ordenar proyectos barra lateral manual creados recientes", "cb309dc06cf679ae": "posponer valores predefinidos horas más tarde esta noche mañana la próxima semana recordar", "6751449c6188912d": "uso cuota límite de uso restablecer reactivar recuperar continuar", - "0aedae6a82c09429": "uso cuota límite de uso restablecer recuperar continuar", + "5190923c9a9d6a2e": "uso cuota límite de tasa restablecer recuperar continuar auto conmutación cambiar suscripción cuenta", "85dbcfec2d41f534": "ocultar agrupar en ejecución seguimiento hilos bandeja de entrada barra lateral estante en curso", "405a2295152c9d77": "beta carpetas proyecto árbol barra lateral clásica", "de42c4690914cee4": "beta barra lateral simple boring sidebar filas de carpetas multilínea rama pull request detalles", @@ -11851,7 +11852,6 @@ "0bd938825ffcf992": "+{percent}% del total", "09c0e00d7fb55402": "Usando el crédito de restablecimiento…", "4df3ff1be768a7ab": "{name}: queda un {remaining}%", - "1b16346722b65812": "Queda un {timeLeft}% de la ventana", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Límite de 0 $", "98947080075a0e9f": "of {capacity}%", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 1dc4d182e53f..ef94c8df97dd 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -4082,6 +4082,7 @@ "66be4fb43249bbd2": "{used} tokens sur {max}", "ee3ae58c8b38a425": "{left} % restant", "ebb26f93fb83a71b": "{label} : {left} % restant", + "1b16346722b65812": "{timeLeft} % de la fenêtre restant", "728c6cc1431e76c8": "Réinitialisation dans {duration} · {time}", "e16b0b9b490c8bc7": "{label} : {value}", "ba67d0a9ff5dabf0": "L’API Presse-papiers n’est pas disponible pour copier la demande à l’administrateur.", @@ -9825,7 +9826,7 @@ "6fc9e5e722cf3c73": "Les clones vont dans github.com/owner/repo sous le dossier ci-dessus, comme ghq.", "bee548d674abd0d2": "Réinitialiser le clonage dans les dossiers de l’hôte à la valeur par défaut", "ef27c4211844aef9": "Report", - "4df30d44eb0b0728": "Reprend automatiquement les fils quand leurs limites d’utilisation sont réinitialisées. Vous pouvez annuler la reprise automatique dans chaque fil.", + "4e8a6e262304c240": "Poursuivre les fils après une limite d’utilisation : les fils en Auto passent à l’abonnement suivant qui a de la marge, les autres reprennent quand leur limite est réinitialisée. Vous pouvez annuler la reprise automatique dans chaque fil.", "0769f91ca46e3003": "Reporte les fils jusqu’à la réinitialisation de leurs limites d’utilisation. Activez la reprise automatique pour que l’agent continue après la réinitialisation.", "7c27e91e75cce7a3": "Clôture automatique", "cf6c5aa9b63957e6": "Clôt un fil quand sa pull request est fusionnée. Les pull requests fermées sont toujours closes automatiquement.", @@ -11456,7 +11457,7 @@ "c437e0f28c6d4a4b": "trier projets barre latérale manuel créés récents", "cb309dc06cf679ae": "reporter préréglages heures plus tard ce soir demain semaine prochaine rappel", "6751449c6188912d": "utilisation quota limite de débit réinitialisation réveil récupérer continuer", - "0aedae6a82c09429": "utilisation quota limite de débit réinitialisation récupérer continuer", + "5190923c9a9d6a2e": "utilisation quota limite de débit réinitialiser récupérer continuer auto basculement changer abonnement compte", "85dbcfec2d41f534": "masquer regrouper en cours surveillance fils boîte de réception barre latérale étagère", "405a2295152c9d77": "bêta dossiers arborescence de projets barre latérale classique", "de42c4690914cee4": "bêta barre latérale classique lignes de dossier multiligne branche détails pull request", @@ -11856,7 +11857,6 @@ "0bd938825ffcf992": "+{percent} % du quota", "09c0e00d7fb55402": "Utilisation du crédit de réinitialisation…", "4df3ff1be768a7ab": "{name} : {remaining} % restant", - "1b16346722b65812": "{timeLeft} % de la fenêtre restant", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Plafond de 0 $", "98947080075a0e9f": "of {capacity}%", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 1ef930607954..397f70ae9a9a 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -4072,6 +4072,7 @@ "66be4fb43249bbd2": "{used} / {max} トークン", "ee3ae58c8b38a425": "残り {left}%", "ebb26f93fb83a71b": "{label}: 残り {left}%", + "1b16346722b65812": "期間の残り {timeLeft}%", "728c6cc1431e76c8": "{duration} 後にリセット · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "管理者へのリクエストをコピーする際にクリップボード API を利用できませんでした。", @@ -9777,7 +9778,7 @@ "6fc9e5e722cf3c73": "ghq と同様に、上のフォルダーの下の github.com/owner/repo にクローンします。", "bee548d674abd0d2": "「ホスト別フォルダーにクローン」をデフォルトにリセット", "ef27c4211844aef9": "スヌーズ", - "4df30d44eb0b0728": "使用量の上限がリセットされたら、スレッドを自動的に再開します。自動再開は各スレッドでキャンセルできます。", + "4e8a6e262304c240": "使用量の上限に達したスレッドを続行します。Auto のスレッドは余裕のある次のサブスクリプションに移り、それ以外のスレッドは上限のリセット時に再開します。自動再開は各スレッドでキャンセルできます。", "0769f91ca46e3003": "使用量の上限がリセットされるまでスレッドをスヌーズします。リセット後にエージェントを続行するには、自動再開を有効にしてください。", "7c27e91e75cce7a3": "自動で対応済みにする", "cf6c5aa9b63957e6": "プルリクエストがマージされたらスレッドを対応済みにします。クローズされたプルリクエストは引き続き自動的に対応済みになります。", @@ -11406,7 +11407,7 @@ "c437e0f28c6d4a4b": "並べ替え プロジェクト サイドバー 手動 作成日 最近 sort", "cb309dc06cf679ae": "スヌーズ プリセット 時刻 後で 今夜 明日 来週 リマインド snooze", "6751449c6188912d": "使用量 クォータ レート制限 リセット 再開 復旧 続行 usage limit", - "0aedae6a82c09429": "使用量 クォータ レート制限 リセット 復旧 続行 usage limit", + "5190923c9a9d6a2e": "使用量 クォータ レート制限 リセット 復旧 続行 auto フェイルオーバー 切り替え サブスクリプション アカウント", "85dbcfec2d41f534": "非表示 折りたたみ 実行中 監視中 スレッド 受信トレイ サイドバー 棚 作業中 working", "405a2295152c9d77": "ベータ フォルダー プロジェクト ツリー クラシック サイドバー beta folders", "de42c4690914cee4": "ベータ シンプルなサイドバー フォルダー 行 複数行 ブランチ プルリクエスト 詳細 beta boring sidebar", @@ -11806,7 +11807,6 @@ "0bd938825ffcf992": "プールの +{percent}%", "09c0e00d7fb55402": "リセットクレジットを使用しています…", "4df3ff1be768a7ab": "{name}: 残り {remaining}%", - "1b16346722b65812": "期間の残り {timeLeft}%", "7aaaff1c6484f25c": "セグメント", "8bcab2ef61de6518": "上限 $0", "98947080075a0e9f": "of {capacity}%", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 33491309b1c4..955f22e321c1 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -4069,6 +4069,7 @@ "66be4fb43249bbd2": "토큰 {max}개 중 {used}개", "ee3ae58c8b38a425": "{left}% 남음", "ebb26f93fb83a71b": "{label}: {left}% 남음", + "1b16346722b65812": "기간 {timeLeft}% 남음", "728c6cc1431e76c8": "{duration} 후 초기화 · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "관리자 요청을 복사하는 중 클립보드 API를 사용할 수 없습니다.", @@ -9780,7 +9781,7 @@ "6fc9e5e722cf3c73": "ghq처럼 위 폴더 아래 github.com/owner/repo에 복제합니다.", "bee548d674abd0d2": "호스트 폴더로 복제 기본값으로 재설정", "ef27c4211844aef9": "다시 알림", - "4df30d44eb0b0728": "사용량 한도가 초기화되면 스레드를 자동으로 재개합니다. 각 스레드에서 자동 재개를 취소할 수 있습니다.", + "4e8a6e262304c240": "사용량 한도 후 스레드를 계속합니다. Auto 스레드는 여유가 있는 다음 구독으로 옮겨지고, 다른 스레드는 한도가 초기화되면 다시 시작됩니다. 각 스레드에서 자동 재개를 취소할 수 있습니다.", "0769f91ca46e3003": "사용량 한도가 초기화될 때까지 스레드를 미룹니다. 초기화 후 에이전트를 계속하려면 자동 재개를 사용하세요.", "7c27e91e75cce7a3": "자동 정리", "cf6c5aa9b63957e6": "풀 리퀘스트가 병합되면 스레드를 정리합니다. 닫힌 풀 리퀘스트는 계속 자동으로 정리됩니다.", @@ -11403,7 +11404,7 @@ "c437e0f28c6d4a4b": "프로젝트 정렬 사이드바 수동 생성일 최근", "cb309dc06cf679ae": "다시 알림 프리셋 시간 나중에 오늘 밤 내일 다음 주 알림", "6751449c6188912d": "사용량 할당량 속도 제한 초기화 깨우기 복구 계속", - "0aedae6a82c09429": "사용량 할당량 속도 제한 초기화 복구 계속", + "5190923c9a9d6a2e": "사용량 할당량 속도 제한 초기화 복구 계속 auto 장애 조치 전환 구독 계정", "85dbcfec2d41f534": "숨기기 접기 실행 중 모니터링 스레드 인박스 사이드바 선반 작업 중", "405a2295152c9d77": "베타 폴더 프로젝트 트리 클래식 사이드바", "de42c4690914cee4": "베타 단순 사이드바 폴더 행 여러 줄 브랜치 풀 리퀘스트 세부 정보", @@ -11803,7 +11804,6 @@ "0bd938825ffcf992": "풀의 +{percent}%", "09c0e00d7fb55402": "초기화 크레딧 사용 중…", "4df3ff1be768a7ab": "{name}: {remaining}% 남음", - "1b16346722b65812": "기간 {timeLeft}% 남음", "7aaaff1c6484f25c": "구간", "8bcab2ef61de6518": "$0 한도", "98947080075a0e9f": "of {capacity}%", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 6f1202c25d32..40cffbff9407 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -4081,6 +4081,7 @@ "66be4fb43249bbd2": "{used} de {max} tokens", "ee3ae58c8b38a425": "{left}% restante", "ebb26f93fb83a71b": "{label}: {left}% restante", + "1b16346722b65812": "{timeLeft}% da janela restante", "728c6cc1431e76c8": "Renova em {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "A API da área de transferência não está disponível ao copiar o pedido para o administrador.", @@ -9824,7 +9825,7 @@ "6fc9e5e722cf3c73": "Os clones vão para github.com/owner/repo dentro da pasta acima, como no ghq.", "bee548d674abd0d2": "Redefinir a clonagem em pastas por host para o padrão", "ef27c4211844aef9": "Adiar", - "4df30d44eb0b0728": "Retoma as threads automaticamente quando os limites de uso delas forem redefinidos. Você pode cancelar a retomada automática em cada thread.", + "4e8a6e262304c240": "Continue as threads após um limite de uso: threads no Auto passam para a próxima assinatura com margem, e as outras são retomadas quando o limite delas é redefinido. Você pode cancelar a retomada automática em cada thread.", "0769f91ca46e3003": "Adia as threads até os limites de uso delas serem redefinidos. Ative a retomada automática para continuar o agente após a redefinição.", "7c27e91e75cce7a3": "Concluir automaticamente", "cf6c5aa9b63957e6": "Conclui uma thread quando o pull request dela é mesclado. Pull requests fechados continuam sendo concluídos automaticamente.", @@ -11455,7 +11456,7 @@ "c437e0f28c6d4a4b": "ordenar projetos barra lateral manual criação recentes", "cb309dc06cf679ae": "adiar predefinições horários mais tarde hoje à noite amanhã próxima semana lembrar", "6751449c6188912d": "uso cota limite de taxa redefinir despertar recuperar continuar", - "0aedae6a82c09429": "uso cota limite de taxa redefinir recuperar continuar", + "5190923c9a9d6a2e": "uso cota limite de taxa redefinir recuperar continuar auto failover trocar assinatura conta", "85dbcfec2d41f534": "ocultar agrupar em execução monitoramento threads caixa de entrada barra lateral prateleira", "405a2295152c9d77": "beta pastas projeto árvore barra lateral clássica", "de42c4690914cee4": "beta barra lateral sem graça pasta linhas várias linhas branch pull request detalhes", @@ -11855,7 +11856,6 @@ "0bd938825ffcf992": "+{percent}% do total", "09c0e00d7fb55402": "Usando crédito de redefinição…", "4df3ff1be768a7ab": "{name}: {remaining}% restante", - "1b16346722b65812": "{timeLeft}% da janela restante", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Limite de $0", "98947080075a0e9f": "of {capacity}%", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 54501fea12e0..6e75617dca1c 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -4081,6 +4081,7 @@ "66be4fb43249bbd2": "{used} из {max} токенов", "ee3ae58c8b38a425": "Осталось {left}%", "ebb26f93fb83a71b": "{label}: осталось {left}%", + "1b16346722b65812": "От окна осталось {timeLeft}%", "728c6cc1431e76c8": "Сброс через {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "API буфера обмена недоступен при копировании запроса администратору.", @@ -9827,7 +9828,7 @@ "6fc9e5e722cf3c73": "Клоны попадают в github.com/owner/repo внутри папки выше, как в ghq.", "bee548d674abd0d2": "Сбросить клонирование в папки хоста к значению по умолчанию", "ef27c4211844aef9": "Отложить", - "4df30d44eb0b0728": "Автоматически возобновлять треды при сбросе лимитов использования. Автовозобновление можно отменить в каждом треде.", + "4e8a6e262304c240": "Продолжать треды после лимита использования: треды на Auto переходят на следующую подписку с запасом, остальные возобновляются после сброса лимита. Автовозобновление можно отменить в каждом треде.", "0769f91ca46e3003": "Откладывать треды до сброса лимитов использования. Включите автовозобновление, чтобы агент продолжил после сброса.", "7c27e91e75cce7a3": "Авторазбор", "cf6c5aa9b63957e6": "Отмечать тред разобранным при слиянии его пул-реквеста. Треды с закрытыми пул-реквестами по-прежнему разбираются автоматически.", @@ -11456,7 +11457,7 @@ "c437e0f28c6d4a4b": "сортировка проекты боковая панель вручную создание недавние", "cb309dc06cf679ae": "отложить пресеты время позже вечером завтра на следующей неделе напомнить", "6751449c6188912d": "использование квота лимит запросов сброс пробуждение восстановить продолжить", - "0aedae6a82c09429": "использование квота лимит запросов сброс восстановить продолжить", + "5190923c9a9d6a2e": "использование квота лимит запросов сброс восстановить продолжить auto переключение подписка аккаунт", "85dbcfec2d41f534": "скрыть свернуть выполняющиеся отслеживающие треды входящие боковая панель полка в работе", "405a2295152c9d77": "бета папки дерево проектов классическая боковая панель", "de42c4690914cee4": "бета простая боковая панель строки папок многострочные ветка пул-реквест подробности", @@ -11856,7 +11857,6 @@ "0bd938825ffcf992": "+{percent}% пула", "09c0e00d7fb55402": "Использование кредита на сброс…", "4df3ff1be768a7ab": "{name}: осталось {remaining}%", - "1b16346722b65812": "От окна осталось {timeLeft}%", "7aaaff1c6484f25c": "Сегмент", "8bcab2ef61de6518": "Лимит $0", "98947080075a0e9f": "of {capacity}%", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index f7a0b7f69cd9..b6a866ecfac1 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -4082,6 +4082,7 @@ "66be4fb43249bbd2": "{used} av {max} token", "ee3ae58c8b38a425": "{left} % kvar", "ebb26f93fb83a71b": "{label}: {left} % kvar", + "1b16346722b65812": "{timeLeft} % av fönstret kvar", "728c6cc1431e76c8": "Återställs om {duration} · {time}", "e16b0b9b490c8bc7": "{label}: {value}", "ba67d0a9ff5dabf0": "Urklipps-API:t är inte tillgängligt vid kopiering av administratörsbegäran.", @@ -9833,7 +9834,7 @@ "6fc9e5e722cf3c73": "Kloner hamnar i github.com/owner/repo under mappen ovan, som ghq.", "bee548d674abd0d2": "Återställ kloning till värdmappar till standard", "ef27c4211844aef9": "Snooza", - "4df30d44eb0b0728": "Återuppta trådar automatiskt när deras användningsgränser återställs. Du kan avbryta automatisk återupptagning i varje tråd.", + "4e8a6e262304c240": "Fortsätt trådar efter en användningsgräns: trådar på Auto flyttas till nästa prenumeration med utrymme, andra trådar återupptas när gränsen återställs. Du kan avbryta automatisk återupptagning i varje tråd.", "0769f91ca46e3003": "Snooza trådar tills deras användningsgränser återställs. Aktivera automatisk återupptagning för att fortsätta agenten efter återställningen.", "7c27e91e75cce7a3": "Markera som klar automatiskt", "cf6c5aa9b63957e6": "Markera en tråd som klar när dess pull request mergas. Stängda pull requests markeras fortfarande som klara automatiskt.", @@ -11464,7 +11465,7 @@ "c437e0f28c6d4a4b": "sortera projekt sidofält manuellt skapade senaste", "cb309dc06cf679ae": "snooza förval tider senare i kväll i morgon nästa vecka påminn snooze", "6751449c6188912d": "användning kvot hastighetsbegränsning återställning vakna återhämta fortsätt", - "0aedae6a82c09429": "användning kvot hastighetsbegränsning återställning återhämta fortsätt", + "5190923c9a9d6a2e": "användning kvot hastighetsgräns återställ återhämta fortsätt auto failover byt prenumeration konto", "85dbcfec2d41f534": "dölj fäll ihop pågående bevakning trådar inkorg sidofält hylla", "405a2295152c9d77": "beta mappar projektträd klassiskt sidofält", "de42c4690914cee4": "beta enkelt sidofält mapprader flera rader gren pull request detaljer", @@ -11864,7 +11865,6 @@ "0bd938825ffcf992": "+{percent} % av poolen", "09c0e00d7fb55402": "Använder återställningskredit…", "4df3ff1be768a7ab": "{name}: {remaining} % kvar", - "1b16346722b65812": "{timeLeft} % av fönstret kvar", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Tak på 0 $", "98947080075a0e9f": "of {capacity}%", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 555e167b5e00..23f0f0eb372d 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -4088,6 +4088,7 @@ "66be4fb43249bbd2": "{used} / {max} token", "ee3ae58c8b38a425": "剩余 {left}%", "ebb26f93fb83a71b": "{label}:剩余 {left}%", + "1b16346722b65812": "窗口剩余 {timeLeft}%", "728c6cc1431e76c8": "{duration} 后重置 · {time}", "e16b0b9b490c8bc7": "{label}:{value}", "ba67d0a9ff5dabf0": "复制管理员请求时剪贴板 API 不可用。", @@ -9840,7 +9841,7 @@ "6fc9e5e722cf3c73": "克隆的仓库会放到上方文件夹下的 github.com/owner/repo 中,与 ghq 相同。", "bee548d674abd0d2": "重置克隆到主机文件夹为默认值", "ef27c4211844aef9": "暂缓", - "4df30d44eb0b0728": "用量限制重置后自动继续会话。你可以在每个会话中取消自动继续。", + "4e8a6e262304c240": "达到用量限制后继续会话:使用 Auto 的会话会切换到下一个仍有余量的订阅,其他会话会在限制重置后继续。你可以在每个会话中取消自动继续。", "0769f91ca46e3003": "将会话暂缓到用量限制重置。开启自动继续后,智能体会在重置后接着工作。", "7c27e91e75cce7a3": "自动收尾", "cf6c5aa9b63957e6": "Pull request 合并后收尾会话。已关闭的 pull request 仍会自动收尾。", @@ -11480,7 +11481,7 @@ "c437e0f28c6d4a4b": "排序 项目 侧边栏 手动 创建 最近", "cb309dc06cf679ae": "暂缓 预设 时间 稍后 今晚 明天 下周 提醒", "6751449c6188912d": "用量 配额 速率限制 重置 唤醒 恢复 继续", - "0aedae6a82c09429": "用量 配额 速率限制 重置 恢复 继续", + "5190923c9a9d6a2e": "用量 配额 速率限制 重置 恢复 继续 auto 故障转移 切换 订阅 账户", "85dbcfec2d41f534": "隐藏 收起 运行中 监控中 会话 收件箱 侧边栏 分组", "405a2295152c9d77": "测试版 文件夹 项目 树 经典 侧边栏", "de42c4690914cee4": "测试版 简洁侧边栏 文件夹 行 多行 分支 PR 详情", @@ -11881,7 +11882,6 @@ "0bd938825ffcf992": "+{percent}%(按共享池总额度计算)", "09c0e00d7fb55402": "正在使用重置额度…", "4df3ff1be768a7ab": "{name}:剩余 {remaining}%", - "1b16346722b65812": "窗口剩余 {timeLeft}%", "7aaaff1c6484f25c": "分段", "8bcab2ef61de6518": "上限 $0", "98947080075a0e9f": "of {capacity}%", diff --git a/docs/progress.md b/docs/progress.md index 794c022123e2..0174d54b3f5d 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -179,3 +179,11 @@ - Review: one read-only review on the second Claude account found no bugs. Taken: the OpenCode comment. Left: upstream's Resume test table now expects Resume in every row; keeping upstream's rows keeps later syncs simple. - Switching the hubs: migration `100_TurnStartReadIndexes` adds three partial indexes. The Node pins did not change. - Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Not checked in a browser: the Resume button on a stopped Grok run. + +## 2026-11-19: "Resume after usage limits" says it also moves Auto threads + +- What: the description of **Resume after usage limits** (web Settings → Threads, mobile thread settings) now reads "Continue threads after a usage limit: threads on Auto move to the next subscription with room, other threads resume when their limit resets. You can cancel auto-resume in each thread." Settings search also matches "auto failover switch subscription account". `docs/user/thread-sidebar.md` says the same switch gates the Auto move. Translated in all 9 non-English web and mobile catalogs. No server change: `AutoFailoverService` still sends nothing while the switch is off. +- Why: the switch was off on both hubs. When Claude A hit its 5-hour limit, Auto benched it but never moved the thread, which sat idle for 50 minutes. The old text only spoke of resuming at reset. +- Numbers: `vp run i18n:check` pass; `vp run check:changed`: format, lint, knip, typecheck (3 packages), 2 test files and react compiler pass. +- Real run: dev server on a seeded worktree `.t3`; Settings → Threads shows the new text, and searching "failover" lists the switch. +- Next: Tomáš merges the PR. diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 38dd4684723f..0167ef21c860 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -258,6 +258,8 @@ the continuation finishes. If the queue was held by a restart, resume it then. When the provider reports a reset time, choose **Resume at reset** to schedule a continuation. You can cancel it from the thread. Enable **Resume after usage limits** in **Settings → Threads** to schedule limit stops by default. +The same switch lets a thread on Auto move to the next subscription with room +when it hits a limit; with it off, the thread stays stopped. The environment must be running when the reset arrives; it resumes overdue continuations after a restart. Stopping the thread, sending a new message, archiving, or settling it prevents a pending continuation from starting. From af2c05a78dfa123f262b20f4d3afe0d4939afdc5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 21:11:08 +0100 Subject: [PATCH 109/230] fix(web): translate the fork's Usage strings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The 17 strings the fork added to Usage → Limits (the pooled view and its chart) were added before the 2026-11-18 upstream sync and stayed English in all nine non-English web catalogs. Translate them, following each catalog's existing words for pool and reset. Mobile has none of these keys. --- apps/web/src/i18n/translations/de.json | 32 ++++++++++----------- apps/web/src/i18n/translations/es.json | 34 +++++++++++------------ apps/web/src/i18n/translations/fr.json | 34 +++++++++++------------ apps/web/src/i18n/translations/ja.json | 34 +++++++++++------------ apps/web/src/i18n/translations/ko.json | 34 +++++++++++------------ apps/web/src/i18n/translations/pt-BR.json | 34 +++++++++++------------ apps/web/src/i18n/translations/ru.json | 34 +++++++++++------------ apps/web/src/i18n/translations/sv.json | 34 +++++++++++------------ apps/web/src/i18n/translations/zh.json | 34 +++++++++++------------ docs/progress.md | 8 ++++++ 10 files changed, 160 insertions(+), 152 deletions(-) diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 894f421428da..3a03d42e9074 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -11861,20 +11861,20 @@ "1b16346722b65812": "{timeLeft} % des Zeitfensters übrig", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "0-$-Limit", - "98947080075a0e9f": "of {capacity}%", - "319d956d8dc9626e": "Pool empty", - "7edac2c4173fee09": "Not by {date}", - "649af7801ecb5d6c": "Empty now", - "7b3b4057463829e0": "First empty", - "0cc4fd1cf5ac9270": "now", + "98947080075a0e9f": "von {capacity} %", + "319d956d8dc9626e": "Kontingent leer", + "7edac2c4173fee09": "Nicht bis {date}", + "649af7801ecb5d6c": "Jetzt leer", + "7b3b4057463829e0": "Zuerst leer", + "0cc4fd1cf5ac9270": "jetzt", "ade42d3734d25cb8": "in {duration}", - "94fcce9e98d053ad": "None", - "e7c90232ad94f3ca": "Next reset", - "22f3ae62c7a65e0f": "Burn, last 3h", - "737171d0d80cb0d0": "Burn, window avg", + "94fcce9e98d053ad": "Keins", + "e7c90232ad94f3ca": "Nächstes Zurücksetzen", + "22f3ae62c7a65e0f": "Verbrauch, letzte 3 h", + "737171d0d80cb0d0": "Verbrauch, Fensterschnitt", "a16b48709357a5a7": "Nutzung verwalten", - "e20b23cc4eee52c1": "Reset advice:", - "aca138d5adaa5f69": "Subscriptions", + "e20b23cc4eee52c1": "Reset-Empfehlung:", + "aca138d5adaa5f69": "Abos", "8bd6f07136317c8f": "Kein Anbieter in den ausgewählten Umgebungen meldet Abo-Limits.", "87f5d0c61b335f38": "Nutzung in ChatGPT mit deinem verbundenen Konto ansehen.", "5b4c71b36b979e80": "Kosten", @@ -11965,10 +11965,10 @@ "b11af3f3da3d494e": "Die Summen sind unvollständig, während ausgewählte Umgebungen scannen.", "8062808b87ce6032": "Modellpreise", "cf5409d12fc3f53b": "Alle Anbieter", - "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", - "b05ed15d19d4a485": "Empty {time}", - "56fb015730a158bc": "projected", - "fc3a1241f943cae6": "Now", + "498a69c10b2ed2d9": "{label}: verbleibendes gemeinsames Kontingent, erfasst und prognostiziert", + "b05ed15d19d4a485": "Leer {time}", + "56fb015730a158bc": "prognostiziert", + "fc3a1241f943cae6": "Jetzt", "55e99aaf3d0e6af4": "Preise nicht geladen", "ed447281261f2d0e": "Nur Lesezugriff", "67633defded66bf7": "Gib eine Modell-ID ein.", diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index e2b4e8cf6f2c..5d301d9c32e0 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -11854,20 +11854,20 @@ "1b16346722b65812": "Queda un {timeLeft}% de la ventana", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Límite de 0 $", - "98947080075a0e9f": "of {capacity}%", - "319d956d8dc9626e": "Pool empty", - "7edac2c4173fee09": "Not by {date}", - "649af7801ecb5d6c": "Empty now", - "7b3b4057463829e0": "First empty", - "0cc4fd1cf5ac9270": "now", - "ade42d3734d25cb8": "in {duration}", - "94fcce9e98d053ad": "None", - "e7c90232ad94f3ca": "Next reset", - "22f3ae62c7a65e0f": "Burn, last 3h", - "737171d0d80cb0d0": "Burn, window avg", + "98947080075a0e9f": "de {capacity}%", + "319d956d8dc9626e": "Total agotado", + "7edac2c4173fee09": "No antes del {date}", + "649af7801ecb5d6c": "Agotado ahora", + "7b3b4057463829e0": "Primero en agotarse", + "0cc4fd1cf5ac9270": "ahora", + "ade42d3734d25cb8": "en {duration}", + "94fcce9e98d053ad": "Ninguna", + "e7c90232ad94f3ca": "Próximo restablecimiento", + "22f3ae62c7a65e0f": "Consumo, últimas 3 h", + "737171d0d80cb0d0": "Consumo, media de la ventana", "a16b48709357a5a7": "Gestionar uso", - "e20b23cc4eee52c1": "Reset advice:", - "aca138d5adaa5f69": "Subscriptions", + "e20b23cc4eee52c1": "Consejo de restablecimiento:", + "aca138d5adaa5f69": "Suscripciones", "8bd6f07136317c8f": "Ningún proveedor de los entornos seleccionados informa de límites de suscripción.", "87f5d0c61b335f38": "Consulta el uso en ChatGPT con tu cuenta conectada.", "5b4c71b36b979e80": "Coste", @@ -11958,10 +11958,10 @@ "b11af3f3da3d494e": "Los totales son parciales mientras se escanean los entornos seleccionados.", "8062808b87ce6032": "Precios de modelos", "cf5409d12fc3f53b": "Todos los proveedores", - "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", - "b05ed15d19d4a485": "Empty {time}", - "56fb015730a158bc": "projected", - "fc3a1241f943cae6": "Now", + "498a69c10b2ed2d9": "{label}: cuota conjunta restante, registrada y prevista", + "b05ed15d19d4a485": "Agotado {time}", + "56fb015730a158bc": "previsto", + "fc3a1241f943cae6": "Ahora", "55e99aaf3d0e6af4": "No se cargaron los precios", "ed447281261f2d0e": "Acceso de solo lectura", "67633defded66bf7": "Introduce un ID de modelo.", diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 1dc4d182e53f..6f69185449a8 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -11859,20 +11859,20 @@ "1b16346722b65812": "{timeLeft} % de la fenêtre restant", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Plafond de 0 $", - "98947080075a0e9f": "of {capacity}%", - "319d956d8dc9626e": "Pool empty", - "7edac2c4173fee09": "Not by {date}", - "649af7801ecb5d6c": "Empty now", - "7b3b4057463829e0": "First empty", - "0cc4fd1cf5ac9270": "now", - "ade42d3734d25cb8": "in {duration}", - "94fcce9e98d053ad": "None", - "e7c90232ad94f3ca": "Next reset", - "22f3ae62c7a65e0f": "Burn, last 3h", - "737171d0d80cb0d0": "Burn, window avg", + "98947080075a0e9f": "sur {capacity} %", + "319d956d8dc9626e": "Quota épuisé", + "7edac2c4173fee09": "Pas avant le {date}", + "649af7801ecb5d6c": "Épuisé maintenant", + "7b3b4057463829e0": "Premier épuisé", + "0cc4fd1cf5ac9270": "maintenant", + "ade42d3734d25cb8": "dans {duration}", + "94fcce9e98d053ad": "Aucun", + "e7c90232ad94f3ca": "Prochaine réinitialisation", + "22f3ae62c7a65e0f": "Consommation, 3 dernières h", + "737171d0d80cb0d0": "Consommation, moyenne de la fenêtre", "a16b48709357a5a7": "Gérer l’utilisation", - "e20b23cc4eee52c1": "Reset advice:", - "aca138d5adaa5f69": "Subscriptions", + "e20b23cc4eee52c1": "Conseil de réinitialisation :", + "aca138d5adaa5f69": "Abonnements", "8bd6f07136317c8f": "Aucun fournisseur des environnements sélectionnés ne signale de limites d’abonnement.", "87f5d0c61b335f38": "Consultez l’utilisation dans ChatGPT avec votre compte connecté.", "5b4c71b36b979e80": "Coût", @@ -11963,10 +11963,10 @@ "b11af3f3da3d494e": "Les totaux sont partiels pendant l’analyse des environnements sélectionnés.", "8062808b87ce6032": "Prix des modèles", "cf5409d12fc3f53b": "Tous les fournisseurs", - "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", - "b05ed15d19d4a485": "Empty {time}", - "56fb015730a158bc": "projected", - "fc3a1241f943cae6": "Now", + "498a69c10b2ed2d9": "{label} : quota commun restant, enregistré et prévu", + "b05ed15d19d4a485": "Épuisé {time}", + "56fb015730a158bc": "prévu", + "fc3a1241f943cae6": "Maintenant", "55e99aaf3d0e6af4": "Prix non chargés", "ed447281261f2d0e": "Accès en lecture seule", "67633defded66bf7": "Saisissez un ID de modèle.", diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index 1ef930607954..69b3696aadbb 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -11809,20 +11809,20 @@ "1b16346722b65812": "期間の残り {timeLeft}%", "7aaaff1c6484f25c": "セグメント", "8bcab2ef61de6518": "上限 $0", - "98947080075a0e9f": "of {capacity}%", - "319d956d8dc9626e": "Pool empty", - "7edac2c4173fee09": "Not by {date}", - "649af7801ecb5d6c": "Empty now", - "7b3b4057463829e0": "First empty", - "0cc4fd1cf5ac9270": "now", - "ade42d3734d25cb8": "in {duration}", - "94fcce9e98d053ad": "None", - "e7c90232ad94f3ca": "Next reset", - "22f3ae62c7a65e0f": "Burn, last 3h", - "737171d0d80cb0d0": "Burn, window avg", + "98947080075a0e9f": "/ {capacity}%", + "319d956d8dc9626e": "プールが空になる", + "7edac2c4173fee09": "{date} までは空にならない", + "649af7801ecb5d6c": "今すぐ空", + "7b3b4057463829e0": "最初に空になる", + "0cc4fd1cf5ac9270": "今", + "ade42d3734d25cb8": "{duration}後", + "94fcce9e98d053ad": "なし", + "e7c90232ad94f3ca": "次のリセット", + "22f3ae62c7a65e0f": "消費量(直近 3 時間)", + "737171d0d80cb0d0": "消費量(期間平均)", "a16b48709357a5a7": "使用量を管理", - "e20b23cc4eee52c1": "Reset advice:", - "aca138d5adaa5f69": "Subscriptions", + "e20b23cc4eee52c1": "リセットのアドバイス:", + "aca138d5adaa5f69": "サブスクリプション", "8bd6f07136317c8f": "選択した環境には、サブスクリプションの上限を報告するプロバイダーがありません。", "87f5d0c61b335f38": "接続したアカウントで ChatGPT の使用量を表示します。", "5b4c71b36b979e80": "コスト", @@ -11913,10 +11913,10 @@ "b11af3f3da3d494e": "選択した環境のスキャン中は、合計は一部のみです。", "8062808b87ce6032": "モデルの価格", "cf5409d12fc3f53b": "すべてのプロバイダー", - "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", - "b05ed15d19d4a485": "Empty {time}", - "56fb015730a158bc": "projected", - "fc3a1241f943cae6": "Now", + "498a69c10b2ed2d9": "{label}: プールの残りクォータ(記録と予測)", + "b05ed15d19d4a485": "{time} に空", + "56fb015730a158bc": "予測", + "fc3a1241f943cae6": "現在", "55e99aaf3d0e6af4": "価格が読み込まれていません", "ed447281261f2d0e": "読み取り専用アクセス", "67633defded66bf7": "モデル ID を入力してください。", diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 33491309b1c4..2fdc812a78e0 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -11806,20 +11806,20 @@ "1b16346722b65812": "기간 {timeLeft}% 남음", "7aaaff1c6484f25c": "구간", "8bcab2ef61de6518": "$0 한도", - "98947080075a0e9f": "of {capacity}%", - "319d956d8dc9626e": "Pool empty", - "7edac2c4173fee09": "Not by {date}", - "649af7801ecb5d6c": "Empty now", - "7b3b4057463829e0": "First empty", - "0cc4fd1cf5ac9270": "now", - "ade42d3734d25cb8": "in {duration}", - "94fcce9e98d053ad": "None", - "e7c90232ad94f3ca": "Next reset", - "22f3ae62c7a65e0f": "Burn, last 3h", - "737171d0d80cb0d0": "Burn, window avg", + "98947080075a0e9f": "/ {capacity}%", + "319d956d8dc9626e": "풀 소진", + "7edac2c4173fee09": "{date}까지 소진 안 됨", + "649af7801ecb5d6c": "지금 소진", + "7b3b4057463829e0": "가장 먼저 소진", + "0cc4fd1cf5ac9270": "지금", + "ade42d3734d25cb8": "{duration} 후", + "94fcce9e98d053ad": "없음", + "e7c90232ad94f3ca": "다음 초기화", + "22f3ae62c7a65e0f": "소비량, 최근 3시간", + "737171d0d80cb0d0": "소비량, 기간 평균", "a16b48709357a5a7": "사용량 관리", - "e20b23cc4eee52c1": "Reset advice:", - "aca138d5adaa5f69": "Subscriptions", + "e20b23cc4eee52c1": "초기화 조언:", + "aca138d5adaa5f69": "구독", "8bd6f07136317c8f": "선택한 환경에 구독 한도를 보고하는 제공자가 없습니다.", "87f5d0c61b335f38": "연결된 계정으로 ChatGPT에서 사용량을 확인하세요.", "5b4c71b36b979e80": "비용", @@ -11910,10 +11910,10 @@ "b11af3f3da3d494e": "선택한 환경을 스캔하는 동안에는 합계가 일부만 표시됩니다.", "8062808b87ce6032": "모델 가격", "cf5409d12fc3f53b": "모든 제공자", - "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", - "b05ed15d19d4a485": "Empty {time}", - "56fb015730a158bc": "projected", - "fc3a1241f943cae6": "Now", + "498a69c10b2ed2d9": "{label}: 풀의 남은 할당량, 기록 및 예측", + "b05ed15d19d4a485": "{time} 소진", + "56fb015730a158bc": "예측", + "fc3a1241f943cae6": "현재", "55e99aaf3d0e6af4": "가격을 불러오지 않음", "ed447281261f2d0e": "읽기 전용 액세스", "67633defded66bf7": "모델 ID를 입력하세요.", diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 6f1202c25d32..ec46a1c4b0e6 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -11858,20 +11858,20 @@ "1b16346722b65812": "{timeLeft}% da janela restante", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Limite de $0", - "98947080075a0e9f": "of {capacity}%", - "319d956d8dc9626e": "Pool empty", - "7edac2c4173fee09": "Not by {date}", - "649af7801ecb5d6c": "Empty now", - "7b3b4057463829e0": "First empty", - "0cc4fd1cf5ac9270": "now", - "ade42d3734d25cb8": "in {duration}", - "94fcce9e98d053ad": "None", - "e7c90232ad94f3ca": "Next reset", - "22f3ae62c7a65e0f": "Burn, last 3h", - "737171d0d80cb0d0": "Burn, window avg", + "98947080075a0e9f": "de {capacity}%", + "319d956d8dc9626e": "Total esgotado", + "7edac2c4173fee09": "Não antes de {date}", + "649af7801ecb5d6c": "Esgotado agora", + "7b3b4057463829e0": "Primeiro a esgotar", + "0cc4fd1cf5ac9270": "agora", + "ade42d3734d25cb8": "em {duration}", + "94fcce9e98d053ad": "Nenhuma", + "e7c90232ad94f3ca": "Próxima renovação", + "22f3ae62c7a65e0f": "Consumo, últimas 3 h", + "737171d0d80cb0d0": "Consumo, média da janela", "a16b48709357a5a7": "Gerenciar uso", - "e20b23cc4eee52c1": "Reset advice:", - "aca138d5adaa5f69": "Subscriptions", + "e20b23cc4eee52c1": "Dica de renovação:", + "aca138d5adaa5f69": "Assinaturas", "8bd6f07136317c8f": "Nenhum provedor nos ambientes selecionados informa limites de assinatura.", "87f5d0c61b335f38": "Veja o uso no ChatGPT com sua conta conectada.", "5b4c71b36b979e80": "Custo", @@ -11962,10 +11962,10 @@ "b11af3f3da3d494e": "Os totais são parciais enquanto os ambientes selecionados são verificados.", "8062808b87ce6032": "Preços dos modelos", "cf5409d12fc3f53b": "Todos os provedores", - "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", - "b05ed15d19d4a485": "Empty {time}", - "56fb015730a158bc": "projected", - "fc3a1241f943cae6": "Now", + "498a69c10b2ed2d9": "{label}: cota conjunta restante, registrada e prevista", + "b05ed15d19d4a485": "Esgota {time}", + "56fb015730a158bc": "previsto", + "fc3a1241f943cae6": "Agora", "55e99aaf3d0e6af4": "Preços não carregados", "ed447281261f2d0e": "Acesso somente leitura", "67633defded66bf7": "Informe o ID de um modelo.", diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 54501fea12e0..463d8f0e369f 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -11859,20 +11859,20 @@ "1b16346722b65812": "От окна осталось {timeLeft}%", "7aaaff1c6484f25c": "Сегмент", "8bcab2ef61de6518": "Лимит $0", - "98947080075a0e9f": "of {capacity}%", - "319d956d8dc9626e": "Pool empty", - "7edac2c4173fee09": "Not by {date}", - "649af7801ecb5d6c": "Empty now", - "7b3b4057463829e0": "First empty", - "0cc4fd1cf5ac9270": "now", - "ade42d3734d25cb8": "in {duration}", - "94fcce9e98d053ad": "None", - "e7c90232ad94f3ca": "Next reset", - "22f3ae62c7a65e0f": "Burn, last 3h", - "737171d0d80cb0d0": "Burn, window avg", + "98947080075a0e9f": "из {capacity}%", + "319d956d8dc9626e": "Пул исчерпан", + "7edac2c4173fee09": "Не раньше {date}", + "649af7801ecb5d6c": "Исчерпан сейчас", + "7b3b4057463829e0": "Первым исчерпается", + "0cc4fd1cf5ac9270": "сейчас", + "ade42d3734d25cb8": "через {duration}", + "94fcce9e98d053ad": "Нет", + "e7c90232ad94f3ca": "Следующий сброс", + "22f3ae62c7a65e0f": "Расход, последние 3 ч", + "737171d0d80cb0d0": "Расход, среднее за окно", "a16b48709357a5a7": "Управление использованием", - "e20b23cc4eee52c1": "Reset advice:", - "aca138d5adaa5f69": "Subscriptions", + "e20b23cc4eee52c1": "Совет по сбросу:", + "aca138d5adaa5f69": "Подписки", "8bd6f07136317c8f": "Ни один провайдер в выбранных окружениях не сообщает лимиты подписки.", "87f5d0c61b335f38": "Смотрите использование в ChatGPT через подключённый аккаунт.", "5b4c71b36b979e80": "Стоимость", @@ -11963,10 +11963,10 @@ "b11af3f3da3d494e": "Итоги неполные, пока выбранные окружения сканируются.", "8062808b87ce6032": "Цены моделей", "cf5409d12fc3f53b": "Все провайдеры", - "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", - "b05ed15d19d4a485": "Empty {time}", - "56fb015730a158bc": "projected", - "fc3a1241f943cae6": "Now", + "498a69c10b2ed2d9": "{label}: остаток общей квоты, записанный и прогнозный", + "b05ed15d19d4a485": "Исчерпан {time}", + "56fb015730a158bc": "прогноз", + "fc3a1241f943cae6": "Сейчас", "55e99aaf3d0e6af4": "Цены не загружены", "ed447281261f2d0e": "Доступ только для чтения", "67633defded66bf7": "Введите ID модели.", diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index f7a0b7f69cd9..dd87c85d7902 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -11867,20 +11867,20 @@ "1b16346722b65812": "{timeLeft} % av fönstret kvar", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Tak på 0 $", - "98947080075a0e9f": "of {capacity}%", - "319d956d8dc9626e": "Pool empty", - "7edac2c4173fee09": "Not by {date}", - "649af7801ecb5d6c": "Empty now", - "7b3b4057463829e0": "First empty", - "0cc4fd1cf5ac9270": "now", - "ade42d3734d25cb8": "in {duration}", - "94fcce9e98d053ad": "None", - "e7c90232ad94f3ca": "Next reset", - "22f3ae62c7a65e0f": "Burn, last 3h", - "737171d0d80cb0d0": "Burn, window avg", + "98947080075a0e9f": "av {capacity} %", + "319d956d8dc9626e": "Poolen tom", + "7edac2c4173fee09": "Inte före {date}", + "649af7801ecb5d6c": "Tom nu", + "7b3b4057463829e0": "Först tom", + "0cc4fd1cf5ac9270": "nu", + "ade42d3734d25cb8": "om {duration}", + "94fcce9e98d053ad": "Inget", + "e7c90232ad94f3ca": "Nästa återställning", + "22f3ae62c7a65e0f": "Förbrukning, senaste 3 h", + "737171d0d80cb0d0": "Förbrukning, fönstersnitt", "a16b48709357a5a7": "Hantera användning", - "e20b23cc4eee52c1": "Reset advice:", - "aca138d5adaa5f69": "Subscriptions", + "e20b23cc4eee52c1": "Återställningsråd:", + "aca138d5adaa5f69": "Prenumerationer", "8bd6f07136317c8f": "Ingen leverantör i de valda miljöerna rapporterar abonnemangsgränser.", "87f5d0c61b335f38": "Visa användning i ChatGPT med ditt anslutna konto.", "5b4c71b36b979e80": "Kostnad", @@ -11971,10 +11971,10 @@ "b11af3f3da3d494e": "Summorna är ofullständiga medan valda miljöer genomsöks.", "8062808b87ce6032": "Modellpriser", "cf5409d12fc3f53b": "Alla leverantörer", - "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", - "b05ed15d19d4a485": "Empty {time}", - "56fb015730a158bc": "projected", - "fc3a1241f943cae6": "Now", + "498a69c10b2ed2d9": "{label}: kvarvarande poolkvot, registrerad och prognos", + "b05ed15d19d4a485": "Tom {time}", + "56fb015730a158bc": "prognos", + "fc3a1241f943cae6": "Nu", "55e99aaf3d0e6af4": "Priserna har inte lästs in", "ed447281261f2d0e": "Skrivskyddad åtkomst", "67633defded66bf7": "Ange ett modell-id.", diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 555e167b5e00..6a1b9ece1725 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -11884,20 +11884,20 @@ "1b16346722b65812": "窗口剩余 {timeLeft}%", "7aaaff1c6484f25c": "分段", "8bcab2ef61de6518": "上限 $0", - "98947080075a0e9f": "of {capacity}%", - "319d956d8dc9626e": "Pool empty", - "7edac2c4173fee09": "Not by {date}", - "649af7801ecb5d6c": "Empty now", - "7b3b4057463829e0": "First empty", - "0cc4fd1cf5ac9270": "now", - "ade42d3734d25cb8": "in {duration}", - "94fcce9e98d053ad": "None", - "e7c90232ad94f3ca": "Next reset", - "22f3ae62c7a65e0f": "Burn, last 3h", - "737171d0d80cb0d0": "Burn, window avg", + "98947080075a0e9f": "/ {capacity}%", + "319d956d8dc9626e": "共享池耗尽", + "7edac2c4173fee09": "{date} 前不会耗尽", + "649af7801ecb5d6c": "现已耗尽", + "7b3b4057463829e0": "最先耗尽", + "0cc4fd1cf5ac9270": "现在", + "ade42d3734d25cb8": "{duration}后", + "94fcce9e98d053ad": "无", + "e7c90232ad94f3ca": "下次重置", + "22f3ae62c7a65e0f": "消耗(最近 3 小时)", + "737171d0d80cb0d0": "消耗(窗口平均)", "a16b48709357a5a7": "管理用量", - "e20b23cc4eee52c1": "Reset advice:", - "aca138d5adaa5f69": "Subscriptions", + "e20b23cc4eee52c1": "重置建议:", + "aca138d5adaa5f69": "订阅", "8bd6f07136317c8f": "选中的环境上没有提供方报告订阅限制。", "87f5d0c61b335f38": "用已连接的账户在 ChatGPT 中查看用量。", "5b4c71b36b979e80": "费用", @@ -11988,10 +11988,10 @@ "b11af3f3da3d494e": "选中的环境仍在扫描,总计暂不完整。", "8062808b87ce6032": "模型价格", "cf5409d12fc3f53b": "所有提供方", - "498a69c10b2ed2d9": "{label}: pooled quota left, recorded and projected", - "b05ed15d19d4a485": "Empty {time}", - "56fb015730a158bc": "projected", - "fc3a1241f943cae6": "Now", + "498a69c10b2ed2d9": "{label}:共享池剩余额度(已记录与预测)", + "b05ed15d19d4a485": "{time} 耗尽", + "56fb015730a158bc": "预测", + "fc3a1241f943cae6": "现在", "55e99aaf3d0e6af4": "价格未加载", "ed447281261f2d0e": "只读权限", "67633defded66bf7": "请输入模型 ID。", diff --git a/docs/progress.md b/docs/progress.md index 794c022123e2..4f4be6958bc8 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -179,3 +179,11 @@ - Review: one read-only review on the second Claude account found no bugs. Taken: the OpenCode comment. Left: upstream's Resume test table now expects Resume in every row; keeping upstream's rows keeps later syncs simple. - Switching the hubs: migration `100_TurnStartReadIndexes` adds three partial indexes. The Node pins did not change. - Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Not checked in a browser: the Resume button on a stopped Grok run. + +## 2026-11-19: Fork Usage strings translated + +- What: the 17 web strings the fork added to Usage → Limits (the pooled view: "Pool empty", "First empty", "Next reset", the burn labels, "Reset advice:", "Subscriptions", the chart's "Now", "projected" and aria label, and their values) are translated in de, es, fr, ja, ko, pt-BR, ru, sv and zh, following each catalog's existing words for pool and reset. Mobile has none of these keys. +- Why: they were added before the 2026-11-18 sync and stayed English in every non-English catalog. +- How found: keys in the fork's web `en.json` that upstream's lacks: 17, all still English in `ja.json`. +- Numbers: `vp run i18n:check` pass; `vp run check:changed`: format and typecheck (2 packages) pass. +- Next: Tomáš merges the PR. From 50ff7e28565a429e8d7e6019f724815a16b5ed52 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Thu, 19 Nov 2026 21:28:03 +0100 Subject: [PATCH 110/230] docs: keep the Next line of the Resume copy progress entry The merge of origin/main into this branch dropped it from the entry #20 added. --- docs/progress.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/progress.md b/docs/progress.md index 4aa249e488d8..89707ceba0d3 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -186,6 +186,7 @@ - Why: the switch was off on both hubs. When Claude A hit its 5-hour limit, Auto benched it but never moved the thread, which sat idle for 50 minutes. The old text only spoke of resuming at reset. - Numbers: `vp run i18n:check` pass; `vp run check:changed`: format, lint, knip, typecheck (3 packages), 2 test files and react compiler pass. - Real run: dev server on a seeded worktree `.t3`; Settings → Threads shows the new text, and searching "failover" lists the switch. +- Next: Tomáš merges the PR. ## 2026-11-19: Fork Usage strings translated From 05adeb7419375ba5b82a35c5c08c8fababd9ecac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 20 Nov 2026 07:05:03 +0100 Subject: [PATCH 111/230] docs: record the upstream 66b8a94f8d sync in progress.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Appends the progress entry for the merge of upstream main 66b8a94f8d (93 commits) into fork main: the one conflict and how it was resolved, the upstream changes checked against fork features, the check, boot and review results, the new migration for the hub switch, and the 61 upstream commits that landed overnight and are left for the next sync. Origin: Tomáš asked to sync the fork with upstream and to add a progress entry in the same PR. --- docs/progress.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/progress.md b/docs/progress.md index 89707ceba0d3..856d7d3ab0a3 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -195,3 +195,16 @@ - How found: keys in the fork's web `en.json` that upstream's lacks: 17, all still English in `ja.json`. - Numbers: `vp run i18n:check` pass; `vp run check:changed`: format and typecheck (2 packages) pass. - Next: Tomáš merges the PR. + +## 2026-11-20: Fork synced with upstream `66b8a94f8d` by a merge + +- What: upstream main `66b8a94f8d`, 93 commits newer than the last sync base `8edefc8818`, was merged into fork main `2f21fd0fbe` with a real merge (`29aceeea47`), as in the last sync. Fork main stays an ancestor, so the PR merges without a force-push and the fork's commits keep their ids. +- Why: fork main was 93 upstream commits behind after #19. +- Conflict: one, in `ProviderTurnStartService.ts`. Upstream #39306 wraps the text sent to the provider in `withMessageSenderNote`, a line that tells the agent when another agent, a scheduled task or a T3 tool sent the message. The fork sends "Continue where you left off." when Resume is pressed on a session without native resume (2026-11-15). The note now wraps whichever text the fork picks. Every client sends Resume as `createdBy: "user"`, which gets no note, so Resume still sends the bare prompt. The 30 other files changed on both sides merged without conflicts, among them AGENTS.md and the web and mobile catalogs. +- Fork behavior kept: `git diff upstream/main...origin/main` (old base) and `git diff upstream/main...HEAD` are both 75 files, +3637/-242, and per file the lines the fork adds and removes are the same in 74. The 75th is the conflict above. +- Checked and left alone: #39283 (the mobile goal pill sends `/goal clear` and `/goal resume` with the thread's stored model; Auto routing also matches a routed selection by its stamped `auto` option, so the command routes like a typed message, as on web), #39281 (a delivered handoff of a failed run is not re-sent to later fresh sessions; Auto failover gets a new handoff for its new provider thread), #35343 (camel-case badge initials; the fork's instance names have two words), #39287 (no `MemoryHigh` for agents on hosts without swap; both hubs have swap). Auto failover's message (`createdBy: "agent"`, `creationSource: "server"`) gets no sender note. +- Numbers: `vp run check:changed upstream/main` (the fork's 75 files): unused patches, format, lint, knip, graphql, typecheck (42 packages), 1105 tests in 31 files (the fork's 15 test files among them) and react compiler pass. `vp run i18n:check` pass. The agent context budget did not change. +- Real run (worktree `.t3` seeded from a read-only snapshot of the live database, settings with only the two Auto instances and `autoResumeLimitedThreads` off): migration `101_DelegatedTaskReadIndexes` applied to the snapshot, and the server ran for 15 minutes with the three Claude drivers, provider status probes and usage sweeps. Of its 4147 trace spans, the only failures are two lookups for managed Codex and Antigravity installs the fresh data dir lacks, and two spans interrupted at shutdown. No agent turn was sent. +- Review: one read-only review on the second Claude account found no bugs. It confirmed that only clients start a manual Resume, so that path never gets a sender note, and that #39281 leaves Auto failover alone: failover moves the thread to another provider thread, which gets its own new handoff. Noted, not acted on: a run on a provider without native resume that failed after an injected handoff now resumes with only "Continue where you left off.", so if that session never kept the failed prompt, the handoff's context is missing. Upstream accepts the same trade-off for native resume. +- Switching the hubs: migration `101_DelegatedTaskReadIndexes` adds two partial indexes. The Node pins did not change. +- Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Upstream main moved 61 commits overnight (`da54e47f26`); they merge without textual conflicts but touch 29 fork files, among them `threadExecution.ts` (the Resume gate), `server.ts`, `Orchestrator.ts` and `ClaudeAdapterV2.ts`, so they go in the next sync. From 94f183751a0af91e9f842cddebd4535fae539444 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 20 Nov 2026 07:40:12 +0100 Subject: [PATCH 112/230] ci: skip the relay preview sweep outside pingdotgg/t3code The daily schedule of "Clean up relay preview" starts "List closed relay previews" on a Blacksmith runner, which exists only in pingdotgg/t3code. On this fork the job sat queued for almost 8 hours until it was cancelled (run 44567211406), and the schedule repeats every day. Run the job only in pingdotgg/t3code, the same repo check #14 uses. No PR on the fork has ever had the relay:preview label, so there is nothing to sweep here. The sweep jobs need this one and skip with it. --- .github/workflows/relay-preview-cleanup.yml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/.github/workflows/relay-preview-cleanup.yml b/.github/workflows/relay-preview-cleanup.yml index 483e3e0b01b7..8351be159c3c 100644 --- a/.github/workflows/relay-preview-cleanup.yml +++ b/.github/workflows/relay-preview-cleanup.yml @@ -100,7 +100,9 @@ jobs: list_closed_previews: name: List closed relay previews - if: github.ref == 'refs/heads/main' && github.event_name != 'pull_request_target' + # Relay previews exist only in pingdotgg/t3code. On a fork this job waits + # for a Blacksmith runner that never comes until GitHub cancels it. + if: github.repository == 'pingdotgg/t3code' && github.ref == 'refs/heads/main' && github.event_name != 'pull_request_target' runs-on: blacksmith-8vcpu-ubuntu-2404 timeout-minutes: 10 outputs: From 6606a46979156c413b56130ae31461b5b3a66aa8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 20 Nov 2026 09:32:25 +0100 Subject: [PATCH 113/230] fix(shared): Auto skips providers whose runtime the manifest rates broken Upstream #38970 rates Antigravity below 1.5 broken for T3 0.1.10 and up, now in the bundled manifest too, and #39427 makes the server refuse a session on any provider whose version the manifest rates broken. Auto's usable() did not read that rating, so once both Claude accounts were out, Auto could pick a runtime the server refuses, and each turn failed with a setup error that failover does not handle. On hub2, Antigravity A and B run 1.4.5 and still list Gemini 3.8 Flash, and B's Gemini pool is 7% used. Replaying Auto on hub2's live provider snapshots with both Claude accounts exhausted, Auto Low went to Antigravity B before this change and goes to OpenCode with it. Origin: review of the upstream 16d40942ac sync (merge 04ba054acf). --- packages/shared/src/autoModel.test.ts | 18 ++++++++++++++++++ packages/shared/src/autoModel.ts | 2 ++ 2 files changed, 20 insertions(+) diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts index 115cd940572a..bb9ddc7e9e3d 100644 --- a/packages/shared/src/autoModel.test.ts +++ b/packages/shared/src/autoModel.test.ts @@ -544,6 +544,24 @@ describe("resolveAutoModelSelection", () => { { id: "auto", value: "medium" }, ], }); + // The server refuses every session on a runtime the manifest rates broken (agy 1.4.5). + const broken = { + ...antigravity, + version: "1.4.5", + compatibilityAdvisory: { + status: "broken", + message: "This provider version is known to be incompatible with this T3 Code release.", + recommendedVersion: null, + recommendedRange: ">=1.5.12 <2", + }, + } as unknown as ServerProvider; + expect( + resolveAutoModelSelection({ + selection: auto(), + providers: [claude("claudeAuto", 100), claude("claudeAutoB", 100), broken], + now, + }), + ).toBeNull(); }); it("after every Claude subscription, uses ChatGPT, then Grok, then Gemini", () => { diff --git a/packages/shared/src/autoModel.ts b/packages/shared/src/autoModel.ts index fcf7b2e86036..93c8670a355f 100644 --- a/packages/shared/src/autoModel.ts +++ b/packages/shared/src/autoModel.ts @@ -279,6 +279,8 @@ function usable(provider: ServerProvider, model: string, now: number): boolean { provider.installed && provider.auth.status !== "unauthenticated" && isProviderAvailable(provider) && + // The server refuses every session on a runtime the manifest rates broken. + provider.compatibilityAdvisory?.status !== "broken" && provider.models.some((entry) => entry.slug === model) && exhaustedUsageWindow(provider, now, model) === undefined ); From 3d5e4fa1029eb2a98a4ebe70ef9c672b5a00b28c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 20 Nov 2026 09:40:55 +0100 Subject: [PATCH 114/230] docs: record the upstream 16d40942ac sync in progress.md MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit What the sync merged, the checks of the fork's diff before and after, the Auto fix for runtimes the manifest rates broken, the real run on a seeded copy of the live database (migrations 101 and 102), the review result, and what switching the hubs needs. Origin: Tomáš asked to sync the fork with upstream. --- docs/progress.md | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/docs/progress.md b/docs/progress.md index 856d7d3ab0a3..824c21cfc7b1 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -208,3 +208,19 @@ - Review: one read-only review on the second Claude account found no bugs. It confirmed that only clients start a manual Resume, so that path never gets a sender note, and that #39281 leaves Auto failover alone: failover moves the thread to another provider thread, which gets its own new handoff. Noted, not acted on: a run on a provider without native resume that failed after an injected handoff now resumes with only "Continue where you left off.", so if that session never kept the failed prompt, the handoff's context is missing. Upstream accepts the same trade-off for native resume. - Switching the hubs: migration `101_DelegatedTaskReadIndexes` adds two partial indexes. The Node pins did not change. - Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Upstream main moved 61 commits overnight (`da54e47f26`); they merge without textual conflicts but touch 29 fork files, among them `threadExecution.ts` (the Resume gate), `server.ts`, `Orchestrator.ts` and `ClaudeAdapterV2.ts`, so they go in the next sync. + +## 2026-11-20: Fork synced with upstream `16d40942ac` by a merge + +- What: upstream main `16d40942ac`, 69 commits newer than the last sync base `66b8a94f8d`, was merged into fork main `9b157f83e0` with a real merge (`04ba054acf`), as in the last two syncs. Fork main stays an ancestor, so the PR merges without a force-push and the fork's commits keep their ids. +- Why: fork main was 69 upstream commits behind after #22 (the 61 noted there at `da54e47f26`, plus 8 since, among them the v0.1.11 release commit). +- Conflicts: none. The 29 files changed on both sides merged cleanly: the web and mobile catalogs, `ClaudeAdapterV2.ts`, `Orchestrator.ts`, `server.ts`, `ProviderRegistry.test.ts`, `ChatView.tsx`, `settingsSearch.ts`, `docs/user/thread-sidebar.md`, and `threadExecution.ts` and its test. +- Fork behavior kept: the fork's diff against upstream is 76 files before (`66b8a94f8d..9b157f83e0`, +3653/-243) and after the merge (`16d40942ac..04ba054acf`, +3643/-233). Per file, the lines the fork adds and removes are identical in 66. The other 10 are the web catalogs, where one key line (`1b16346722b65812`) counted as moved in the old diff and not in the new one. Parsed as JSON, each of the 20 web and mobile catalogs equals the old base plus the fork's key changes plus upstream's, and no key was changed by both. +- The Resume gate: upstream's only change to `threadExecution.ts` (#37419) adds `lastErrorSource`, which keys the error banner. `deriveResumableRunId`, and with it Resume on providers without native resume, is untouched. +- Checked and left alone: #39417 (an agent's automatic send waits behind a queued agent message; Auto failover sends only after the run failed, so there is no active run to overtake), #38869 and #39455 (subagent delegation after the parent's turn, compaction follow-ups), #39528 (Claude steering no longer interrupts tools; the `Auto level:` line and the reopen on a level change are untouched), #39502 (provider batches drop superseded entity snapshots; failover listens for `run.updated`, which still arrives), #39378 (Antigravity's new "Auto" is agy's own auto-review permission mode, not the Auto model). No upstream change touched `autoModel.ts`, `AutoFailoverService.ts`, `ProviderTurnStartService.ts`, the Grok usage reader, or the contract files the fork reads (`server.ts`, `providerUsageLimits.ts`, `modelSelection.ts`, `orchestrationV2.ts`). +- Numbers: `vp run check:changed 16d40942ac` (the fork's 76 files): unused patches, format, lint, knip, graphql, typecheck (42 packages), 1107 tests in 31 files and react compiler pass. `vp run i18n:check` pass. +- Real run: `vp run migrate-dev-db` seeded the worktree's `.t3` from a read-only snapshot of the live database (5 projects, 28 threads, 137.5 MB) and applied `101_DelegatedTaskReadIndexes` (from the last sync, not yet deployed) and `102_ThreadItemCounts`. The new per-thread item totals match the per-run counts for all 28 threads. The server then booted on that data dir with settings holding only the two Auto instances and auto-resume off. Replaying Auto on the snapshots it cached (A at 99% weekly, past the 90% guard; B at 78%): Low → Auto B Sonnet 5.5 at low, Medium → Auto B Opus 5.5 at medium, High → Auto B Opus 5.5 at max. No agent turn was sent. +- What went wrong in the run: the first boot inherited this agent's `CLAUDE_CONFIG_DIR` (Claude B), so the instances without their own home path read account B's usage. The second boot unset the Claude session variables; agents running on Claude B should do the same before starting a dev server. On a fresh data dir, the startup welcome thread (dev and `t3 start` only; `t3 serve`, which the hubs run, never creates it) is created about 4 s before the first Claude probe returns, so Auto rejects it and it is skipped with a warning. With cached snapshots it routes like any thread (the second boot: Auto Medium, Opus 5.5). That path is unchanged by this merge. Trace of the second boot: 3406 spans in about 4 minutes, 2 failures (the managed Codex install the fresh data dir lacks, one transport error from Claude's usage endpoint); all three Claude checks passed. +- Fixed (`6606a46979`): Auto skips a provider whose runtime the manifest rates broken. Upstream #38970 rates Antigravity below 1.5 broken for T3 0.1.10 and up (hub2's live manifest already did; now the bundled one does too), and #39427 refuses a session on any runtime rated broken. Auto's `usable()` ignored the rating. On hub2, Antigravity A and B run 1.4.5 and still list Gemini 3.8 Flash, and B's Gemini pool is 7% used. Replaying Auto on hub2's live provider snapshots with both Claude accounts exhausted, Auto Low went to Antigravity B before the fix (a refused session, which failover does not handle) and goes to OpenCode after it; Medium and High reach Grok first either way. The new row in the Antigravity fallback test failed on the merge and passes; autoModel 24/24, autoRoute and AutoFailoverService pass. +- Review: one read-only review on the second Claude account found no semantic conflicts and confirmed each call above (failover sets no `deliveryIntent`, so #39417 never queues it; a stream's failure waits for its queued snapshots, so the error item commits before `run.updated: failed`). Its one finding, Auto routing to a broken runtime, is the fix above. +- Switching the hubs: migrations `101_DelegatedTaskReadIndexes` (two partial indexes) and `102_ThreadItemCounts` (a table filled from the existing counts, an index and five triggers). The app version is 0.1.11. The Node pins and the lockfile did not change. +- Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Update Antigravity A and B in Antigravity setup: until they run 1.5 or newer, the server refuses them and Auto now skips them. Upstream main moved 3 commits during the sync (`f2d4df0367`: #39585, #39579, #39569); they touch none of the fork's files and go in the next sync. From 28266b7d5e024f659a70aeb04b5d3801b2325700 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 20 Nov 2026 11:26:32 +0100 Subject: [PATCH 115/230] feat(server): threads launched from a thread name it as their parent A thread an agent starts with t3_thread_launch kept no link to the thread that launched it: thread.create dropped delegatedFrom unless a linked environment sent the launch. So the launcher could not list or follow its workers. The launch now stamps delegatedFrom with the calling thread whenever a thread here calls it. An agent cannot name another parent: only a linked environment's launch keeps the parent it sends. thread.create keeps the field without linkOrigin, since withCreationProvenance already strips it from client commands. Asked for in the launched-thread lineage task: a maintainer thread that launches workers loses track of them. --- apps/server/src/mcp/linkOrigin.test.ts | 44 +++++++++++++++++++ .../src/mcp/toolkits/project/handlers.ts | 10 ++++- .../src/orchestration-v2/Orchestrator.ts | 6 +-- packages/contracts/src/orchestrationV2.ts | 4 +- 4 files changed, 56 insertions(+), 8 deletions(-) diff --git a/apps/server/src/mcp/linkOrigin.test.ts b/apps/server/src/mcp/linkOrigin.test.ts index 928fda0dd72f..855729491555 100644 --- a/apps/server/src/mcp/linkOrigin.test.ts +++ b/apps/server/src/mcp/linkOrigin.test.ts @@ -6,6 +6,7 @@ import { CommandId, ContextTransferId, EnvironmentId, + MessageId, NodeId, type OrchestrationV2Run, ProjectId, @@ -231,6 +232,14 @@ const laptop = clientScope("laptop", true, "auto"); const desk = clientScope("desk", true, "auto"); const trusted = clientScope("trusted", true, "full-access"); const claudeCode = clientScope("claude-code", false, "full-access"); +const threadScope = (threadId: ThreadId): McpInvocationContext.McpInvocationScope => ({ + environmentId: EnvironmentId.make("environment:box"), + requestNamespace: `provider:${threadId}`, + thread: { threadId, providerSessionId: `provider:${threadId}`, providerInstanceId: instanceId }, + client: undefined, + capabilities: new Set(["orchestration"]), + issuedAt: 0, +}); const call = ( scope: McpInvocationContext.McpInvocationScope, @@ -349,6 +358,41 @@ it.layer(Layer.provideMerge(layerTools, layerOrchestration))("work a link starts assert.deepEqual((yield* projections.getThreadShell(task))?.delegatedFrom, delegatedFrom); const claimed = yield* launch(claudeCode, "Claims a parent", { delegatedFrom }); assert.equal((yield* projections.getThreadShell(claimed))?.delegatedFrom, undefined); + + // A thread here that launches one is its parent, whatever parent it names. + const orchestrator = yield* Orchestrator.OrchestratorV2; + const launcher = ThreadId.make("thread:launcher"); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make("create:launcher"), + threadId: launcher, + projectId, + title: "Launcher", + modelSelection: { instanceId, model: "gpt-5" }, + runtimeMode: "auto", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("start:launcher"), + threadId: launcher, + messageId: MessageId.make("message:launcher"), + text: "Launch a worker.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "user", + creationSource: "web", + }); + const worker = yield* launch(threadScope(launcher), "Worker", { delegatedFrom }); + assert.deepEqual((yield* projections.getThreadShell(worker))?.delegatedFrom, { + environmentId: "environment:box", + threadId: launcher, + title: "Launcher", + }); }), ); diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 08f372e2fcef..3204ab3205bb 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -403,6 +403,13 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { )?.supportedRuntimeModes, }); } + // A link's launch may name its parent there; a thread here is always its own launch's parent. + const delegatedFrom = + linkOrigin !== undefined + ? input.delegatedFrom + : caller === undefined + ? undefined + : { environmentId: scope.environmentId, threadId: caller.id, title: caller.title }; const result = yield* ThreadMessageIntake.launchThread({ commandId, threadId, @@ -425,8 +432,7 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { createdBy: "agent", creationSource: "mcp", ...(linkOrigin === undefined ? {} : { linkOrigin }), - // Kept only alongside linkOrigin: thread.create drops it otherwise. - ...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }), + ...(delegatedFrom === undefined ? {} : { delegatedFrom }), }).pipe( Effect.mapError((error) => { if (error._tag === "AttachmentClaimError") { diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 3e310a7570eb..08af1d5ecbd6 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -4014,10 +4014,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio activeProviderThreadId: null, pullRequests: [], ...(command.linkOrigin === undefined ? {} : { linkOrigin: command.linkOrigin }), - // Only stamped work names a remote parent, so a client cannot claim one. - ...(command.linkOrigin === undefined || command.delegatedFrom === undefined - ? {} - : { delegatedFrom: command.delegatedFrom }), + // Clients never send one (withCreationProvenance strips it); the MCP launch sets it. + ...(command.delegatedFrom === undefined ? {} : { delegatedFrom: command.delegatedFrom }), lineage: { parentThreadId: null, relationshipToParent: null, diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 573607abc7e9..f26ae40b5b00 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -568,7 +568,7 @@ export function applyOrchestrationV2ThreadVisit, ): boolean => @@ -3148,7 +3148,7 @@ export const OrchestrationV2Command = Schema.Union([ worktreePath: Schema.NullOr(TrimmedNonEmptyString), /** Only the server sets this; a client's thread.create never carries one. */ linkOrigin: Schema.optional(OrchestrationV2LinkOrigin), - /** Only the server sets this, with `linkOrigin`, for a linked environment's delegated task. */ + /** Only the server sets this: the thread whose agent launched this one, here or over a link. */ delegatedFrom: Schema.optional(OrchestrationV2DelegatedFrom), importedNativeThread: Schema.optional( Schema.Struct({ From 6dda6687d26553d1ca0fa4ea4693d7064812f2fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 20 Nov 2026 11:27:37 +0100 Subject: [PATCH 116/230] feat(server): a launched thread's finished run notifies its launcher The thread that launched another had to poll it with t3_thread_wait or t3_thread_read to learn it was done. LaunchedThreadNoticeReactor watches run.updated. When a run of a thread whose delegatedFrom names a thread here ends as completed, failed or interrupted, it sends the launcher the notice a delegated task sends: a delegated_task notification carrying the run's last reply, as delegate_task results inline it. Delivery is unchanged: the orchestrator steers that notice into the launcher's live turn or queues it to wake an idle one. Runs that the thread's own pull request watch or Monitor woke send nothing, and neither do cancelled runs, which include restart-cut runs that a continuation picks up. Archived, deleted and linked-environment launchers are skipped; linked tasks report through their follower. Command and message ids derive from the run, so a repeated run.updated adds no second notice. Asked for in the launched-thread lineage task: the launcher should hear when its workers finish instead of polling. --- .../LaunchedThreadNoticeReactor.test.ts | 269 ++++++++++++++++++ .../LaunchedThreadNoticeReactor.ts | 151 ++++++++++ apps/server/src/server.ts | 7 + 3 files changed, 427 insertions(+) create mode 100644 apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.test.ts create mode 100644 apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.ts diff --git a/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.test.ts b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.test.ts new file mode 100644 index 000000000000..cef103d491fe --- /dev/null +++ b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.test.ts @@ -0,0 +1,269 @@ +import { assert, it } from "@effect/vitest"; +import { + CommandId, + EnvironmentId, + EventId, + MessageId, + type OrchestrationV2DelegatedFrom, + type OrchestrationV2Notification, + type OrchestrationV2Run, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts"; +import * as EventSink from "./EventSink.ts"; +import * as LaunchedThreadNoticeReactor from "./LaunchedThreadNoticeReactor.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "./ProviderAdapterRegistry.ts"; +import * as ProviderReplayHarness from "./testkit/ProviderReplayHarness.ts"; +import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter"; + +const here = EnvironmentId.make("environment:here"); +const instanceId = ProviderInstanceId.make("codex"); +const modelSelection = { instanceId, model: "gpt-5.1-codex" }; +const projectId = ProjectId.make("project:launched"); +const adapter = { + instanceId, + driver: ProviderDriverKind.make("codex"), + getCapabilities: () => Effect.succeed(CodexProviderCapabilitiesV2), + planSelectionTransition: () => Effect.succeed({ type: "apply_on_next_turn" as const }), + openSession: () => Effect.die("No provider process needed for notices"), +} as ProviderAdapter.ProviderAdapterV2["Service"]; +const layerDatabase = SqlitePersistence.layerMemory; +const layerTest = LaunchedThreadNoticeReactor.layer.pipe( + Layer.provideMerge( + Layer.mergeAll( + layerDatabase, + ProjectionStore.layer.pipe(Layer.provide(layerDatabase)), + ProviderReplayHarness.layerWithRegistry( + { name: "launched-thread-notice" }, + ProviderAdapterRegistry.layerFromAdapters([adapter]), + { databaseLayer: layerDatabase, runEffectWorker: false }, + ), + Layer.mock(ServerEnvironment.ServerEnvironment)({ getEnvironmentId: Effect.succeed(here) }), + ), + ), +); + +const createThread = ( + threadId: ThreadId, + title: string, + delegatedFrom?: OrchestrationV2DelegatedFrom, +) => + Orchestrator.OrchestratorV2.pipe( + Effect.flatMap((orchestrator) => + orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`create:${threadId}`), + threadId, + projectId, + title, + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + ...(delegatedFrom === undefined ? {} : { delegatedFrom }), + createdBy: delegatedFrom === undefined ? "user" : "agent", + creationSource: delegatedFrom === undefined ? "web" : "mcp", + }), + ), + ); + +/** Starts a run on the worker for a message, then ends it with `reply`, as the provider would. */ +const runToEnd = Effect.fn("test.runToEnd")(function* (input: { + readonly threadId: ThreadId; + readonly key: string; + readonly status: OrchestrationV2Run["status"]; + readonly reply?: string; + readonly senderThreadId?: ThreadId; + readonly notification?: OrchestrationV2Notification; +}) { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const eventSink = yield* EventSink.EventSinkV2; + const messageId = MessageId.make(`message:${input.key}`); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`send:${input.key}`), + threadId: input.threadId, + messageId, + text: `Work on ${input.key}`, + attachments: [], + // A wake is always queued; with nothing running it starts at once. + dispatchMode: { + type: input.notification === undefined ? "start_immediately" : "queue_after_active", + }, + ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }), + ...(input.notification === undefined ? {} : { notification: input.notification }), + createdBy: "agent", + creationSource: input.notification === undefined ? "mcp" : "server", + }); + const { runs } = yield* projections.getThreadRecords(input.threadId, ["runs"]); + const run = runs.find((candidate) => candidate.userMessageId === messageId)!; + const now = yield* DateTime.now; + const ended = { + id: EventId.make(`event:${input.key}:ended`), + type: "run.updated", + threadId: input.threadId, + runId: run.id, + occurredAt: now, + payload: { ...run, status: input.status, queuePosition: null, completedAt: now }, + } as const; + yield* eventSink.write({ + events: [ + ...(input.reply === undefined + ? [] + : [ + { + id: EventId.make(`event:${input.key}:reply`), + type: "message.updated" as const, + threadId: input.threadId, + runId: run.id, + occurredAt: now, + payload: { + id: MessageId.make(`message:${input.key}:reply`), + threadId: input.threadId, + runId: run.id, + nodeId: run.rootNodeId, + role: "assistant" as const, + text: input.reply, + attachments: [], + streaming: false, + createdAt: now, + updatedAt: now, + createdBy: "agent" as const, + creationSource: "provider" as const, + }, + }, + ]), + ended, + ], + }); + return ended; +}); + +const notices = (threadId: ThreadId) => + ProjectionStore.ProjectionStoreV2.pipe( + Effect.flatMap((projections) => projections.getThreadRecords(threadId, ["messages"])), + Effect.map(({ messages }) => messages.filter((message) => message.notification !== undefined)), + ); + +it.layer(layerTest)("a thread launched from another", (it) => { + it.effect("tells its launcher when a run ends, once per run", () => + Effect.gen(function* () { + const reactor = yield* LaunchedThreadNoticeReactor.LaunchedThreadNoticeReactor; + const launcher = ThreadId.make("thread:launcher"); + const worker = ThreadId.make("thread:worker"); + yield* createThread(launcher, "Launcher"); + yield* createThread(worker, "Worker", { + environmentId: here, + threadId: launcher, + title: "Launcher", + }); + + const completed = yield* runToEnd({ + threadId: worker, + key: "completed", + status: "completed", + reply: "Opened the pull request.", + senderThreadId: launcher, + }); + yield* reactor.handle(completed); + yield* reactor.handle(completed); + const [notice] = yield* notices(launcher); + assert.equal((yield* notices(launcher)).length, 1); + assert.deepEqual(notice?.notification, { + source: { kind: "delegated_task", taskIds: [], childThreadId: worker }, + outcome: "completed", + summary: 'Launched thread "Worker" completed', + }); + assert.equal( + notice?.text, + `Launched thread ${worker} (Worker) [completed]:\nOpened the pull request.`, + ); + + // Stopped by the user there, or failed: the launcher hears that too. + const interrupted = yield* runToEnd({ + threadId: worker, + key: "interrupted", + status: "interrupted", + }); + yield* reactor.handle(interrupted); + assert.deepEqual((yield* notices(launcher)).at(-1)?.notification, { + source: { kind: "delegated_task", taskIds: [], childThreadId: worker }, + outcome: "cancelled", + summary: 'Launched thread "Worker" was interrupted', + }); + + // A run its own pull request watch woke, and one that never ran, tell it nothing. + const watched = yield* runToEnd({ + threadId: worker, + key: "watched", + status: "completed", + reply: "Checks are still running.", + notification: { + source: { kind: "monitor" }, + outcome: "updated", + summary: "#7: checks running", + }, + }); + yield* reactor.handle(watched); + const cancelled = yield* runToEnd({ + threadId: worker, + key: "cancelled", + status: "cancelled", + }); + yield* reactor.handle(cancelled); + assert.equal((yield* notices(launcher)).length, 2); + }), + ); + + it.effect("tells no one when the launcher is elsewhere or archived", () => + Effect.gen(function* () { + const reactor = yield* LaunchedThreadNoticeReactor.LaunchedThreadNoticeReactor; + const orchestrator = yield* Orchestrator.OrchestratorV2; + const archived = ThreadId.make("thread:archived-launcher"); + const remote = ThreadId.make("thread:remote-task"); + const orphan = ThreadId.make("thread:orphan"); + yield* createThread(archived, "Archived launcher"); + yield* orchestrator.dispatch({ + type: "thread.archive", + commandId: CommandId.make("archive:launcher"), + threadId: archived, + }); + yield* createThread(orphan, "Orphan", { + environmentId: here, + threadId: archived, + title: "Archived launcher", + }); + // A linked environment's task: its follower there reports it, not this reactor. + yield* createThread(remote, "Remote task", { + environmentId: EnvironmentId.make("environment:elsewhere"), + threadId: archived, + title: "Archived launcher", + }); + for (const threadId of [orphan, remote]) { + yield* reactor.handle( + yield* runToEnd({ + threadId, + key: `${threadId}:done`, + status: "completed", + reply: "Done.", + senderThreadId: archived, + }), + ); + } + assert.equal((yield* notices(archived)).length, 0); + }), + ); +}); diff --git a/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.ts b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.ts new file mode 100644 index 000000000000..cc595be40ee0 --- /dev/null +++ b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.ts @@ -0,0 +1,151 @@ +import { + CommandId, + MessageId, + type OrchestrationV2DomainEvent, + type OrchestrationV2Notification, + type OrchestrationV2Run, + type ThreadId, +} from "@t3tools/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import type * as Scope from "effect/Scope"; +import * as Stream from "effect/Stream"; + +import { reportLabel } from "@t3tools/provider-core/server/notification"; +import { subagentResultForRun } from "@t3tools/provider-core/server/subagentProjection"; +import * as KeyedLock from "@t3tools/shared/KeyedLock"; + +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as Orchestrator from "./Orchestrator.ts"; +import * as ProjectionStore from "./ProjectionStore.ts"; + +/** + * Tells the thread that launched a thread here (its `delegatedFrom`) when one of that thread's + * runs ends, as a delegated task's notice: steered into the launcher's turn or queued to wake it. + */ +export class LaunchedThreadNoticeReactor extends Context.Service< + LaunchedThreadNoticeReactor, + { + readonly start: () => Effect.Effect; + readonly handle: (event: OrchestrationV2DomainEvent) => Effect.Effect; + } +>()("t3/orchestration-v2/LaunchedThreadNoticeReactor") {} + +// A delegated task's result inlines up to the same size before it points at a read. +const RESULT_INLINE_BYTES = 16_000; + +const OUTCOMES: Partial< + Record< + OrchestrationV2Run["status"], + { readonly outcome: OrchestrationV2Notification["outcome"]; readonly verb: string } + > +> = { + completed: { outcome: "completed", verb: "completed" }, + failed: { outcome: "failed", verb: "failed" }, + interrupted: { outcome: "cancelled", verb: "was interrupted" }, +}; + +const make = Effect.gen(function* () { + const engine = yield* Orchestrator.OrchestratorV2; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const hereId = yield* ServerEnvironment.ServerEnvironment.pipe( + Effect.flatMap((environment) => environment.getEnvironmentId), + ); + + /** The launcher here of the thread whose run ended, or null when there is none to tell. */ + const launcherOf = Effect.fnUntraced(function* (event: OrchestrationV2DomainEvent) { + if (event.type !== "run.updated" || OUTCOMES[event.payload.status] === undefined) return null; + const from = (yield* projections.findThread(event.threadId))?.delegatedFrom; + // A linked environment's task is reported by its follower there. + return from == null || from.environmentId !== hereId ? null : from.threadId; + }); + + const handle: LaunchedThreadNoticeReactor["Service"]["handle"] = Effect.fnUntraced( + function* (event) { + if (event.type !== "run.updated") return; + const ended = OUTCOMES[event.payload.status]; + const launcherId = yield* launcherOf(event); + if (ended === undefined || launcherId === null) return; + const launcher = yield* projections.findThread(launcherId); + if (launcher === null || launcher.archivedAt !== null || launcher.deletedAt !== null) return; + const run = event.payload; + const child = yield* projections.getThreadRecords( + event.threadId, + ["messages", "turnItems", "providerTurns"], + { + messageRunIds: [run.id], + turnItemRunIds: [run.id], + turnItemTypes: ["assistant_message", "error", "system_notice"], + providerTurnAttemptIds: run.activeAttemptId === null ? [] : [run.activeAttemptId], + }, + ); + // Its own pull request watch or Monitor woke this run: the launcher did not ask for it. + const wake = child.messages.find((message) => message.id === run.userMessageId); + if (wake?.notification?.source.kind === "monitor") return; + const label = `Launched thread ${child.thread.id} (${child.thread.title}) [${run.status}]`; + const result = subagentResultForRun(child, run).text; + const text = + Buffer.byteLength(result) <= RESULT_INLINE_BYTES + ? `${label}:\n${result}` + : `${label}. Use t3_thread_read with threadId ${child.thread.id} to read the result.`; + const title = reportLabel(child.thread.title); + yield* engine.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`server:launched-thread-notice:${run.id}`), + threadId: launcherId, + messageId: MessageId.make(`message:launched-thread-notice:${run.id}`), + text, + notification: { + source: { kind: "delegated_task", taskIds: [], childThreadId: child.thread.id }, + outcome: ended.outcome, + summary: `Launched thread${title === undefined ? "" : ` "${title}"`} ${ended.verb}`, + }, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "server", + }); + }, + (effect, event) => + effect.pipe( + Effect.catchCause((cause) => + Effect.logWarning("telling the launcher of a thread that its run ended failed", { + threadId: event.threadId, + cause, + }), + ), + ), + ); + + const start: LaunchedThreadNoticeReactor["Service"]["start"] = Effect.fn( + "LaunchedThreadNoticeReactor.start", + )(function* () { + // Keyed by launcher, so a busy launcher delays only its own notices. + const launcherReactions = yield* KeyedLock.makeRunner(); + yield* forkParked( + Stream.runForEach(engine.streamDomainEvents, (event) => + launcherOf(event).pipe( + Effect.flatMap((launcherId) => + launcherId === null ? Effect.void : launcherReactions.run(launcherId, handle(event)), + ), + Effect.catchCause((cause) => + Effect.logWarning("finding the launcher of a thread failed", { + threadId: event.threadId, + cause, + }), + ), + ), + ).pipe( + Effect.catchCause((cause) => + Effect.logWarning("launched thread notice event stream failed", { cause }), + ), + ), + ); + }); + + return { start, handle } satisfies LaunchedThreadNoticeReactor["Service"]; +}); + +export const layer = Layer.effect(LaunchedThreadNoticeReactor, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index d347feaa6f49..d0ba460d2934 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -8,6 +8,7 @@ import * as StorageCleanup from "./storageCleanup.ts"; import * as PullRequestSyncReactor from "./orchestration-v2/PullRequestSyncReactor.ts"; import * as PullRequestWatchReactor from "./orchestration-v2/PullRequestWatchReactor.ts"; import * as DelegatedTaskQuestionReactor from "./orchestration-v2/DelegatedTaskQuestionReactor.ts"; +import * as LaunchedThreadNoticeReactor from "./orchestration-v2/LaunchedThreadNoticeReactor.ts"; // Effect wraps this raw Node HTTP server after its startup and write-error guards attach. // @effect-diagnostics nodeBuiltinImport:off import * as NodeHttp from "node:http"; @@ -734,6 +735,12 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( yield* service.start(); }), ).pipe(Layer.provide(DelegatedTaskQuestionReactor.layer), Layer.provide(ProjectionStoreV2.layer)), + Layer.effectDiscard( + Effect.gen(function* () { + const service = yield* LaunchedThreadNoticeReactor.LaunchedThreadNoticeReactor; + yield* service.start(); + }), + ).pipe(Layer.provide(LaunchedThreadNoticeReactor.layer), Layer.provide(ProjectionStoreV2.layer)), ProviderUsageLimitsIngestion.layer, layerProviderInstallationRefresh, ProviderInstallation.layer, From 32a338f342f0aafb90af38b747cded35f09fa9a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 20 Nov 2026 12:34:41 +0100 Subject: [PATCH 117/230] fix(client-runtime): a launched thread's approvals and questions show on its launcher With delegatedFrom stamped on local launches, the sidebar nests a launched thread under the thread that launched it, as it nests a subagent. But the roll-up that marks a parent row with a hidden child's pending approval followed only subagent and side-chat links, so a worker waiting on the user stayed invisible behind its launcher. pendingSubagentRequestsByThread now also walks from a thread to its launcher in the same environment, and keeps questions as well as approvals for launched threads: no agent is woken to answer a launched thread's question, unlike a subagent's, so it needs the user too. Asked for in the launched-thread lineage task: the launcher lists and follows the threads it launched. --- .../src/state/threadShell.test.ts | 58 +++++++++++++++++++ .../client-runtime/src/state/threadShell.ts | 37 +++++++++--- 2 files changed, 87 insertions(+), 8 deletions(-) diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index de1bc04aeda8..fe992d167b94 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -452,6 +452,64 @@ describe("v2 thread shell lists", () => { registry.dispose(); }); + it("lists threads launched from a thread here under it, with their questions and approvals", () => { + const { registry, threads, snapshotAtom } = makeHarness(); + const launcher = v2ThreadShell; + const worker = { + ...v2ThreadShell, + id: ThreadId.make("worker"), + creationSource: "mcp" as const, + status: "running" as const, + activityRunStatus: "running" as const, + delegatedFrom: { environmentId, threadId: launcher.id, title: launcher.title }, + }; + // The worker launched one of its own, which shows under the worker, so under the launcher. + const nested = { + ...worker, + id: ThreadId.make("nested-worker"), + delegatedFrom: { environmentId, threadId: worker.id, title: worker.title }, + }; + const request = { id: RuntimeRequestId.make("ask"), createdAt: v2Now }; + const launcherRef = { environmentId, threadId: launcher.id }; + const disposeNavigation = registry.mount(threads.navigationThreadShellsAtom); + const disposeLauncher = registry.mount(threads.threadShellAtom(launcherRef)); + const show = (asking: typeof worker, kind: "user_input" | "command") => + registry.set(snapshotAtom(environmentId), { + ...v2ShellSnapshot, + threads: [ + launcher, + ...[worker, nested].map((thread) => + thread === asking ? { ...thread, pendingRuntimeRequest: { ...request, kind } } : thread, + ), + ], + }); + + show(worker, "user_input"); + expect(registry.get(threads.navigationThreadShellsAtom).map((thread) => thread.id)).toEqual([ + launcher.id, + ]); + // No agent is woken to answer a launched thread's question, so it reaches the user. + expect(registry.get(threads.threadShellAtom(launcherRef))?.pendingSubagentRequest).toBe( + "user_input", + ); + show(nested, "command"); + expect(registry.get(threads.threadShellAtom(launcherRef))?.pendingSubagentRequest).toBe( + "approval", + ); + + // An archived launcher leaves navigation, so its worker is listed on its own. + registry.set(snapshotAtom(environmentId), { + ...v2ShellSnapshot, + threads: [{ ...launcher, archivedAt: v2Now }, worker], + }); + expect(registry.get(threads.navigationThreadShellsAtom).map((thread) => thread.id)).toEqual([ + worker.id, + ]); + disposeLauncher(); + disposeNavigation(); + registry.dispose(); + }); + it("brings an approval up a chain of tasks across three environments to its root", () => { const thirdEnvironmentId = EnvironmentId.make("third-environment-v2"); const { registry, threads, snapshotAtom } = makeHarness([ diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index d5c60570b0a1..035251ad801a 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -149,11 +149,12 @@ function sideChatRequest(thread: OrchestrationV2ThreadShell): PendingSubagentReq /** * The threads to flag for a subagent's live approval, up its - * subagent chain and through a side chat to its parent. `delegated` are tasks this + * subagent chain and through a side chat or a launch to its parent. `delegated` are tasks this * environment's threads delegated to linked environments, with what each one, or its * own subagents, asks. */ function pendingSubagentRequestsByThread( + environmentId: EnvironmentId, threads: ReadonlyArray, delegated: ReadonlyArray<{ readonly parentThreadId: ThreadId; @@ -162,9 +163,17 @@ function pendingSubagentRequestsByThread( ): ReadonlyMap { const requests = new Map(); let byId: ReadonlyMap | undefined; - const flag = (firstParentId: ThreadId | null, request: RolledUpRequest, seen: Set) => { + // A thread launched from one here shows under its launcher, as a subagent does. + const launcherOf = (thread: OrchestrationV2ThreadShell) => + thread.delegatedFrom?.environmentId === environmentId ? thread.delegatedFrom.threadId : null; + const flag = ( + firstParentId: ThreadId | null, + request: RolledUpRequest, + seen: Set, + withQuestions = false, + ) => { // The coordinator answers child questions; approvals and user-only cards need the user. - if (request === "user_input") return; + if (request === "user_input" && !withQuestions) return; byId ??= new Map(threads.map((thread) => [thread.id, thread] as const)); let parentId = firstParentId; while (parentId !== null && !seen.has(parentId)) { @@ -172,9 +181,11 @@ function pendingSubagentRequestsByThread( if (requests.get(parentId) !== "approval") requests.set(parentId, request); const parent = byId.get(parentId); parentId = - parent?.lineage.relationshipToParent === "subagent" || parent?.lineage.sideChat === true - ? parent.lineage.parentThreadId - : null; + parent === undefined + ? null + : parent.lineage.relationshipToParent === "subagent" || parent.lineage.sideChat === true + ? parent.lineage.parentThreadId + : launcherOf(parent); } }; for (const child of threads) { @@ -186,7 +197,13 @@ function pendingSubagentRequestsByThread( } continue; } - if (child.lineage.relationshipToParent !== "subagent") continue; + if (child.lineage.relationshipToParent !== "subagent") { + // No agent is woken to answer a launched thread's question, so it needs the user too. + const launcherId = launcherOf(child); + const request = launcherId === null ? null : rolledUpRequest(child, subagentRequest(child)); + if (request !== null) flag(launcherId, request, new Set([child.id]), true); + continue; + } const request = rolledUpRequest(child, subagentRequest(child)); if (request !== null) flag(parentId, request, new Set([child.id])); } @@ -337,7 +354,10 @@ export function createEnvironmentThreadShellAtoms(input: { const localSubagentRequestsAtom = Atom.family((environmentId: EnvironmentId) => { let previous: ReadonlyMap = EMPTY_SUBAGENT_REQUESTS; return Atom.make((get) => { - const next = pendingSubagentRequestsByThread(get(environmentThreadsAtom(environmentId))); + const next = pendingSubagentRequestsByThread( + environmentId, + get(environmentThreadsAtom(environmentId)), + ); if (sameRequests(previous, next)) return previous; previous = next; return next; @@ -381,6 +401,7 @@ export function createEnvironmentThreadShellAtoms(input: { }); if (delegated.length === 0) continue; const requests = pendingSubagentRequestsByThread( + environmentId, get(environmentThreadsAtom(environmentId)), delegated, ); From 70c968e3bd703d38299aa24289e57487d42a798c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 20 Nov 2026 12:35:36 +0100 Subject: [PATCH 118/230] feat(web): a thread's lineage lists the threads it launched A thread an agent started with t3_thread_launch linked back to its launcher, but the launcher's lineage panel listed only its subagents, forks, transfers and side chats, so a maintainer thread could not see its workers. deriveThreadRelationshipGraph adds a "launched" edge from a thread's delegatedFrom when that launcher lives in the same environment and the thread is not archived; a linked environment's task keeps its subagent record instead. The panel groups launched threads with agents, active or previous, with their provider icon, and the launched thread shows its launcher as an ordinary parent row. The remote-parent row and the "on " header label stay for linked-environment parents only. The relationship shells include the launcher and its launched threads, so both ends load. Asked for in the launched-thread lineage task: the launcher lists the threads it launched, and an archived one leaves the list. --- apps/web/src/components/ChatView.tsx | 9 +++-- .../chat/ThreadRelationshipsControl.tsx | 27 ++++++++++---- apps/web/src/i18n/translations/de.json | 1 + apps/web/src/i18n/translations/en.json | 1 + apps/web/src/i18n/translations/es.json | 1 + apps/web/src/i18n/translations/fr.json | 1 + apps/web/src/i18n/translations/ja.json | 1 + apps/web/src/i18n/translations/ko.json | 1 + apps/web/src/i18n/translations/pt-BR.json | 1 + apps/web/src/i18n/translations/ru.json | 1 + apps/web/src/i18n/translations/sv.json | 1 + apps/web/src/i18n/translations/zh.json | 1 + .../state/entities.relationshipShells.test.ts | 35 ++++++++++++++++--- apps/web/src/state/entities.ts | 21 +++++++---- .../src/state/threadRelationships.test.ts | 31 +++++++++++++++- .../src/state/threadRelationships.ts | 21 ++++++++++- 16 files changed, 132 insertions(+), 22 deletions(-) diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index a8e412e46f71..8a9519d48edc 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -912,7 +912,7 @@ export default function ChatView(props: ChatViewProps) { }, messages, ); - // A linked environment's agent may have delegated this thread from there. + // The thread whose agent launched this one, here or in a linked environment. const delegatedFrom = activeThread?.delegatedFrom ?? null; const delegatedFromEnvironment = useEnvironment(delegatedFrom?.environmentId ?? null); const delegatedFromRef = @@ -959,7 +959,12 @@ export default function ChatView(props: ChatViewProps) { const parentRef = delegatedFromRef; return { title: delegatedFromThread?.title ?? delegatedFrom.title, - environmentLabel: delegatedFromEnvironment?.label ?? activeThread?.linkOrigin?.label ?? "", + ...(delegatedFrom.environmentId === environmentId + ? {} + : { + environmentLabel: + delegatedFromEnvironment?.label ?? activeThread?.linkOrigin?.label ?? "", + }), // Only an environment this client is connected to can open the parent. ...(delegatedFromEnvironment === null ? {} diff --git a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx index e8a5fc1fe60a..8a964cfe0a55 100644 --- a/apps/web/src/components/chat/ThreadRelationshipsControl.tsx +++ b/apps/web/src/components/chat/ThreadRelationshipsControl.tsx @@ -219,6 +219,11 @@ function relationshipHint( ) { if (sideChat) return resolve(msg("Open side chat in this chat")); if (edge.kind === "transfer") return resolve(msg("Open context transfer in this chat")); + if (edge.kind === "launched") { + return edge.sourceThreadId === currentThreadId + ? resolve(msg("Open launched thread in this chat")) + : resolve(msg("Open parent agent in this chat")); + } if (edge.kind === "subagent") { return edge.sourceThreadId === currentThreadId ? resolve(msg("Open subagent in this chat")) @@ -559,7 +564,11 @@ export function ThreadRelationshipsPanel(props: { ...relationshipShells, ...(archivedShells ?? []), ]; - const graph = deriveThreadRelationshipGraph({ threads: shells, projection }); + const graph = deriveThreadRelationshipGraph({ + threads: shells, + projection, + environmentId: props.environmentId, + }); const isHiddenRelation = (threadId: ThreadId) => hiddenKeys.has(threadKey({ environmentId: props.environmentId, threadId })); // While hiding, an unloaded parent, fork or transfer may be hidden; unloaded subagent @@ -626,7 +635,7 @@ export function ThreadRelationshipsPanel(props: { const isParent = isParentThreadRelationship(edge, props.threadId); if (!isParent && graph.nodes.get(threadId)?.thread?.lineage.sideChat === true) return "sideChats"; - if (edge.kind !== "subagent" || isParent) return "related"; + if ((edge.kind !== "subagent" && edge.kind !== "launched") || isParent) return "related"; return isFinishedAgentStatus(edge.status) ? "previous" : "active"; }); const { remoteActive = [], remotePrevious = [] } = groupBy( @@ -655,8 +664,12 @@ export function ThreadRelationshipsPanel(props: { (agent) => agent.childThreadId === null && agent.status === "running", ).length ?? 0) + active.filter(({ edge }) => edge.status === "running").length; - // A linked environment's agent may have delegated this thread from there. - const delegatedFrom = currentThread?.delegatedFrom; + // A linked environment's agent may have delegated this thread from there; a launcher here is a + // parent row of its own. + const delegatedFrom = + currentThread?.delegatedFrom?.environmentId === props.environmentId + ? undefined + : (currentThread?.delegatedFrom ?? undefined); const lineageVisible = props.showLineage && @@ -774,6 +787,8 @@ export function ThreadRelationshipsPanel(props: { const renderRelationshipRow = ({ threadId, edge }: ThreadRelationshipWalkRow) => { const node = graph.nodes.get(threadId); const isSubagent = edge.kind === "subagent"; + // A thread this one launched is an agent too, shown with its own provider. + const isAgent = isSubagent || edge.kind === "launched"; const isMergeTarget = threadId === mergeTargetThreadId; const isParent = isParentThreadRelationship(edge, props.threadId); const rowStatus = @@ -782,7 +797,7 @@ export function ThreadRelationshipsPanel(props: { : undefined) ?? threadRelationshipRowStatus(graph, { threadId, edge }); const RelationshipIcon = isParent ? CornerLeftUpIcon - : isSubagent + : isAgent ? BotIcon : node?.thread?.lineage.sideChat === true ? MessagesSquareIcon @@ -862,7 +877,7 @@ export function ThreadRelationshipsPanel(props: { const relationshipContent = ( <> }) as unknown as OrchestrationV2ThreadShell; const threadId = "current" as OrchestrationV2ThreadShell["id"]; +const here = EnvironmentId.make("environment-here"); +const launchedFrom = (id: string, launcher: string, environmentId = here) => + ({ + ...shell(id), + delegatedFrom: { environmentId, threadId: launcher, title: launcher }, + }) as unknown as OrchestrationV2ThreadShell; describe("selectThreadRelationshipShells", () => { it("keeps the thread, its parent, its children and the threads its projection names", () => { @@ -45,7 +52,9 @@ describe("selectThreadRelationshipShells", () => { >; expect( - selectThreadRelationshipShells(threadId, projection, threads).map((thread) => thread.id), + selectThreadRelationshipShells(threadId, projection, threads, here).map( + (thread) => thread.id, + ), ).toEqual([ "current", "parent", @@ -59,9 +68,25 @@ describe("selectThreadRelationshipShells", () => { it("finds the parent from the shell before the projection loads", () => { const threads = [shell("current", "parent"), shell("parent"), shell("unrelated")]; expect( - selectThreadRelationshipShells(threadId, null as Projection, threads).map( + selectThreadRelationshipShells(threadId, null as Projection, threads, here).map( (thread) => thread.id, ), ).toEqual(["current", "parent"]); }); + + it("keeps the threads it launched here and the thread that launched it", () => { + const threads = [ + launchedFrom("current", "launcher"), + shell("launcher"), + launchedFrom("worker", "current"), + // A linked environment's task names its parent there by an id this one could share. + launchedFrom("linked-task", "current", EnvironmentId.make("environment-elsewhere")), + shell("unrelated"), + ]; + expect( + selectThreadRelationshipShells(threadId, null as Projection, threads, here).map( + (thread) => thread.id, + ), + ).toEqual(["current", "launcher", "worker"]); + }); }); diff --git a/apps/web/src/state/entities.ts b/apps/web/src/state/entities.ts index 185069d4849e..dc5429058420 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -391,12 +391,16 @@ export function readDelegatedUnderParent(): ReadonlySet { return appAtomRegistry.get(environmentThreadShells.delegatedUnderParentAtom); } +/** Its parent here: the thread it forked from, its lineage parent, or the thread that launched it. */ function shellParentThreadId( - thread: Pick, + thread: Pick, + environmentId: EnvironmentId, ): ThreadId | null { - return thread.forkedFrom?.type === "run" - ? thread.forkedFrom.threadId - : thread.lineage.parentThreadId; + if (thread.forkedFrom?.type === "run") return thread.forkedFrom.threadId; + if (thread.lineage.parentThreadId !== null) return thread.lineage.parentThreadId; + return thread.delegatedFrom?.environmentId === environmentId + ? thread.delegatedFrom.threadId + : null; } /** Retains unchanged reachable shells so unrelated streams do not re-render the panel. */ @@ -404,10 +408,11 @@ export function selectThreadRelationshipShells( threadId: ThreadId, projection: Pick | null, threads: ReadonlyArray, + environmentId: EnvironmentId, ): ReadonlyArray { const named = new Set([threadId]); if (projection !== null) { - const parentThreadId = shellParentThreadId(projection.thread); + const parentThreadId = shellParentThreadId(projection.thread, environmentId); if (parentThreadId !== null) named.add(parentThreadId); for (const subagent of projection.subagents) { if (subagent.childThreadId !== null) named.add(subagent.childThreadId); @@ -421,10 +426,11 @@ export function selectThreadRelationshipShells( } } const current = threads.find((thread) => thread.id === threadId); - const currentParentId = current === undefined ? null : shellParentThreadId(current); + const currentParentId = + current === undefined ? null : shellParentThreadId(current, environmentId); if (currentParentId !== null) named.add(currentParentId); return threads.filter( - (thread) => named.has(thread.id) || shellParentThreadId(thread) === threadId, + (thread) => named.has(thread.id) || shellParentThreadId(thread, environmentId) === threadId, ); } @@ -436,6 +442,7 @@ const relationshipShellsAtomFamily = Atom.family((key: string) => { ref.threadId, get(environmentThreadDetails.quietThreadAtom(ref))?.projection ?? null, get(environmentThreadShells.environmentThreadsAtom(ref.environmentId)), + ref.environmentId, ).map( (thread) => get( diff --git a/packages/client-runtime/src/state/threadRelationships.test.ts b/packages/client-runtime/src/state/threadRelationships.test.ts index 90dc68c21dd8..593cbc320741 100644 --- a/packages/client-runtime/src/state/threadRelationships.test.ts +++ b/packages/client-runtime/src/state/threadRelationships.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "vite-plus/test"; -import { ThreadId } from "@t3tools/contracts"; +import { EnvironmentId, ThreadId } from "@t3tools/contracts"; import * as DateTime from "effect/DateTime"; import { @@ -93,6 +93,35 @@ describe("thread relationships", () => { }, ); + it("links a thread launched from one here to its launcher until it is archived", () => { + const here = EnvironmentId.make("environment-here"); + const launcher = ThreadId.make("launcher"); + const thread = (id: string, from: string, archived = false) => ({ + id: ThreadId.make(id), + status: "running", + archivedAt: archived ? DateTime.makeUnsafe("2026-11-20T00:00:00Z") : null, + lineage: { parentThreadId: null }, + delegatedFrom: { environmentId: EnvironmentId.make(from), threadId: launcher, title: "L" }, + }); + const graph = deriveThreadRelationshipGraph({ + threads: [ + { id: launcher, status: "completed", archivedAt: null, lineage: { parentThreadId: null } }, + thread("worker", "environment-here"), + thread("archived-worker", "environment-here", true), + // A linked environment's task here is its parent's subagent record there, not a launch. + thread("linked-task", "environment-elsewhere"), + ] as never, + projection: null, + environmentId: here, + }); + expect(immediateThreadRelationships(graph, launcher)).toEqual([ + expect.objectContaining({ + threadId: ThreadId.make("worker"), + edge: expect.objectContaining({ kind: "launched", status: "running" }), + }), + ]); + }); + it("keeps an older activity run visible over a newer cancelled run", () => { const parent = ThreadId.make("thread-parent"); const child = ThreadId.make("thread-child"); diff --git a/packages/client-runtime/src/state/threadRelationships.ts b/packages/client-runtime/src/state/threadRelationships.ts index 26ff658a5191..3cb0cc8d1181 100644 --- a/packages/client-runtime/src/state/threadRelationships.ts +++ b/packages/client-runtime/src/state/threadRelationships.ts @@ -1,4 +1,5 @@ import { + type EnvironmentId, isOrchestrationV2WorkActive, type OrchestrationV2ThreadShell, type ThreadId, @@ -7,7 +8,7 @@ import * as DateTime from "effect/DateTime"; import type { ThreadStructure } from "./models.ts"; -export type ThreadRelationshipKind = "parent" | "fork" | "subagent" | "transfer"; +export type ThreadRelationshipKind = "parent" | "fork" | "subagent" | "transfer" | "launched"; export interface ThreadRelationshipNode { readonly threadId: ThreadId; @@ -50,6 +51,8 @@ function edgeKey(edge: ThreadRelationshipEdge): string { export function deriveThreadRelationshipGraph(input: { readonly threads: ReadonlyArray; readonly projection: ThreadStructure | null; + /** Where `threads` live, so a thread launched from one of them links to its launcher. */ + readonly environmentId?: EnvironmentId; }): ThreadRelationshipGraph { const threadsById = new Map(); for (const thread of input.threads) { @@ -99,6 +102,22 @@ export function deriveThreadRelationshipGraph(input: { status: thread.activityRunStatus ?? thread.status, }); } + // A linked environment's task names a launcher there, whose subagent record lists it instead. + for (const thread of threads) { + const launcher = thread.delegatedFrom; + if ( + launcher == null || + launcher.environmentId !== input.environmentId || + thread.archivedAt !== null + ) + continue; + addEdge({ + sourceThreadId: launcher.threadId, + targetThreadId: thread.id, + kind: "launched", + status: thread.activityRunStatus ?? thread.status, + }); + } if (input.projection !== null) { const ownerThreadId = input.projection.thread.id; From dc33bb8d6ea45ec584ed4956cd7a2a4acb7d5f9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 20 Nov 2026 12:54:50 +0100 Subject: [PATCH 119/230] docs: a thread that launches another becomes its parent The MCP server guide described t3_thread_launch as starting an unlinked top-level thread, and four comments still said delegatedFrom names only a linked environment's parent. Neither held once local launches stamped delegatedFrom (28266b7d5e) and notified the launcher (6dda6687d2). The guide now says a launch from a thread makes that thread the parent: its lineage lists the new thread, the sidebar nests it, it counts as a delegated thread, and each run that ends sends the parent a delegated_task notice. The comments in models.ts, ThreadForkService, ChatView and the mobile thread screen say the same. Asked for in the launched-thread lineage task. --- apps/mobile/src/features/threads/ThreadRouteScreen.tsx | 2 +- apps/server/src/orchestration-v2/ThreadForkService.ts | 2 +- apps/web/src/components/ChatView.tsx | 2 +- docs/orchestration-v2/orchestrator-mcp-server.md | 9 +++++++++ packages/client-runtime/src/state/models.ts | 2 +- 5 files changed, 13 insertions(+), 4 deletions(-) diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 9d9cddd644e3..f85683f57379 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -553,7 +553,7 @@ function ThreadRouteContent( const headerSubtitle = [ selectedThreadProject?.title ?? null, selectedEnvironmentConnection?.environmentLabel ?? null, - // A linked environment's delegated task names its parent; other linked work its origin. + // A launched thread names the thread that launched it; other linked work its origin. delegatedFrom !== null ? gt("Subagent of {title}", { title: delegatedFromThread?.title ?? delegatedFrom.title }) : selectedThread?.linkOrigin diff --git a/apps/server/src/orchestration-v2/ThreadForkService.ts b/apps/server/src/orchestration-v2/ThreadForkService.ts index e3e523e372bd..587a72ad0606 100644 --- a/apps/server/src/orchestration-v2/ThreadForkService.ts +++ b/apps/server/src/orchestration-v2/ThreadForkService.ts @@ -77,7 +77,7 @@ export const layer: Layer.Layer = Layer.succeed( plan: Effect.fn("ThreadForkService.plan")(function* (input) { const { sourceRun } = input; const sourceLineage = input.sourceProjection.thread.lineage; - // A task a linked environment delegated here is a subagent of a remote thread. + // A thread another thread's agent launched, here or from a linked environment, is its agent. if ( input.sideChat && (sourceLineage.sideChat || diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 8a9519d48edc..84b2409903f5 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -2875,7 +2875,7 @@ export default function ChatView(props: ChatViewProps) { ]); usePasteToFocusComposer(embedded ? null : activeThreadId, composerRef); - // A delegated task is a remote thread's subagent. + // A thread another thread's agent launched, here or from a linked environment, is its agent. const isSubagentThread = activeThread?.lineage.relationshipToParent === "subagent" || delegatedFrom !== null; // Side chats do not nest or start from subagents, and older servers would fork a listed thread. diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 5f48ed4a2c14..fa5ed53461be 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -358,6 +358,15 @@ provider does not offer is refused, and an inherited or default one steps down to the broadest mode it offers. `create_threads` remains the batch option for a shared checkout. +A thread here that launches one becomes its parent: the server stamps the new +thread's `delegatedFrom` with the caller, so the parent's lineage lists it, the +sidebar nests it there, and it counts as a delegated thread +(`isDelegatedAppThread`). Each of its runs that ends completed, failed, or +interrupted sends the parent a `delegated_task` notice with the run's last reply, +steered into the parent's turn or queued to wake it, so the parent need not wait +or poll. Runs the thread's own monitor woke, cancelled runs, and archived parents +get no notice. A launch from an outside agent has no parent. + Set `clientRequestId` on the initial launch to make it retryable. After an error or a lost reply, resend the same request with the same key from the same provider session. This reuses any thread already created by that request. If the diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index 4401f90e898c..afbb54ddb116 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -160,7 +160,7 @@ export interface EnvironmentThreadShell { readonly lineage: OrchestrationV2ThreadShell["lineage"]; readonly forkedFrom: OrchestrationV2ThreadShell["forkedFrom"]; readonly linkOrigin: OrchestrationV2ThreadShell["linkOrigin"] | null; - /** The thread in a linked environment that delegated this one, if one did. */ + /** The thread whose agent launched this one, here or in a linked environment. */ readonly delegatedFrom: OrchestrationV2ThreadShell["delegatedFrom"] | null; readonly activeProviderThreadId: OrchestrationV2ThreadShell["activeProviderThreadId"]; readonly latestRun: ThreadRunSummary | null; From c959eb7a04ba132bee772efff8003c79e0e3240b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 20 Nov 2026 13:12:00 +0100 Subject: [PATCH 120/230] fix(server): a user's own turn in a launched thread does not wake its launcher A thread can be launched because the user asked for a new thread. Once the user works in it directly, every run that ended woke the launcher with a notice it never asked for, at the cost of a turn on the launcher's model each time. The notice now skips a run whose message the user typed in the launched thread, as it already skips runs the thread's own monitor woke. Runs the launcher, the launch, or the server started still notify, so a maintainer thread still hears when its worker finishes. From the read-only review of the launched-thread lineage branch. --- .../LaunchedThreadNoticeReactor.test.ts | 18 +++++++++++++++--- .../LaunchedThreadNoticeReactor.ts | 5 +++-- .../orchestrator-mcp-server.md | 5 +++-- 3 files changed, 21 insertions(+), 7 deletions(-) diff --git a/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.test.ts b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.test.ts index cef103d491fe..b995ff3a4c0a 100644 --- a/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.test.ts +++ b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.test.ts @@ -87,6 +87,8 @@ const runToEnd = Effect.fn("test.runToEnd")(function* (input: { readonly reply?: string; readonly senderThreadId?: ThreadId; readonly notification?: OrchestrationV2Notification; + /** The user typed the message in the worker itself. */ + readonly typed?: boolean; }) { const orchestrator = yield* Orchestrator.OrchestratorV2; const projections = yield* ProjectionStore.ProjectionStoreV2; @@ -105,8 +107,9 @@ const runToEnd = Effect.fn("test.runToEnd")(function* (input: { }, ...(input.senderThreadId === undefined ? {} : { senderThreadId: input.senderThreadId }), ...(input.notification === undefined ? {} : { notification: input.notification }), - createdBy: "agent", - creationSource: input.notification === undefined ? "mcp" : "server", + createdBy: input.typed === true ? "user" : "agent", + creationSource: + input.typed === true ? "web" : input.notification === undefined ? "mcp" : "server", }); const { runs } = yield* projections.getThreadRecords(input.threadId, ["runs"]); const run = runs.find((candidate) => candidate.userMessageId === messageId)!; @@ -205,7 +208,8 @@ it.layer(layerTest)("a thread launched from another", (it) => { summary: 'Launched thread "Worker" was interrupted', }); - // A run its own pull request watch woke, and one that never ran, tell it nothing. + // A run its own pull request watch woke, one that never ran, and one the user started in the + // worker itself tell it nothing: the launcher did not ask for them. const watched = yield* runToEnd({ threadId: worker, key: "watched", @@ -224,6 +228,14 @@ it.layer(layerTest)("a thread launched from another", (it) => { status: "cancelled", }); yield* reactor.handle(cancelled); + const typed = yield* runToEnd({ + threadId: worker, + key: "typed", + status: "completed", + reply: "Renamed it as you asked.", + typed: true, + }); + yield* reactor.handle(typed); assert.equal((yield* notices(launcher)).length, 2); }), ); diff --git a/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.ts b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.ts index cc595be40ee0..730b694c272c 100644 --- a/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.ts +++ b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.ts @@ -81,9 +81,10 @@ const make = Effect.gen(function* () { providerTurnAttemptIds: run.activeAttemptId === null ? [] : [run.activeAttemptId], }, ); - // Its own pull request watch or Monitor woke this run: the launcher did not ask for it. + // The user typed this run's message there, or its own pull request watch or Monitor woke it: + // the launcher did not ask for it. const wake = child.messages.find((message) => message.id === run.userMessageId); - if (wake?.notification?.source.kind === "monitor") return; + if (wake?.createdBy === "user" || wake?.notification?.source.kind === "monitor") return; const label = `Launched thread ${child.thread.id} (${child.thread.title}) [${run.status}]`; const result = subagentResultForRun(child, run).text; const text = diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index fa5ed53461be..7bfeceb20580 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -364,8 +364,9 @@ sidebar nests it there, and it counts as a delegated thread (`isDelegatedAppThread`). Each of its runs that ends completed, failed, or interrupted sends the parent a `delegated_task` notice with the run's last reply, steered into the parent's turn or queued to wake it, so the parent need not wait -or poll. Runs the thread's own monitor woke, cancelled runs, and archived parents -get no notice. A launch from an outside agent has no parent. +or poll. Runs the user started in the thread, runs its own monitor woke, +cancelled runs, and archived parents get no notice. A launch from an outside +agent has no parent. Set `clientRequestId` on the initial launch to make it retryable. After an error or a lost reply, resend the same request with the same key from the same From bd4dad8e5f05fd2f662e9ded0626fe0e69275b11 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Fri, 20 Nov 2026 13:14:24 +0100 Subject: [PATCH 121/230] fix(server): a linked environment cannot name a thread here as a launch's parent A linked environment's t3_thread_launch keeps the parent it sends, so it may name its own thread as a delegated task's parent. It could also name any thread in this environment. Since launched threads started notifying their launcher here, that parent would get a delegated_task notice, with text the link controls, each time the task's run ended. A link's launch now drops a parent that names this environment. Its parent can only be in the linked environment; only this server stamps a parent here, from the calling thread. From the read-only review of the launched-thread lineage branch. --- apps/server/src/mcp/linkOrigin.test.ts | 5 +++++ apps/server/src/mcp/toolkits/project/handlers.ts | 7 +++++-- 2 files changed, 10 insertions(+), 2 deletions(-) diff --git a/apps/server/src/mcp/linkOrigin.test.ts b/apps/server/src/mcp/linkOrigin.test.ts index 855729491555..ef8c4c4b6331 100644 --- a/apps/server/src/mcp/linkOrigin.test.ts +++ b/apps/server/src/mcp/linkOrigin.test.ts @@ -358,6 +358,11 @@ it.layer(Layer.provideMerge(layerTools, layerOrchestration))("work a link starts assert.deepEqual((yield* projections.getThreadShell(task))?.delegatedFrom, delegatedFrom); const claimed = yield* launch(claudeCode, "Claims a parent", { delegatedFrom }); assert.equal((yield* projections.getThreadShell(claimed))?.delegatedFrom, undefined); + // Nor may a link name a thread here: that parent would hear each of the task's runs. + const namesHere = yield* launch(laptop, "Names a parent here", { + delegatedFrom: { ...delegatedFrom, environmentId: "environment:box" }, + }); + assert.equal((yield* projections.getThreadShell(namesHere))?.delegatedFrom, undefined); // A thread here that launches one is its parent, whatever parent it names. const orchestrator = yield* Orchestrator.OrchestratorV2; diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index 3204ab3205bb..31f7458f479e 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -403,10 +403,13 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { )?.supportedRuntimeModes, }); } - // A link's launch may name its parent there; a thread here is always its own launch's parent. + // A link's launch may name its parent there, never here; a thread here is always its own + // launch's parent. const delegatedFrom = linkOrigin !== undefined - ? input.delegatedFrom + ? input.delegatedFrom?.environmentId === scope.environmentId + ? undefined + : input.delegatedFrom : caller === undefined ? undefined : { environmentId: scope.environmentId, threadId: caller.id, title: caller.title }; From 5a85432fac891438d244a7a6529ff25402cccee9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 21 Nov 2026 16:19:43 +0100 Subject: [PATCH 122/230] fix(mobile): launched threads keep their own row on mobile Nesting a launched thread under its launcher hid it from mobile's home list, sidebar and command palette. Mobile has no lineage view and its agents sheet lists only subagent records, so a launched thread there could be opened only from a pasted link. The shared thread-shell atoms take nestLaunchedThreads; mobile passes false, so a thread launched here keeps its row and shows its own approvals, and its open row selects itself. Web keeps nesting them under the launcher's lineage. Linked environments' tasks nest as before. The approval roll-up also stops at an archived launcher, matching delegatedUnderParent, so a request under one shows on the row it is listed on rather than also on a launcher further up. From the read-only review of the launched-thread lineage branch. --- .../threads/useSidebarRowThreadKey.ts | 4 +- apps/mobile/src/state/threads.ts | 3 + .../src/state/threadShell.test.ts | 65 ++++++++++++++++++- .../client-runtime/src/state/threadShell.ts | 29 +++++++-- 4 files changed, 93 insertions(+), 8 deletions(-) diff --git a/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts b/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts index 0e72dad60ca0..e0f41e9c8b37 100644 --- a/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts +++ b/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts @@ -10,6 +10,8 @@ export function useSidebarRowThreadKey(openThreadKey: string | null): string | n const threads = useAtomValue(environmentThreadShells.quietThreadShellsAtom); const openThreadRef = openThreadKey === null ? null : parseScopedThreadKey(openThreadKey); if (openThreadRef === null) return openThreadKey; - const rowRef = resolveListedAncestorThreadRef(openThreadRef, threads); + const rowRef = resolveListedAncestorThreadRef(openThreadRef, threads, { + nestLaunchedThreads: false, + }); return scopedThreadKey(rowRef.environmentId, rowRef.threadId); } diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.ts index bf2013aef539..a16ce77533ed 100644 --- a/apps/mobile/src/state/threads.ts +++ b/apps/mobile/src/state/threads.ts @@ -46,6 +46,8 @@ export const environmentThreadShells = createEnvironmentThreadShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, snapshotAtom: threadEnvironment.snapshotAtom, hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom, + // Mobile has no lineage view, so a launched thread keeps its own row. + nestLaunchedThreads: false, }); const steadyShells = createSteadyShellAtoms({ catalogValueAtom: environmentCatalog.catalogValueAtom, @@ -63,6 +65,7 @@ export const steadyNavigationThreadShellsAtom = createEnvironmentThreadShellAtom catalogValueAtom: environmentCatalog.catalogValueAtom, snapshotAtom: steadyShells.snapshotAtom, hiddenThreadTagsAtom: serverEnvironment.hiddenThreadTagsAtom, + nestLaunchedThreads: false, }).navigationThreadShellsAtom; export const childThreadApprovalsAtom = createChildThreadApprovalsAtom({ childThreadInputsAtom: environmentThreadShells.childThreadInputsAtom, diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index fe992d167b94..0dc2a80effb2 100644 --- a/packages/client-runtime/src/state/threadShell.test.ts +++ b/packages/client-runtime/src/state/threadShell.test.ts @@ -26,7 +26,10 @@ const environmentId = EnvironmentId.make("environment-v2"); const remoteEnvironmentId = EnvironmentId.make("remote-environment-v2"); const otherProjectId = ProjectId.make("other-project"); -function makeHarness(environmentIds: ReadonlyArray = [environmentId]) { +function makeHarness( + environmentIds: ReadonlyArray = [environmentId], + options: { readonly nestLaunchedThreads?: boolean } = {}, +) { const snapshotAtom = Atom.family((_environmentId: EnvironmentId) => Atom.make(v2ShellSnapshot), ); @@ -56,6 +59,7 @@ function makeHarness(environmentIds: ReadonlyArray = [environment catalogValueAtom, snapshotAtom, hiddenThreadTagsAtom: () => Atom.make(null), + ...options, }), }; } @@ -505,6 +509,65 @@ describe("v2 thread shell lists", () => { expect(registry.get(threads.navigationThreadShellsAtom).map((thread) => thread.id)).toEqual([ worker.id, ]); + // A request asked under an archived launcher shows on the row it is listed on, not above it. + registry.set(snapshotAtom(environmentId), { + ...v2ShellSnapshot, + threads: [ + launcher, + { ...worker, archivedAt: v2Now }, + { ...nested, pendingRuntimeRequest: { ...request, kind: "command" } }, + ], + }); + expect(registry.get(threads.navigationThreadShellsAtom).map((thread) => thread.id)).toEqual([ + launcher.id, + nested.id, + ]); + expect(registry.get(threads.threadShellAtom(launcherRef))?.pendingSubagentRequest).toBeNull(); + disposeLauncher(); + disposeNavigation(); + registry.dispose(); + }); + + it("keeps launched threads listed where a client cannot list a thread's launched threads", () => { + const { registry, threads, snapshotAtom } = makeHarness([environmentId], { + nestLaunchedThreads: false, + }); + const launcher = v2ThreadShell; + const worker = { + ...v2ThreadShell, + id: ThreadId.make("worker"), + status: "running" as const, + activityRunStatus: "running" as const, + delegatedFrom: { environmentId, threadId: launcher.id, title: launcher.title }, + pendingRuntimeRequest: { + id: RuntimeRequestId.make("ask"), + createdAt: v2Now, + kind: "command" as const, + }, + }; + const launcherRef = { environmentId, threadId: launcher.id }; + registry.set(snapshotAtom(environmentId), { ...v2ShellSnapshot, threads: [launcher, worker] }); + const disposeNavigation = registry.mount(threads.navigationThreadShellsAtom); + const disposeLauncher = registry.mount(threads.threadShellAtom(launcherRef)); + expect(registry.get(threads.navigationThreadShellsAtom).map((thread) => thread.id)).toEqual([ + launcher.id, + worker.id, + ]); + // The worker's own row shows its approval, so the launcher's does not repeat it. + expect(registry.get(threads.threadShellAtom(launcherRef))?.pendingSubagentRequest).toBeNull(); + expect( + resolveListedAncestorThreadRef( + { environmentId, threadId: worker.id }, + [launcher, worker].map((thread) => ({ + id: thread.id, + environmentId, + lineage: thread.lineage, + archivedAt: null, + delegatedFrom: thread.delegatedFrom ?? null, + })), + { nestLaunchedThreads: false }, + ), + ).toEqual({ environmentId, threadId: worker.id }); disposeLauncher(); disposeNavigation(); registry.dispose(); diff --git a/packages/client-runtime/src/state/threadShell.ts b/packages/client-runtime/src/state/threadShell.ts index 035251ad801a..aebf64b1b55a 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -59,8 +59,8 @@ const isChildRunLive = ( /** * Whether a thread shows under its parent rather than in thread lists: a - * subagent, a side chat, or a task a linked environment delegated here whose parent the - * client lists (`delegatedUnderParent`, by thread key). A task whose parent + * subagent, a side chat, or a task a linked environment delegated here or a thread launched + * here, whose parent the client lists (`delegatedUnderParent`, by thread key). A task whose parent * the client cannot list stays in the lists, so its work is never out of reach. */ export function isShownUnderParent( @@ -80,6 +80,7 @@ export function resolveListedAncestorThreadRef( EnvironmentThreadShell, "id" | "environmentId" | "lineage" | "delegatedFrom" | "archivedAt" >[], + options: { readonly nestLaunchedThreads?: boolean } = {}, ): ScopedThreadRef { const findThread = (target: ScopedThreadRef) => threads.find( @@ -93,7 +94,11 @@ export function resolveListedAncestorThreadRef( if (!isListedThreadLineage(thread.lineage)) { if (thread.lineage.parentThreadId === null) return ref; parent = { environmentId: thread.environmentId, threadId: thread.lineage.parentThreadId }; - } else if (thread.delegatedFrom != null) { + } else if ( + thread.delegatedFrom != null && + (options.nestLaunchedThreads !== false || + thread.delegatedFrom.environmentId !== thread.environmentId) + ) { parent = { environmentId: thread.delegatedFrom.environmentId, threadId: thread.delegatedFrom.threadId, @@ -155,6 +160,7 @@ function sideChatRequest(thread: OrchestrationV2ThreadShell): PendingSubagentReq */ function pendingSubagentRequestsByThread( environmentId: EnvironmentId, + nestLaunchedThreads: boolean, threads: ReadonlyArray, delegated: ReadonlyArray<{ readonly parentThreadId: ThreadId; @@ -163,9 +169,14 @@ function pendingSubagentRequestsByThread( ): ReadonlyMap { const requests = new Map(); let byId: ReadonlyMap | undefined; - // A thread launched from one here shows under its launcher, as a subagent does. - const launcherOf = (thread: OrchestrationV2ThreadShell) => - thread.delegatedFrom?.environmentId === environmentId ? thread.delegatedFrom.threadId : null; + // A thread launched from one here shows under its launcher, as a subagent does, + // unless the client lists it on its own or its launcher is archived (delegatedUnderParent). + const launcherOf = (thread: OrchestrationV2ThreadShell) => { + const from = thread.delegatedFrom; + if (!nestLaunchedThreads || from?.environmentId !== environmentId) return null; + byId ??= new Map(threads.map((candidate) => [candidate.id, candidate] as const)); + return byId.get(from.threadId)?.archivedAt === null ? from.threadId : null; + }; const flag = ( firstParentId: ThreadId | null, request: RolledUpRequest, @@ -287,7 +298,10 @@ export function createEnvironmentThreadShellAtoms(input: { readonly hiddenThreadTagsAtom: ( environmentId: EnvironmentId, ) => Atom.Atom | null>; + /** False where the client has no lineage view to reach a thread's launched threads from. */ + readonly nestLaunchedThreads?: boolean; }) { + const nestLaunchedThreads = input.nestLaunchedThreads !== false; // Point reads and aggregate lists share values without keeping an atom alive // for every listed thread. Replaced source objects can be collected. const scopedThreads = new WeakMap< @@ -356,6 +370,7 @@ export function createEnvironmentThreadShellAtoms(input: { return Atom.make((get) => { const next = pendingSubagentRequestsByThread( environmentId, + nestLaunchedThreads, get(environmentThreadsAtom(environmentId)), ); if (sameRequests(previous, next)) return previous; @@ -402,6 +417,7 @@ export function createEnvironmentThreadShellAtoms(input: { if (delegated.length === 0) continue; const requests = pendingSubagentRequestsByThread( environmentId, + nestLaunchedThreads, get(environmentThreadsAtom(environmentId)), delegated, ); @@ -759,6 +775,7 @@ export function createEnvironmentThreadShellAtoms(input: { if ( parent !== undefined && environmentIds.has(parent.environmentId) && + (nestLaunchedThreads || parent.environmentId !== environmentId) && // An archived parent leaves navigation; its task there stays listed on its own. get(environmentThreadIndexAtom(parent.environmentId)).get(parent.threadId)?.archivedAt === null From 2bcc086f7a8e8178d95257c9058cc4a23afa1c05 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 21 Nov 2026 16:23:48 +0100 Subject: [PATCH 123/230] fix(server): a run a queued message stopped does not tell its launcher it was interrupted Some paths end a launched thread's run as interrupted only to carry on the work in the next run: a restart on a provider without native restart, or applying /goal. The launcher heard "was interrupted" and then "completed" for one piece of work. An interrupted run now sends no notice while another run of that thread is queued or active; that run reports when it ends. From the read-only review of the launched-thread lineage branch. --- .../LaunchedThreadNoticeReactor.test.ts | 39 +++++++++++++++++++ .../LaunchedThreadNoticeReactor.ts | 17 +++++++- 2 files changed, 55 insertions(+), 1 deletion(-) diff --git a/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.test.ts b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.test.ts index b995ff3a4c0a..84248f4ae05d 100644 --- a/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.test.ts +++ b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.test.ts @@ -89,6 +89,8 @@ const runToEnd = Effect.fn("test.runToEnd")(function* (input: { readonly notification?: OrchestrationV2Notification; /** The user typed the message in the worker itself. */ readonly typed?: boolean; + /** Queues a message behind the run before it ends, as a restart or `/goal` does. */ + readonly queueBehind?: boolean; }) { const orchestrator = yield* Orchestrator.OrchestratorV2; const projections = yield* ProjectionStore.ProjectionStoreV2; @@ -111,6 +113,19 @@ const runToEnd = Effect.fn("test.runToEnd")(function* (input: { creationSource: input.typed === true ? "web" : input.notification === undefined ? "mcp" : "server", }); + if (input.queueBehind === true) { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`send:${input.key}:next`), + threadId: input.threadId, + messageId: MessageId.make(`message:${input.key}:next`), + text: `Continue ${input.key}`, + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "agent", + creationSource: "mcp", + }); + } const { runs } = yield* projections.getThreadRecords(input.threadId, ["runs"]); const run = runs.find((candidate) => candidate.userMessageId === messageId)!; const now = yield* DateTime.now; @@ -240,6 +255,30 @@ it.layer(layerTest)("a thread launched from another", (it) => { }), ); + it.effect("says nothing of a run that a queued message stopped to carry on the work", () => + Effect.gen(function* () { + const reactor = yield* LaunchedThreadNoticeReactor.LaunchedThreadNoticeReactor; + const launcher = ThreadId.make("thread:restart-launcher"); + const worker = ThreadId.make("thread:restart-worker"); + yield* createThread(launcher, "Launcher"); + yield* createThread(worker, "Worker", { + environmentId: here, + threadId: launcher, + title: "Launcher", + }); + yield* reactor.handle( + yield* runToEnd({ + threadId: worker, + key: "restarted", + status: "interrupted", + senderThreadId: launcher, + queueBehind: true, + }), + ); + assert.equal((yield* notices(launcher)).length, 0); + }), + ); + it.effect("tells no one when the launcher is elsewhere or archived", () => Effect.gen(function* () { const reactor = yield* LaunchedThreadNoticeReactor.LaunchedThreadNoticeReactor; diff --git a/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.ts b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.ts index 730b694c272c..b5a4bceca341 100644 --- a/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.ts +++ b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.ts @@ -47,6 +47,14 @@ const OUTCOMES: Partial< interrupted: { outcome: "cancelled", verb: "was interrupted" }, }; +const CARRYING_ON: ReadonlySet = new Set([ + "queued", + "preparing", + "starting", + "running", + "waiting", +]); + const make = Effect.gen(function* () { const engine = yield* Orchestrator.OrchestratorV2; const projections = yield* ProjectionStore.ProjectionStoreV2; @@ -73,7 +81,7 @@ const make = Effect.gen(function* () { const run = event.payload; const child = yield* projections.getThreadRecords( event.threadId, - ["messages", "turnItems", "providerTurns"], + ["runs", "messages", "turnItems", "providerTurns"], { messageRunIds: [run.id], turnItemRunIds: [run.id], @@ -85,6 +93,13 @@ const make = Effect.gen(function* () { // the launcher did not ask for it. const wake = child.messages.find((message) => message.id === run.userMessageId); if (wake?.createdBy === "user" || wake?.notification?.source.kind === "monitor") return; + // A queued message stopped it to carry on the work (a restart, /goal); that run reports. + if ( + run.status === "interrupted" && + child.runs.some((other) => other.id !== run.id && CARRYING_ON.has(other.status)) + ) { + return; + } const label = `Launched thread ${child.thread.id} (${child.thread.title}) [${run.status}]`; const result = subagentResultForRun(child, run).text; const text = From 6933b358418a9dec676d89f73355d7afb2120f70 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 21 Nov 2026 16:26:11 +0100 Subject: [PATCH 124/230] refactor(client-runtime): the relationship graph always names its environment deriveThreadRelationshipGraph links a launched thread to its launcher only when it knows which environment its threads live in. With the field optional, a caller that left it out silently lost every launched edge. It is now required; the one caller already passes it. From the read-only review of the launched-thread lineage branch. --- .../src/state/threadRelationships.test.ts | 15 ++++++++++++++- .../src/state/threadRelationships.ts | 2 +- 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/packages/client-runtime/src/state/threadRelationships.test.ts b/packages/client-runtime/src/state/threadRelationships.test.ts index 593cbc320741..7eed8798c669 100644 --- a/packages/client-runtime/src/state/threadRelationships.test.ts +++ b/packages/client-runtime/src/state/threadRelationships.test.ts @@ -10,6 +10,8 @@ import { threadRelationshipRowStatus, } from "./threadRelationships.ts"; +const testEnvironmentId = EnvironmentId.make("environment-test"); + describe("thread relationships", () => { it.each([ ["running", "completed"], @@ -18,6 +20,7 @@ describe("thread relationships", () => { const parent = ThreadId.make("parent"); const child = ThreadId.make("child"); const graph = deriveThreadRelationshipGraph({ + environmentId: testEnvironmentId, threads: [ { id: parent, @@ -45,6 +48,7 @@ describe("thread relationships", () => { const parent = ThreadId.make("missing-parent"); const child = ThreadId.make("child"); const graph = deriveThreadRelationshipGraph({ + environmentId: testEnvironmentId, threads: [ { id: child, @@ -76,7 +80,11 @@ describe("thread relationships", () => { subagents: [], contextTransfers: [], } as never; - const graph = deriveThreadRelationshipGraph({ threads: [], projection }); + const graph = deriveThreadRelationshipGraph({ + threads: [], + projection, + environmentId: testEnvironmentId, + }); expect(immediateThreadRelationships(graph, child)).toEqual([ expect.objectContaining({ threadId: parent, @@ -126,6 +134,7 @@ describe("thread relationships", () => { const parent = ThreadId.make("thread-parent"); const child = ThreadId.make("thread-child"); const graph = deriveThreadRelationshipGraph({ + environmentId: testEnvironmentId, threads: [ { id: child, @@ -153,6 +162,7 @@ describe("thread relationships", () => { const child = ThreadId.make("thread-child"); const missing = ThreadId.make("thread-missing"); const graph = deriveThreadRelationshipGraph({ + environmentId: testEnvironmentId, threads: [ { id: root, @@ -183,6 +193,7 @@ describe("thread relationships", () => { const child = ThreadId.make("thread-child"); const transferTarget = ThreadId.make("thread-transfer"); const graph = deriveThreadRelationshipGraph({ + environmentId: testEnvironmentId, threads: [ { id: parent, @@ -266,6 +277,7 @@ describe("thread relationships", () => { } as const; const graph = deriveThreadRelationshipGraph({ + environmentId: testEnvironmentId, threads: [liveChild, staleArchivedChild] as never, projection: null, }); @@ -365,6 +377,7 @@ function orderedLineageIds(input: { readonly projection?: unknown; }): ReadonlyArray { const graph = deriveThreadRelationshipGraph({ + environmentId: testEnvironmentId, threads: input.threads as never, projection: (input.projection ?? null) as never, }); diff --git a/packages/client-runtime/src/state/threadRelationships.ts b/packages/client-runtime/src/state/threadRelationships.ts index 3cb0cc8d1181..a0d38f7949c4 100644 --- a/packages/client-runtime/src/state/threadRelationships.ts +++ b/packages/client-runtime/src/state/threadRelationships.ts @@ -52,7 +52,7 @@ export function deriveThreadRelationshipGraph(input: { readonly threads: ReadonlyArray; readonly projection: ThreadStructure | null; /** Where `threads` live, so a thread launched from one of them links to its launcher. */ - readonly environmentId?: EnvironmentId; + readonly environmentId: EnvironmentId; }): ThreadRelationshipGraph { const threadsById = new Map(); for (const thread of input.threads) { From 58e950ca857de9a84f466026910a319ad3e5716e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 21 Nov 2026 16:27:04 +0100 Subject: [PATCH 125/230] docs: a launched thread's notice is best-effort and mobile lists it on its own The orchestrator MCP doc told launchers they need not wait or poll, but the notice follows the live event stream: a run that ends while the server is down sends none. It also said the sidebar nests launched threads, which now holds on web only. The doc now says both, and lists interrupted runs a queued run carries on among those without a notice. From the read-only review of the launched-thread lineage branch. --- docs/orchestration-v2/orchestrator-mcp-server.md | 13 ++++++++----- docs/progress.md | 10 ++++++++++ 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/docs/orchestration-v2/orchestrator-mcp-server.md b/docs/orchestration-v2/orchestrator-mcp-server.md index 7bfeceb20580..e9dcfab855d6 100644 --- a/docs/orchestration-v2/orchestrator-mcp-server.md +++ b/docs/orchestration-v2/orchestrator-mcp-server.md @@ -360,13 +360,16 @@ shared checkout. A thread here that launches one becomes its parent: the server stamps the new thread's `delegatedFrom` with the caller, so the parent's lineage lists it, the -sidebar nests it there, and it counts as a delegated thread +web sidebar nests it there (mobile has no lineage view, so it keeps its own row), +and it counts as a delegated thread (`isDelegatedAppThread`). Each of its runs that ends completed, failed, or interrupted sends the parent a `delegated_task` notice with the run's last reply, -steered into the parent's turn or queued to wake it, so the parent need not wait -or poll. Runs the user started in the thread, runs its own monitor woke, -cancelled runs, and archived parents get no notice. A launch from an outside -agent has no parent. +steered into the parent's turn or queued to wake it, so the parent need not +poll. The notice follows the live event stream, not the outbox: a run that ends +while the server is down sends none, so a parent that must not miss a result +still reads the thread. Runs the user started in the thread, runs its own +monitor woke, cancelled runs, interrupted runs that a queued run carries on, and +archived parents get no notice. A launch from an outside agent has no parent. Set `clientRequestId` on the initial launch to make it retryable. After an error or a lost reply, resend the same request with the same key from the same diff --git a/docs/progress.md b/docs/progress.md index 824c21cfc7b1..beaf8bfcbc5d 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -224,3 +224,13 @@ - Review: one read-only review on the second Claude account found no semantic conflicts and confirmed each call above (failover sets no `deliveryIntent`, so #39417 never queues it; a stream's failure waits for its queued snapshots, so the error item commits before `run.updated: failed`). Its one finding, Auto routing to a broken runtime, is the fix above. - Switching the hubs: migrations `101_DelegatedTaskReadIndexes` (two partial indexes) and `102_ThreadItemCounts` (a table filled from the existing counts, an index and five triggers). The app version is 0.1.11. The Node pins and the lockfile did not change. - Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Update Antigravity A and B in Antigravity setup: until they run 1.5 or newer, the server refuses them and Auto now skips them. Upstream main moved 3 commits during the sync (`f2d4df0367`: #39585, #39579, #39569); they touch none of the fork's files and go in the next sync. + +## 2026-11-21: Threads launched from a thread are listed under it and notify it + +- What: `t3_thread_launch` called from a thread here stamps the new thread's `delegatedFrom` with the caller. The web lineage panel lists launched threads, the web sidebar nests them under the launcher, and their approvals and questions roll up to the launcher's row. `LaunchedThreadNoticeReactor` sends the launcher a `delegated_task` notice when a launched thread's run ends completed, failed or interrupted, through the same steer-or-queue path delegated tasks use. +- Why: a maintainer thread that launched workers lost track of them in the UI and had to poll with `t3_thread_wait`. +- Left out on purpose: runs the user typed in the launched thread, runs its own monitor woke, cancelled runs, interrupted runs a queued run carries on, and archived launchers send no notice. A linked environment cannot name a thread here as a parent. Mobile has no lineage view, so there a launched thread keeps its own row. +- Numbers: `vp run check:changed` over 31 files: format, lint, knip, graphql, typecheck (38 packages), 231 tests in 20 files and react compiler pass. +- Real run: dev server on the worktree's seeded `.t3`, a Haiku 5.5 launcher calling `t3_thread_launch`. Before, the worker was its own sidebar row and the launcher showed nothing; after, the launcher listed it under its lineage, the sidebar nested it, and its finished run landed as a notice in the launcher's turn. Archiving the worker removed it from the launcher's lineage. +- Review: one read-only review on the second Claude account. Fixed: a user's own turns in a launched thread woke the launcher, mobile hid launched threads with no way in, interrupted-then-continued runs sent two notices, a link could name a local parent, the roll-up walked through an archived launcher, and the graph's environment was optional. Documented, not fixed: the notice follows the live event stream, so a run that ends while the server is down sends none. +- Next: Tomáš decides whether the `t3_thread_launch` tool text ("new top-level thread") should change; that needs the model evals in `evals/README.md` first. From 346e4c79fc849d4b835a1401e7474e191066e541 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 21 Nov 2026 19:39:05 +0100 Subject: [PATCH 126/230] fix(server): queued Auto runs follow the failover instance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Queued messages and unread steers kept the selection stamped while they waited, so they started on a provider that had already hit its usage limit. Auto-stamped queued runs now follow the thread's current selection at queue start and requeue; pinned selections and the autoResumeLimitedThreads gate are unchanged. Requested by Tomáš. --- .../src/orchestration-v2/Orchestrator.ts | 25 +- .../src/orchestration-v2/runtimeLayer.test.ts | 310 ++++++++++++++++++ docs/progress.md | 9 + 3 files changed, 336 insertions(+), 8 deletions(-) diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 08af1d5ecbd6..b6365150e1da 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -1025,7 +1025,8 @@ function nextQueuedRun( } // Delegated completions, monitor notifications and unpinned scheduled deliveries never choose a -// model, so a queued one runs on the thread's current pick rather than the one frozen at queue time. +// model. Auto-routed messages pick an instance at dispatch time too: a failover can move the +// thread while they wait, so they follow its current pick rather than the one frozen at queue time. function followsCurrentConversation( message: | Pick< @@ -1045,12 +1046,19 @@ function followsCurrentConversation( ); } +function queuedRunFollowsCurrent( + projection: Pick, + run: OrchestrationV2Run, +): boolean { + const message = projection.messages.find((candidate) => candidate.id === run.userMessageId); + return followsCurrentConversation(message) || isAutoModelSelection(run.modelSelection); +} + function queuedRunModelSelection( projection: Pick, run: OrchestrationV2Run, ): ModelSelection { - const message = projection.messages.find((candidate) => candidate.id === run.userMessageId); - return followsCurrentConversation(message) + return queuedRunFollowsCurrent(projection, run) ? projection.thread.modelSelection : run.modelSelection; } @@ -1061,10 +1069,7 @@ function queueTailModelSelection( ): ModelSelection { return ( queuedRunsInDeliveryOrder(projection).findLast( - (run) => - !followsCurrentConversation( - projection.messages.find((message) => message.id === run.userMessageId), - ), + (run) => !queuedRunFollowsCurrent(projection, run), )?.modelSelection ?? projection.thread.modelSelection ); } @@ -3552,6 +3557,10 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio left.afterRunOrdinal - right.afterRunOrdinal || left.item.ordinal - right.item.ordinal, ); for (const { run, message, steer, afterRunOrdinal } of placed) { + const storedSelection = steer?.modelSelection ?? run.modelSelection; + const modelSelection = isAutoModelSelection(storedSelection) + ? projection.thread.modelSelection + : storedSelection; yield* dispatchWithReceiptEffect({ type: "message.dispatch", commandId: CommandId.make(`command:unread-steer:${run.id}:${message.id}`), @@ -3559,7 +3568,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageId: message.id, steerFollowUpOfRunId: run.id, steerFollowUpAfterRunOrdinal: afterRunOrdinal, - modelSelection: steer?.modelSelection ?? run.modelSelection, + modelSelection, text: message.text, ...(message.context ? { context: message.context } : {}), attachments: message.attachments, diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 9b928dceda59..cf1de40f9c76 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -9508,6 +9508,316 @@ it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => { }), ); + it.effect("starts a queued Auto message on the instance a failover selected", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make("runtime-layer-queued-auto-failover"); + const failedSelection = { + ...modelSelection, + options: [{ id: "auto", value: "medium" }], + } satisfies ModelSelection; + const movedSelection = { + instanceId: alternateInstanceId, + model: "gpt-5.5", + options: [{ id: "auto", value: "medium" }], + } satisfies ModelSelection; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + createdBy: "user", + creationSource: "web", + projectId: ProjectId.make(`${threadId}:project`), + title: "Queued Auto failover", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + const send = (name: string, type: "start_immediately" | "queue_after_active") => + orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:${name}`), + threadId, + messageId: MessageId.make(`${threadId}:${name}`), + text: name, + attachments: [], + createdBy: "user", + creationSource: "web", + modelSelection, + dispatchMode: { type }, + }); + yield* send("active", "start_immediately"); + yield* send("queued", "queue_after_active"); + const [active, queued] = (yield* orchestrator.getThreadProjection(threadId)).runs; + assert.isDefined(active); + assert.isDefined(queued); + const thread = (yield* orchestrator.getThreadProjection(threadId)).thread; + const now = yield* DateTime.now; + // Auto routing stamps the concrete selection; supply it through events, as the router does. + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}:active-auto`), + type: "run.updated", + threadId, + runId: active.id, + providerInstanceId: active.providerInstanceId, + occurredAt: now, + payload: { ...active, modelSelection: failedSelection }, + }, + { + id: EventId.make(`${threadId}:queued-auto`), + type: "run.updated", + threadId, + runId: queued.id, + providerInstanceId: queued.providerInstanceId, + occurredAt: now, + payload: { ...queued, modelSelection: failedSelection }, + }, + { + id: EventId.make(`${threadId}:thread-auto`), + type: "thread.model-selection-updated", + threadId, + providerInstanceId: thread.providerInstanceId, + occurredAt: now, + payload: { ...thread, modelSelection: failedSelection }, + }, + ], + }); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}:error`), + type: "turn-item.updated", + threadId, + runId: active.id, + nodeId: active.rootNodeId!, + providerInstanceId: active.providerInstanceId, + occurredAt: now, + payload: { + id: TurnItemId.make(`${threadId}:error`), + type: "error", + threadId, + runId: active.id, + nodeId: active.rootNodeId, + providerThreadId: active.providerThreadId, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "failed", + title: "Usage limit", + startedAt: now, + completedAt: now, + updatedAt: now, + failure: { + class: "usage_limit", + message: "Usage limit reached", + code: "usage_limit", + retryable: null, + }, + }, + }, + { + id: EventId.make(`${threadId}:failed`), + type: "run.updated", + threadId, + runId: active.id, + providerInstanceId: active.providerInstanceId, + occurredAt: now, + payload: { + ...active, + modelSelection: failedSelection, + status: "failed", + completedAt: now, + }, + }, + ], + }); + const failedThread = (yield* orchestrator.getThreadProjection(threadId)).thread; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}:moved`), + type: "thread.model-selection-updated", + threadId, + providerInstanceId: alternateInstanceId, + occurredAt: now, + payload: { + ...failedThread, + modelSelection: movedSelection, + providerInstanceId: alternateInstanceId, + }, + }, + ], + }); + yield* orchestrator.resumeQueuedRuns; + const after = yield* orchestrator.getThreadProjection(threadId); + const started = after.runs.find((run) => run.id === queued.id); + assert.equal(started?.status, "starting"); + assert.deepEqual(started?.modelSelection, movedSelection); + }), + ); + + it.effect("requeues an unread Auto steer on the instance a failover selected", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const eventSink = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make("runtime-layer-unread-steer-auto-failover"); + const failedSelection = { + ...modelSelection, + options: [{ id: "auto", value: "medium" }], + } satisfies ModelSelection; + const movedSelection = { + instanceId: alternateInstanceId, + model: "gpt-5.5", + options: [{ id: "auto", value: "medium" }], + } satisfies ModelSelection; + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${threadId}:create`), + threadId, + createdBy: "user", + creationSource: "web", + projectId: ProjectId.make(`${threadId}:project`), + title: "Unread steer Auto failover", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + const activeId = MessageId.make(`${threadId}:active`); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:active`), + threadId, + messageId: activeId, + text: "active", + attachments: [], + createdBy: "user", + creationSource: "web", + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + const before = yield* orchestrator.getThreadProjection(threadId); + const active = before.runs.find((run) => run.userMessageId === activeId)!; + const prompt = before.turnItems.find( + (item): item is Extract<(typeof before.turnItems)[number], { type: "user_message" }> => + item.type === "user_message" && item.messageId === activeId, + )!; + const promptMessage = before.messages.find((message) => message.id === activeId)!; + const steerId = MessageId.make(`${threadId}:steer`); + const now = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}:active-auto`), + type: "run.updated", + threadId, + runId: active.id, + providerInstanceId: active.providerInstanceId, + occurredAt: now, + payload: { ...active, modelSelection: failedSelection }, + }, + { + id: EventId.make(`${threadId}:thread-auto`), + type: "thread.model-selection-updated", + threadId, + providerInstanceId: before.thread.providerInstanceId, + occurredAt: now, + payload: { ...before.thread, modelSelection: failedSelection }, + }, + ], + }); + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}:steer-message`), + type: "message.updated", + threadId, + runId: active.id, + nodeId: prompt.nodeId ?? undefined, + providerInstanceId: active.providerInstanceId, + occurredAt: now, + payload: { ...promptMessage, id: steerId, text: "unread steer" }, + }, + { + id: EventId.make(`${threadId}:steer-item`), + type: "turn-item.updated", + threadId, + runId: active.id, + nodeId: prompt.nodeId ?? undefined, + providerInstanceId: active.providerInstanceId, + occurredAt: now, + payload: { + ...prompt, + id: TurnItemId.make(`${threadId}:steer-item`), + type: "user_message" as const, + messageId: steerId, + inputIntent: "steer" as const, + status: "pending" as const, + text: "unread steer", + startedAt: null, + completedAt: null, + updatedAt: now, + }, + }, + { + id: EventId.make(`${threadId}:failed`), + type: "run.updated", + threadId, + runId: active.id, + providerInstanceId: active.providerInstanceId, + occurredAt: now, + payload: { + ...active, + modelSelection: failedSelection, + status: "failed", + completedAt: now, + }, + }, + ], + }); + const failedThread = (yield* orchestrator.getThreadProjection(threadId)).thread; + yield* eventSink.write({ + events: [ + { + id: EventId.make(`${threadId}:moved`), + type: "thread.model-selection-updated", + threadId, + providerInstanceId: alternateInstanceId, + occurredAt: now, + payload: { + ...failedThread, + modelSelection: movedSelection, + providerInstanceId: alternateInstanceId, + }, + }, + ], + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${threadId}:next`), + threadId, + messageId: MessageId.make(`${threadId}:next`), + text: "next", + attachments: [], + createdBy: "user", + creationSource: "web", + modelSelection: { instanceId: alternateInstanceId, model: "gpt-5.5" }, + dispatchMode: { type: "queue_after_active" }, + }); + const after = yield* orchestrator.getThreadProjection(threadId); + const requeued = after.runs.find((run) => run.userMessageId === steerId); + assert.isDefined(requeued); + assert.deepEqual(requeued?.modelSelection, movedSelection); + }), + ); + it.effect.each(["the reset passes", "the user resumes"] as const)( "holds a limited provider's queue through another provider's turn until %s", (release) => diff --git a/docs/progress.md b/docs/progress.md index beaf8bfcbc5d..146c895775e1 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -234,3 +234,12 @@ - Real run: dev server on the worktree's seeded `.t3`, a Haiku 5.5 launcher calling `t3_thread_launch`. Before, the worker was its own sidebar row and the launcher showed nothing; after, the launcher listed it under its lineage, the sidebar nested it, and its finished run landed as a notice in the launcher's turn. Archiving the worker removed it from the launcher's lineage. - Review: one read-only review on the second Claude account. Fixed: a user's own turns in a launched thread woke the launcher, mobile hid launched threads with no way in, interrupted-then-continued runs sent two notices, a link could name a local parent, the roll-up walked through an archived launcher, and the graph's environment was optional. Documented, not fixed: the notice follows the live event stream, so a run that ends while the server is down sends none. - Next: Tomáš decides whether the `t3_thread_launch` tool text ("new top-level thread") should change; that needs the model evals in `evals/README.md` first. + +## 2026-11-21: Queued Auto messages follow the thread's failover choice + +- What: queued messages and unread steers stamped by Auto routing now use the thread's current model selection when their run starts. `queuedRunFollowsCurrent` treats an Auto-stamped run like a delegated completion or unpinned scheduled delivery, and the unread-steer requeue reads the thread selection instead of the one frozen in the steer or run. +- Why: after an Auto usage-limit failover moves the thread to another instance, messages already in its queue and steers requeued by `requeueUnreadSteers` still started on the limited instance. Pinned, user-chosen selections stay unchanged, and the existing `autoResumeLimitedThreads` gate still decides whether Auto resumes at all. +- Fix: one helper in `Orchestrator.ts` shared by the two queue-selection paths, plus one selection override in the steer requeue. No change to routing, failover, or the queue order. +- Tests: two cases in `runtimeLayer.test.ts`, stamped through events because the test layer has no usable Auto provider. Both failed on the base (a queued run stayed `queued`; a requeued steer kept `codex` instead of `codex_alternate`) and pass with the fix. `vp run check:changed` passes all seven steps: format, lint, knip, graphql, typecheck (3 packages), 233 tests in 5 files. +- Real run: a scratch database was migrated from a read-only snapshot of the live data into the worktree's `.t3/verify` (69 MB, 5 projects). `vp run dev:server --home-dir .t3/verify` booted on port 15326 and answered an HTTP request before being stopped by the PIDs this task started. The GitHub probe in the log failed on DNS; it is unrelated to this path. No agent turn was sent. +- Next: review, commit, push, then open the PR. From 763187c3ff7913b7e8a346ed59c7c7be9d3fedda Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 21 Nov 2026 21:00:25 +0100 Subject: [PATCH 127/230] docs: record the review of the upstream sync --- docs/progress.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/progress.md b/docs/progress.md index c17647cbffdd..781bce4aedee 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -248,9 +248,9 @@ - What: upstream main `194025ef11`, 273 commits newer than the last sync base `16d40942ac` (2116 files), was merged into fork main `076c653424` with a real merge (`49de175ae0`), as in the last three syncs. Fork main stays an ancestor, so the PR merges without a force-push and the fork's commits keep their ids. Replaying the fork's commits would have meant selecting its originals out of 160 ancestors, many of them earlier replay copies; a merge is the smaller change. - Why: fork main was 273 upstream commits behind after #26. -- Conflicts: 13 files. `Orchestrator.ts`: combined comments and kept the fork's `isAutoModelSelection` selection for unread steers alongside upstream's `followsThreadSelection` omission. `ProviderTurnStartService.ts`: kept the fork's prompt fallback for sessions without native resume under upstream's `messageText` rename. `usageLimitsCopy.ts`: kept both imports. The nine web catalogs kept upstream's renamed "Open subagent" key and the fork's launched-thread key; the old "Open subagent in this chat" key became stale after upstream's rename and was removed from all nine. +- Conflicts: 13 files. `Orchestrator.ts`: combined comments and kept the fork's `isAutoModelSelection` selection for unread steers alongside upstream's `followsThreadSelection` omission. `ProviderTurnStartService.ts`: kept the fork's prompt fallback for sessions without native resume under upstream's `messageText` rename. `usageLimitsCopy.ts`: kept both imports. The nine web catalogs kept upstream's renamed "Open subagent" key and the fork's launched-thread key; the old "Open subagent in this chat" key became stale after upstream's rename and was removed from en plus the nine translations. - Fork behavior kept: the fork's diff against upstream is 95 files both before (`16d40942ac..origin/main`) and after the merge; per-file added and removed line counts match everywhere except `Orchestrator.ts` (+2/-3, the combined comment). - Numbers: `vp run check:changed upstream/main` all steps pass (43 packages, 1442 tests in 43 files, lint, knip, format, graphql, react compiler). `vp run check:changed origin/main`: every step passes except the 751-file test step, killed by the runner's 900 s timeout (an 1800 s retry also ran past this agent's shell timeout); that is a timeout under load, not a failed assertion, and CI owns the full suite. `vp run i18n:check` pass. - Real run: `vp run migrate-dev-db --base-dir .t3` seeded the worktree's own `.t3` from a read-only snapshot (67.5 MB, 5 projects, 31 threads) and applied migrations `103_IssueTrackerAdditionalScopes`, `104_ProjectionProjectsTrackedFolders` and `105_TaskFolders`. The server then booted on that data dir on port 15168, answered HTTP 302 and was stopped by the PID this task started. No agent turn was sent. -- Review: pending. +- Review: one read-only fallback review on the first Claude account (the second was at its weekly limit) found no bugs. It confirmed both conflict resolutions and each fork behavior named above. Its one nit, the catalog count in the conflicts line, is corrected here. - Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Migrations 103-105 add tracker scopes, a tracked-folders table and task folders. Recheck upstream main before the merge if it has moved during the sync. From f9d8788459085a7db29b679dc9f683eef28450b2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 21 Nov 2026 21:24:44 +0100 Subject: [PATCH 128/230] feat(server): report this machine's load and agents for the machine bar MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Each server now answers `server.getMachineStatus` with the machine it runs on: host name, platform, cores, load, CPU share, memory, swap, disk, Linux pressure (PSI), and its agents. Working agents are threads with a run that is preparing, queued, starting or running (delegated children are threads, so they count); open agents are threads whose provider session is alive without such a run. The cap comes from the new server setting `machineStatus.maxWorkingAgents` (null: memory alone decides). Reads are cached for 5 s, so several clients polling share one sample. The `machineStatus` capability tells clients which servers answer. Linux reads /proc/meminfo and /proc/pressure directly, the host's view that Hub Power and the hubs' rules use; other platforms take memory from HostResources and have no pressure or load gates. The client setting `machineBarEnabled` (default on) lets a device hide the bar. Origin: Tomáš's request for a machine bar that replaces opening Hub Power to decide where the next thread should start (brief of 2026-11-18). --- apps/server/src/auth/RpcAuthorization.ts | 1 + .../src/environment/ServerEnvironment.ts | 1 + .../src/observability/RpcInstrumentation.ts | 1 + .../resourceTelemetry/MachineStatus.test.ts | 157 +++++++++++++++ .../src/resourceTelemetry/MachineStatus.ts | 184 ++++++++++++++++++ apps/server/src/server.ts | 2 + apps/server/src/ws.test.ts | 2 + apps/server/src/ws.ts | 3 + packages/contracts/src/environment.ts | 2 + packages/contracts/src/index.ts | 1 + packages/contracts/src/machineStatus.ts | 46 +++++ packages/contracts/src/rpc.ts | 9 + packages/contracts/src/settings.ts | 17 ++ 13 files changed, 426 insertions(+) create mode 100644 apps/server/src/resourceTelemetry/MachineStatus.test.ts create mode 100644 apps/server/src/resourceTelemetry/MachineStatus.ts create mode 100644 packages/contracts/src/machineStatus.ts diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index ffe84c428a67..363de99b0e28 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -121,6 +121,7 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.serverGetProcessDiagnostics]: AuthDiagnosticsReadScope, // Thread load balancing reads host load, so it needs thread scope rather than diagnostics scope. [WS_METHODS.serverGetHostResources]: AuthOrchestrationReadScope, + [WS_METHODS.serverGetMachineStatus]: AuthOrchestrationReadScope, [WS_METHODS.serverGetProcessResourceHistory]: AuthDiagnosticsReadScope, [WS_METHODS.serverGetResourceTelemetryHistory]: AuthDiagnosticsReadScope, [WS_METHODS.serverRetryResourceTelemetry]: AuthDiagnosticsReadScope, diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index b29f9c874f12..74a339ae9101 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -254,6 +254,7 @@ export const make = Effect.gen(function* () { threadForceStop: true, environmentThemes: true, usageLimitSources: true, + machineStatus: true, providerWorkspaceSnapshotsOnDemand: true, modelCatalogRefresh: true, usagePriceOverrides: true, diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index f02f32d67e76..cf233249200a 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -95,6 +95,7 @@ const RPC_AGGREGATES = { [WS_METHODS.serverGetTraceDiagnostics]: "server", [WS_METHODS.serverGetProcessDiagnostics]: "server", [WS_METHODS.serverGetHostResources]: "server", + [WS_METHODS.serverGetMachineStatus]: "server", [WS_METHODS.serverGetProcessResourceHistory]: "server", [WS_METHODS.serverGetResourceTelemetryHistory]: "server", [WS_METHODS.serverRetryResourceTelemetry]: "server", diff --git a/apps/server/src/resourceTelemetry/MachineStatus.test.ts b/apps/server/src/resourceTelemetry/MachineStatus.test.ts new file mode 100644 index 000000000000..8e3708d2dcbf --- /dev/null +++ b/apps/server/src/resourceTelemetry/MachineStatus.test.ts @@ -0,0 +1,157 @@ +import { assert, describe, it } from "@effect/vitest"; +import * as NodeServices from "@effect/platform-node/NodeServices"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as SqlClient from "effect/sql/SqlClient"; + +import * as ServerConfig from "../config.ts"; +import * as SqlitePersistence from "../persistence/Sqlite.ts"; +import * as ServerSettings from "../serverSettings.ts"; +import * as HostResources from "./HostResources.ts"; +import * as MachineStatus from "./MachineStatus.ts"; + +const GiB = 1024 ** 3; + +const layerTest = MachineStatus.layer.pipe( + Layer.provide( + Layer.mock(HostResources.HostResources)({ + read: Effect.succeed({ + sampledAt: 0, + cpuUtilization: 0.25, + cpuCount: 4, + availableMemoryBytes: 2 * GiB, + totalMemoryBytes: 4 * GiB, + }), + }), + ), + Layer.provide(ServerSettings.layerTest({ machineStatus: { maxWorkingAgents: 2 } })), + Layer.provide(ServerConfig.layerTest(process.cwd(), { prefix: "t3-machine-status-test-" })), + Layer.provideMerge(SqlitePersistence.layerMemory), + Layer.provide(NodeServices.layer), +); + +const seed = Effect.fn("seed")(function* ( + threads: ReadonlyArray<{ + readonly id: string; + readonly minute: number; + readonly deleted?: boolean; + readonly runs?: ReadonlyArray; + /** A session status, and whether the thread is bound only through the bindings table. */ + readonly session?: { readonly status: string; readonly boundOnly?: boolean }; + }>, +) { + const sql = yield* SqlClient.SqlClient; + for (const thread of threads) { + const at = `2026-11-21T10:${String(thread.minute).padStart(2, "0")}:00.000Z`; + yield* sql` + INSERT INTO orchestration_v2_projection_threads ( + thread_id, project_id, title, default_provider, runtime_mode, interaction_mode, + created_at, updated_at, deleted_at, payload_json + ) VALUES ( + ${thread.id}, 'project', ${`Title ${thread.id}`}, 'codex', 'full-access', 'default', + ${at}, ${at}, ${thread.deleted ? at : null}, '{}' + ) + `; + for (const [ordinal, status] of (thread.runs ?? []).entries()) { + yield* sql` + INSERT INTO orchestration_v2_projection_runs ( + run_id, thread_id, ordinal, provider, provider_instance_id, status, requested_at, payload_json + ) VALUES ( + ${`${thread.id}:${ordinal}`}, ${thread.id}, ${ordinal}, 'claudeAgent', 'claudeAgent', + ${status}, ${at}, '{}' + ) + `; + } + if (thread.session) { + const sessionId = `session:${thread.id}`; + yield* sql` + INSERT INTO orchestration_v2_projection_provider_sessions ( + provider_session_id, thread_id, provider, driver, provider_instance_id, status, + updated_at, payload_json + ) VALUES ( + ${sessionId}, ${thread.session.boundOnly ? null : thread.id}, 'codex', 'codex', 'codex', + ${thread.session.status}, ${at}, '{}' + ) + `; + yield* sql` + INSERT INTO orchestration_v2_projection_provider_session_bindings (provider_session_id, thread_id) + VALUES (${sessionId}, ${thread.id}) + `; + } + } +}); + +describe("MachineStatusReader", () => { + it.effect("counts threads with an active run as working and idle live sessions as open", () => + Effect.gen(function* () { + yield* seed([ + { id: "running", minute: 1, runs: ["completed", "running", "queued"] }, + { id: "queued", minute: 2, runs: ["queued"] }, + { id: "preparing-child", minute: 3, runs: ["preparing"] }, + { id: "waiting", minute: 4, runs: ["waiting"], session: { status: "waiting" } }, + { id: "idle", minute: 5, runs: ["completed"], session: { status: "ready" } }, + { id: "bound", minute: 6, session: { status: "ready", boundOnly: true } }, + { id: "stopped", minute: 7, runs: ["completed"], session: { status: "stopped" } }, + { id: "failed", minute: 8, runs: ["failed"], session: { status: "error" } }, + { id: "deleted", minute: 9, deleted: true, runs: ["running"] }, + ]); + const status = yield* (yield* MachineStatus.MachineStatusReader).read; + + assert.deepStrictEqual( + status.agents.map(({ threadId, state, providerInstanceId }) => ({ + threadId: String(threadId), + state, + providerInstanceId: providerInstanceId === null ? null : String(providerInstanceId), + })), + [ + { threadId: "preparing-child", state: "working", providerInstanceId: "claudeAgent" }, + { threadId: "queued", state: "working", providerInstanceId: "claudeAgent" }, + { threadId: "running", state: "working", providerInstanceId: "claudeAgent" }, + { threadId: "bound", state: "open", providerInstanceId: "codex" }, + { threadId: "idle", state: "open", providerInstanceId: "codex" }, + { threadId: "waiting", state: "open", providerInstanceId: "codex" }, + ], + ); + assert.strictEqual(status.working, 3); + assert.strictEqual(status.open, 3); + assert.strictEqual(status.agents[0]?.title, "Title preparing-child"); + assert.strictEqual(status.maxWorkingAgents, 2); + assert.strictEqual(status.cpuUtilization, 0.25); + }).pipe(Effect.provide(layerTest)), + ); +}); + +describe("parseMeminfo", () => { + it("reads memory and swap in bytes", () => { + const meminfo = [ + "MemTotal: 7522760 kB", + "MemFree: 264852 kB", + "MemAvailable: 4800888 kB", + "SwapTotal: 7954428 kB", + "SwapFree: 7354428 kB", + ].join("\n"); + assert.deepStrictEqual(MachineStatus.parseMeminfo(meminfo), { + memory: { totalBytes: 7522760 * 1024, availableBytes: 4800888 * 1024 }, + swap: { totalBytes: 7954428 * 1024, usedBytes: 600000 * 1024 }, + }); + }); + + it("gives up without MemAvailable", () => { + assert.strictEqual(MachineStatus.parseMeminfo("MemTotal: 7522760 kB\n"), null); + }); +}); + +describe("parsePressure", () => { + it("reads the some line", () => { + assert.deepStrictEqual( + MachineStatus.parsePressure( + "some avg10=3.92 avg60=2.02 avg300=1.67 total=322035421\nfull avg10=3.33 avg60=1.84 avg300=1.52 total=264998880\n", + ), + { avg10: 3.92, avg60: 2.02 }, + ); + }); + + it("gives up on an empty file", () => { + assert.strictEqual(MachineStatus.parsePressure(""), null); + }); +}); diff --git a/apps/server/src/resourceTelemetry/MachineStatus.ts b/apps/server/src/resourceTelemetry/MachineStatus.ts new file mode 100644 index 000000000000..b7acb21458c9 --- /dev/null +++ b/apps/server/src/resourceTelemetry/MachineStatus.ts @@ -0,0 +1,184 @@ +// @effect-diagnostics nodeBuiltinImport:off - host name, load averages and disk space have no Effect API. +import * as NodeFSP from "node:fs/promises"; +import * as NodeOS from "node:os"; +import { + type MachineAgent, + type MachinePressure, + type MachineStatus, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import * as HostProcess from "@t3tools/shared/HostProcess"; +import * as Cache from "effect/Cache"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; +import * as Layer from "effect/Layer"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as SqlSchema from "effect/sql/SqlSchema"; + +import { ServerConfig } from "../config.ts"; +import { ServerSettingsService } from "../serverSettings.ts"; +import { HostResources } from "./HostResources.ts"; + +export class MachineStatusReader extends Context.Service< + MachineStatusReader, + { readonly read: Effect.Effect } +>()("t3/resourceTelemetry/MachineStatus/MachineStatusReader") {} + +const MAX_LISTED_AGENTS = 12; + +/** Memory and swap from `/proc/meminfo`, in bytes; null without MemTotal and MemAvailable. */ +export function parseMeminfo(meminfo: string) { + const bytes = (field: string) => { + const kib = new RegExp(`^${field}:\\s+(\\d+) kB$`, "m").exec(meminfo)?.[1]; + return kib === undefined ? null : Number(kib) * 1024; + }; + const totalBytes = bytes("MemTotal"); + const availableBytes = bytes("MemAvailable"); + if (totalBytes === null || availableBytes === null) return null; + const swapTotal = bytes("SwapTotal"); + const swapFree = bytes("SwapFree"); + return { + memory: { totalBytes, availableBytes }, + swap: + swapTotal === null || swapFree === null + ? null + : { totalBytes: swapTotal, usedBytes: Math.max(0, swapTotal - swapFree) }, + }; +} + +/** The `some` line of a `/proc/pressure/*` file. */ +export function parsePressure(text: string): MachinePressure | null { + const match = /^some avg10=(\d+(?:\.\d+)?) avg60=(\d+(?:\.\d+)?)/m.exec(text); + return match ? { avg10: Number(match[1]), avg60: Number(match[2]) } : null; +} + +const AgentRow = Schema.Struct({ + threadId: ThreadId, + title: Schema.String, + working: Schema.Number, + providerInstanceId: Schema.NullOr(Schema.String), +}); +const isProviderInstanceId = Schema.is(ProviderInstanceId); + +const make = Effect.gen(function* () { + const fs = yield* FileSystem.FileSystem; + const platform = yield* HostProcess.Platform; + const hostResources = yield* HostResources; + const settings = yield* ServerSettingsService; + const config = yield* ServerConfig; + const sql = yield* SqlClient.SqlClient; + + const readFile = (path: string) => fs.readFileString(path).pipe(Effect.orElseSucceed(() => "")); + + // Working: a run that is not waiting on the user. Open: a live session without one. + // The status list repeats the partial recovery index's predicate so SQLite can use it. + const readAgents = SqlSchema.findAll({ + Request: Schema.Void, + Result: AgentRow, + execute: () => sql` + WITH working_runs AS ( + SELECT thread_id, provider_instance_id, MIN(ordinal) + FROM orchestration_v2_projection_runs + WHERE status IN ('queued', 'preparing', 'starting', 'running', 'waiting') + AND status != 'waiting' + GROUP BY thread_id + ), + live_sessions AS ( + SELECT bindings.thread_id, sessions.provider_instance_id + FROM orchestration_v2_projection_provider_sessions AS sessions + JOIN orchestration_v2_projection_provider_session_bindings AS bindings + ON bindings.provider_session_id = sessions.provider_session_id + WHERE sessions.status NOT IN ('stopped', 'error') + UNION ALL + SELECT thread_id, provider_instance_id + FROM orchestration_v2_projection_provider_sessions + WHERE status NOT IN ('stopped', 'error') AND thread_id IS NOT NULL + ) + SELECT + threads.thread_id AS "threadId", + threads.title AS title, + runs.thread_id IS NOT NULL AS working, + COALESCE(runs.provider_instance_id, MIN(sessions.provider_instance_id)) AS "providerInstanceId" + FROM orchestration_v2_projection_threads AS threads + LEFT JOIN working_runs AS runs ON runs.thread_id = threads.thread_id + LEFT JOIN live_sessions AS sessions ON sessions.thread_id = threads.thread_id + WHERE threads.deleted_at IS NULL + AND (runs.thread_id IS NOT NULL OR sessions.thread_id IS NOT NULL) + GROUP BY threads.thread_id + ORDER BY runs.thread_id IS NULL, threads.updated_at DESC + `, + }); + + const readPressure = Effect.fn("MachineStatusReader.readPressure")(function* () { + const [cpu, memory, io] = yield* Effect.forEach(["cpu", "memory", "io"], (kind) => + Effect.map(readFile(`/proc/pressure/${kind}`), parsePressure), + ); + return cpu && memory && io ? { cpu, memory, io } : null; + }); + + const readDisk = Effect.promise(() => + NodeFSP.statfs(config.baseDir, { bigint: true }).then( + (stats) => ({ + totalBytes: Number(stats.blocks * stats.bsize), + freeBytes: Number(stats.bavail * stats.bsize), + }), + () => null, + ), + ); + + const sample = Effect.fn("MachineStatusReader.sample")(function* () { + const [host, rows, disk, current] = yield* Effect.all( + [ + hostResources.read, + readAgents(undefined).pipe(Effect.orDie), + readDisk, + settings.getSettings.pipe(Effect.orElseSucceed(() => null)), + ], + { concurrency: "unbounded" }, + ); + // /proc/meminfo is the host's view; HostResources narrows to the server's own cgroup. + const meminfo = platform === "linux" ? parseMeminfo(yield* readFile("/proc/meminfo")) : null; + const working = rows.filter((row) => row.working !== 0).length; + const agents = rows.slice(0, MAX_LISTED_AGENTS).map((row): MachineAgent => ({ + threadId: row.threadId, + title: row.title, + state: row.working !== 0 ? "working" : "open", + providerInstanceId: isProviderInstanceId(row.providerInstanceId) + ? row.providerInstanceId + : null, + })); + const [one = 0, five = 0, fifteen = 0] = NodeOS.loadavg(); + return { + hostname: NodeOS.hostname().trim() || "localhost", + platform, + sampledAt: DateTime.toEpochMillis(yield* DateTime.now), + cores: Math.max(1, NodeOS.cpus().length), + load: platform === "win32" ? null : ([one, five, fifteen] as const), + cpuUtilization: host.cpuUtilization, + memory: meminfo?.memory ?? { + totalBytes: host.totalMemoryBytes, + availableBytes: host.availableMemoryBytes, + }, + swap: meminfo?.swap ?? null, + disk, + pressure: platform === "linux" ? yield* readPressure() : null, + working, + open: rows.length - working, + maxWorkingAgents: current?.machineStatus.maxWorkingAgents ?? null, + agents, + } satisfies MachineStatus; + }); + + const cache = yield* Cache.make({ + capacity: 1, + lookup: (_key: "machine") => sample(), + timeToLive: "5 seconds", + }); + return MachineStatusReader.of({ read: Cache.get(cache, "machine") }); +}); + +export const layer = Layer.effect(MachineStatusReader, make); diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 9c1bb07bf699..ffdbf593bb5d 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -208,6 +208,7 @@ import * as DesktopAppUpdate from "./desktopUpdate/DesktopAppUpdate.ts"; import * as ServiceLauncherClient from "./cloud/serviceLauncherClient.ts"; import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; import * as HostResources from "./resourceTelemetry/HostResources.ts"; +import * as MachineStatus from "./resourceTelemetry/MachineStatus.ts"; import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; import * as TriageService from "./triage/TriageService.ts"; @@ -333,6 +334,7 @@ const layerUsage = UsageService.layer.pipe( const layerResourceDiagnostics = Layer.mergeAll( HostResources.layer, + MachineStatus.layer.pipe(Layer.provide(HostResources.layer), Layer.provide(layerServerSettings)), layerResourceTelemetry, ProcessDiagnostics.layer.pipe(Layer.provide(layerResourceTelemetry)), ProcessResourceMonitor.layer.pipe(Layer.provide(layerResourceTelemetry)), diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index e629af899c17..30f334953332 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -92,6 +92,7 @@ import * as EnvironmentAuth from "./auth/EnvironmentAuth.ts"; import * as EnvironmentTheme from "./environmentTheme.ts"; import * as GitWorkflowService from "./git/GitWorkflowService.ts"; import * as HostResources from "./resourceTelemetry/HostResources.ts"; +import * as MachineStatus from "./resourceTelemetry/MachineStatus.ts"; import * as ManagedProjectFolders from "./project/ManagedProjectFolders.ts"; import * as ScratchThreadPromotion from "./project/ScratchThreadPromotion.ts"; import * as McpAppRequests from "./mcpApps/McpAppRequests.ts"; @@ -845,6 +846,7 @@ const layerUnusedConfigRpcServices = Layer.mergeAll( Layer.mock(EnvironmentTheme.EnvironmentThemeService)({}), Layer.mock(GitWorkflowService.GitWorkflowService)({}), Layer.mock(HostResources.HostResources)({}), + Layer.mock(MachineStatus.MachineStatusReader)({}), Layer.mock(McpAppRequests.McpAppRequests)({}), Layer.mock(McpSignIn.McpSignIn)({}), Layer.mock(ModelManifest.ModelManifest)({}), diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index afa030d4d7e9..25d64eb1fc17 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -249,6 +249,7 @@ import * as ProcessDiagnostics from "./diagnostics/ProcessDiagnostics.ts"; import * as ProcessResourceMonitor from "./diagnostics/ProcessResourceMonitor.ts"; import * as ResourceTelemetry from "./resourceTelemetry/ResourceTelemetry.ts"; import * as HostResources from "./resourceTelemetry/HostResources.ts"; +import * as MachineStatus from "./resourceTelemetry/MachineStatus.ts"; import * as AnalyticsService from "./telemetry/AnalyticsService.ts"; import { commandFeatureUsage, featureUsage } from "./telemetry/FeatureUsage.ts"; import type { TelemetryOwner } from "./telemetry/Identify.ts"; @@ -1606,6 +1607,7 @@ export const layerWsRpc = ( const processDiagnostics = yield* ProcessDiagnostics.ProcessDiagnostics; const triage = yield* TriageService.TriageService; const hostResources = yield* HostResources.HostResources; + const machineStatus = yield* MachineStatus.MachineStatusReader; const processResourceMonitor = yield* ProcessResourceMonitor.ProcessResourceMonitor; const resourceTelemetry = yield* ResourceTelemetry.ResourceTelemetry; const relayClient = yield* RelayClient.RelayClient; @@ -2772,6 +2774,7 @@ export const layerWsRpc = ( }), [WS_METHODS.serverGetProcessDiagnostics]: (_input) => processDiagnostics.read, [WS_METHODS.serverGetHostResources]: (_input) => hostResources.read, + [WS_METHODS.serverGetMachineStatus]: (_input) => machineStatus.read, [WS_METHODS.serverGetProcessResourceHistory]: (input) => processResourceMonitor.readHistory(input), [WS_METHODS.serverGetResourceTelemetryHistory]: (input) => diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 34c8688316ae..f6d7bb1c04f3 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -128,6 +128,8 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ /** Every protocol-2 server sends this; older mobile builds still read it. */ environmentThemes: Schema.optionalKey(Schema.Boolean), usageLimitSources: Schema.optionalKey(Schema.Boolean), + /** Answers `server.getMachineStatus` for the machine bar. */ + machineStatus: Schema.optionalKey(Schema.Boolean), /** Honors `workspaceSnapshotsOnDemand`; older servers send every snapshot and drop them in the stream. */ providerWorkspaceSnapshotsOnDemand: Schema.optionalKey(Schema.Boolean), /** Honors `modelCatalogOnly`; older servers drop the field and probe every provider. */ diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index d7af43291a06..b32d04dccb8c 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -69,6 +69,7 @@ export * from "./usage.ts"; export * from "./scheduledTask.ts"; export * from "./worktreeMcp.ts"; export * from "./resourceTelemetry.ts"; +export * from "./machineStatus.ts"; export * from "./rpc.ts"; export * from "./worktreeSetup.ts"; export * from "./secretRequest.ts"; diff --git a/packages/contracts/src/machineStatus.ts b/packages/contracts/src/machineStatus.ts new file mode 100644 index 000000000000..5f57f22ac677 --- /dev/null +++ b/packages/contracts/src/machineStatus.ts @@ -0,0 +1,46 @@ +import * as Schema from "effect/Schema"; + +import { NonNegativeInt, PositiveInt, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { ProviderInstanceId } from "./providerInstance.ts"; + +/** Linux PSI "some" averages: the share of time (0-100) some task waited on the resource. */ +export const MachinePressure = Schema.Struct({ + avg10: Schema.Number, + avg60: Schema.Number, +}); +export type MachinePressure = typeof MachinePressure.Type; + +/** A thread with a live agent on this server: working runs first, then idle open sessions. */ +export const MachineAgent = Schema.Struct({ + threadId: ThreadId, + title: Schema.String, + state: Schema.Literals(["working", "open"]), + providerInstanceId: Schema.NullOr(ProviderInstanceId), +}); +export type MachineAgent = typeof MachineAgent.Type; + +/** What one T3 server reports about the machine it runs on, for the machine bar. */ +export const MachineStatus = Schema.Struct({ + hostname: TrimmedNonEmptyString, + platform: TrimmedNonEmptyString, + sampledAt: NonNegativeInt, + cores: PositiveInt, + /** 1, 5 and 15 minute load averages; null on Windows, which has none. */ + load: Schema.NullOr(Schema.Tuple([Schema.Number, Schema.Number, Schema.Number])), + cpuUtilization: Schema.NullOr(Schema.Number.check(Schema.isBetween({ minimum: 0, maximum: 1 }))), + memory: Schema.Struct({ totalBytes: NonNegativeInt, availableBytes: NonNegativeInt }), + swap: Schema.NullOr(Schema.Struct({ totalBytes: NonNegativeInt, usedBytes: NonNegativeInt })), + disk: Schema.NullOr(Schema.Struct({ totalBytes: NonNegativeInt, freeBytes: NonNegativeInt })), + /** Linux only; the other platforms report no pressure stall information. */ + pressure: Schema.NullOr( + Schema.Struct({ cpu: MachinePressure, memory: MachinePressure, io: MachinePressure }), + ), + /** Threads with a run preparing, queued, starting or running, delegated children included. */ + working: NonNegativeInt, + /** Threads whose agent session is alive but has no such run. */ + open: NonNegativeInt, + /** The server's `machineStatus.maxWorkingAgents`; null leaves the room to memory alone. */ + maxWorkingAgents: Schema.NullOr(PositiveInt), + agents: Schema.Array(MachineAgent), +}); +export type MachineStatus = typeof MachineStatus.Type; diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index e30bf9af2937..f66f25fd53b1 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -403,6 +403,7 @@ import { ResourceTelemetryRetryResult, ResourceTelemetrySnapshot, } from "./resourceTelemetry.ts"; +import { MachineStatus } from "./machineStatus.ts"; import { UsageLimitSourceError, ProviderConsumeResetCreditInput, @@ -605,6 +606,7 @@ export const WS_METHODS = { serverGetTraceDiagnostics: "server.getTraceDiagnostics", serverGetProcessDiagnostics: "server.getProcessDiagnostics", serverGetHostResources: "server.getHostResources", + serverGetMachineStatus: "server.getMachineStatus", serverGetProcessResourceHistory: "server.getProcessResourceHistory", serverGetResourceTelemetryHistory: "server.getResourceTelemetryHistory", serverRetryResourceTelemetry: "server.retryResourceTelemetry", @@ -1102,6 +1104,12 @@ const WsServerGetHostResourcesRpc = Rpc.make(WS_METHODS.serverGetHostResources, error: EnvironmentAuthorizationError, }); +const WsServerGetMachineStatusRpc = Rpc.make(WS_METHODS.serverGetMachineStatus, { + payload: Schema.Struct({}), + success: MachineStatus, + error: EnvironmentAuthorizationError, +}); + const WsServerGetProcessResourceHistoryRpc = Rpc.make(WS_METHODS.serverGetProcessResourceHistory, { payload: ServerProcessResourceHistoryInput, success: ServerProcessResourceHistoryResult, @@ -2443,6 +2451,7 @@ export const WsRpcGroup = RpcGroup.make( WsServerGetTraceDiagnosticsRpc, WsServerGetProcessDiagnosticsRpc, WsServerGetHostResourcesRpc, + WsServerGetMachineStatusRpc, WsServerGetProcessResourceHistoryRpc, WsServerGetResourceTelemetryHistoryRpc, WsServerRetryResourceTelemetryRpc, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index b0726b07174c..4d31c7324584 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -17,6 +17,7 @@ import { ForwardCompatibleNullable, ForwardCompatibleOptional, OmittedWhenNull, + PositiveInt, ProjectId, ThreadId, TrimmedNonEmptyString, @@ -556,6 +557,7 @@ export const ClientSettingsSchema = Schema.Struct({ Schema.withDecodingDefault(Effect.succeed({})), ), sidebarWorkingShelfEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + machineBarEnabled: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), sidebarProjectGroupingMode: SidebarProjectGroupingMode.pipe( Schema.withDecodingDefault(Effect.succeed(DEFAULT_SIDEBAR_PROJECT_GROUPING_MODE)), ), @@ -1373,6 +1375,14 @@ export const CloudSpeechCredentials = Schema.Struct({ openrouter: CloudSpeechCredential, }); +export const MachineStatusSettings = Schema.Struct({ + /** Most agents working at once that the owner allows here; null leaves it to memory alone. */ + maxWorkingAgents: Schema.NullOr(PositiveInt).pipe( + Schema.withDecodingDefault(Effect.succeed(null)), + ), +}); +export type MachineStatusSettings = typeof MachineStatusSettings.Type; + export const ServerSettings = Schema.Struct({ // Null means unmigrated; empty is authoritative and must not resurrect cleared preferences. favorites: Schema.NullOr(ModelFavorites).pipe(Schema.withDecodingDefault(Effect.succeed(null))), @@ -1400,6 +1410,9 @@ export const ServerSettings = Schema.Struct({ ), /** Holds an OS sleep inhibitor while any run is active; closing a laptop lid still sleeps it. */ keepAwakeWhileAgentsWork: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + machineStatus: MachineStatusSettings.pipe( + Schema.withDecodingDefault(Effect.succeed(Schema.decodeSync(MachineStatusSettings)({}))), + ), /** New T3 Connect device keys wait for approval from someone already trusted here. */ requireConnectDeviceApproval: Schema.Boolean.pipe( Schema.withDecodingDefault(Effect.succeed(false)), @@ -1868,6 +1881,9 @@ export const ServerSettingsPatch = Schema.Struct({ enableProviderUpdateChecks: Schema.optionalKey(Schema.Boolean), continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean), keepAwakeWhileAgentsWork: Schema.optionalKey(Schema.Boolean), + machineStatus: Schema.optionalKey( + Schema.Struct({ maxWorkingAgents: Schema.optionalKey(Schema.NullOr(PositiveInt)) }), + ), requireConnectDeviceApproval: Schema.optionalKey(Schema.Boolean), enableAgentBrowserAccess: Schema.optionalKey(Schema.Boolean), enablePreviewTunnel: Schema.optionalKey(Schema.Boolean), @@ -2122,6 +2138,7 @@ export const ClientSettingsPatch = Schema.Struct({ threadDetailsUsageEnabled: Schema.optionalKey(Schema.Boolean), threadDetailsItems: Schema.optionalKey(Schema.Record(Schema.String, Schema.Boolean)), sidebarWorkingShelfEnabled: Schema.optionalKey(Schema.Boolean), + machineBarEnabled: Schema.optionalKey(Schema.Boolean), sidebarProjectGroupingMode: Schema.optionalKey(SidebarProjectGroupingMode), sidebarProjectGroupingOverrides: Schema.optionalKey( Schema.Record(TrimmedNonEmptyString, SidebarProjectGroupingMode), From e99ce1e77098550b1ad278ea467c95b9239ca77c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 21 Nov 2026 21:25:42 +0100 Subject: [PATCH 129/230] feat(shared): agent room per machine and the next machine to use MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `machineCapacity()` ports Hub Power's `capacity()` with its constants: free memory minus a reserve (15% of RAM, at least 512 MB) over 700 MB per agent, 0 under memory pressure (PSI avg60 > 10), a busy CPU (5-minute load at 85% of the cores, or CPU PSI avg60 > 25) or IO pressure (avg10 > 50, the hubs' gate for heavy work), then capped by the machine's own agent limit. The hubs' 800 MB gate needs no branch: the reserve already leaves no room below about 1.2 GB. Windows has no load average, so its sampled CPU share stands in. `recommendNextMachine()` picks the machine with the most room; ties go to the larger share of free memory, then to list order. With nothing free it returns every reporting machine's reason. Origin: Tomáš's machine bar brief of 2026-11-18. --- packages/shared/package.json | 4 + packages/shared/src/machineCapacity.test.ts | 140 ++++++++++++++++++++ packages/shared/src/machineCapacity.ts | 97 ++++++++++++++ 3 files changed, 241 insertions(+) create mode 100644 packages/shared/src/machineCapacity.test.ts create mode 100644 packages/shared/src/machineCapacity.ts diff --git a/packages/shared/package.json b/packages/shared/package.json index 000adf64b008..3c0ab43f9d3d 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -415,6 +415,10 @@ "types": "./src/autoModel.ts", "import": "./src/autoModel.ts" }, + "./machineCapacity": { + "types": "./src/machineCapacity.ts", + "import": "./src/machineCapacity.ts" + }, "./usageLimits": { "types": "./src/usageLimits.ts", "import": "./src/usageLimits.ts" diff --git a/packages/shared/src/machineCapacity.test.ts b/packages/shared/src/machineCapacity.test.ts new file mode 100644 index 000000000000..7b611d7af34c --- /dev/null +++ b/packages/shared/src/machineCapacity.test.ts @@ -0,0 +1,140 @@ +import { describe, expect, it } from "vite-plus/test"; + +import { + machineCapacity, + recommendNextMachine, + type MachineCapacityInput, +} from "./machineCapacity.ts"; + +const MB = 1024 * 1024; +const calm = { avg10: 0, avg60: 0 }; + +function machine( + overrides: Partial & { + readonly totalMb: number; + readonly availableMb: number; + }, +): MachineCapacityInput { + const { totalMb, availableMb, ...rest } = overrides; + return { + cores: 4, + load: [0.4, 0.5, 0.6], + cpuUtilization: 0.1, + memory: { totalBytes: totalMb * MB, availableBytes: availableMb * MB }, + pressure: { cpu: calm, memory: calm, io: calm }, + working: 0, + maxWorkingAgents: null, + ...rest, + }; +} + +// hub2: 7.3 GB, 4 cores, at most 2 agents. hub: 3.2 GB on a slow disk. +const hub2 = (overrides: Partial = {}) => + machine({ totalMb: 7346, availableMb: 4688, maxWorkingAgents: 2, ...overrides }); +const hub = (availableMb: number, overrides: Partial = {}) => + machine({ totalMb: 3276, availableMb, maxWorkingAgents: 2, ...overrides }); + +describe("machineCapacity", () => { + it.each([ + // 15% of 7346 MB is above the 512 MB floor: (4688 - 1102) / 700 = 5 by memory, the cap says 1. + ["hub2 with one agent", hub2({ working: 1 }), { more: 1, limit: "cap", level: "room" }], + ["hub2 at its cap", hub2({ working: 2 }), { more: 0, limit: "cap", level: "full" }], + ["hub2 over its cap", hub2({ working: 3 }), { more: 0, limit: "cap", level: "full" }], + [ + "hub2 without a cap", + hub2({ maxWorkingAgents: null }), + { more: 5, limit: "memory", level: "room" }, + ], + // The 512 MB floor applies: (1500 - 512) / 700 = 1. + ["hub with 1.5 GB free", hub(1500), { more: 1, limit: "memory", level: "room" }], + ["hub at its memory reserve", hub(1100), { more: 0, limit: "memory", level: "full" }], + // Below the 800 MB gate for heavy work, the reserve already leaves no room. + ["hub below the heavy-work gate", hub(790), { more: 0, limit: "memory", level: "full" }], + ] as const)("%s", (_name, status, expected) => { + expect(machineCapacity(status)).toEqual(expected); + }); + + it.each([ + [ + "memory pressure over 10", + hub2({ pressure: { cpu: calm, memory: { avg10: 30, avg60: 11 }, io: calm } }), + "memoryPressure", + ], + ["a 5-minute load at 85% of the cores", hub2({ load: [3, 3.4, 2] }), "cpu"], + [ + "CPU pressure over 25", + hub2({ pressure: { cpu: { avg10: 40, avg60: 26 }, memory: calm, io: calm } }), + "cpu", + ], + [ + "IO pressure over 50", + hub2({ pressure: { cpu: calm, memory: calm, io: { avg10: 51, avg60: 20 } } }), + "io", + ], + ["a busy Windows CPU", hub2({ load: null, pressure: null, cpuUtilization: 0.9 }), "cpu"], + [ + "pressure on a machine over its cap", + hub2({ working: 3, pressure: { cpu: calm, memory: { avg10: 0, avg60: 12 }, io: calm } }), + "memoryPressure", + ], + ] as const)("leaves no room under %s", (_name, status, limit) => { + expect(machineCapacity(status)).toEqual({ more: 0, limit, level: "pressure" }); + }); + + it("skips the pressure gates where the platform reports no pressure", () => { + expect( + machineCapacity(machine({ totalMb: 16_000, availableMb: 9_000, load: null, pressure: null })), + ).toEqual({ more: 9, limit: "memory", level: "room" }); + }); +}); + +describe("recommendNextMachine", () => { + const notebook = (overrides: Partial = {}) => + machine({ totalMb: 16_000, availableMb: 9_000, maxWorkingAgents: 3, ...overrides }); + + it("picks the machine with the most room", () => { + expect( + recommendNextMachine([ + { id: "hub2", status: hub2({ working: 1 }) }, + { id: "notebook", status: notebook({ working: 1 }) }, + { id: "hub", status: hub(1500) }, + ]), + ).toEqual({ kind: "start", id: "notebook", more: 2 }); + }); + + it("breaks a tie by the share of free memory, then by order", () => { + const tied = [ + { id: "hub", status: hub(1500) }, + { id: "hub2", status: hub2({ working: 1 }) }, + { id: "notebook", status: notebook({ working: 2, memory: hub2().memory }) }, + ]; + expect(recommendNextMachine(tied)).toEqual({ kind: "start", id: "hub2", more: 1 }); + }); + + it("skips offline machines", () => { + expect( + recommendNextMachine([ + { id: "hub2", status: null }, + { id: "hub", status: hub(1500) }, + ]), + ).toEqual({ kind: "start", id: "hub", more: 1 }); + }); + + it("waits with each reason when nothing fits", () => { + expect( + recommendNextMachine([ + { id: "hub2", status: hub2({ working: 2 }) }, + { id: "notebook", status: notebook({ working: 3 }) }, + { id: "hub", status: hub(1500, { load: [4, 4, 4] }) }, + { id: "pc", status: null }, + ]), + ).toEqual({ kind: "wait", limits: ["cap", "cpu"] }); + }); + + it("waits without a reason when no machine reported", () => { + expect(recommendNextMachine([{ id: "hub2", status: null }])).toEqual({ + kind: "wait", + limits: [], + }); + }); +}); diff --git a/packages/shared/src/machineCapacity.ts b/packages/shared/src/machineCapacity.ts new file mode 100644 index 000000000000..d88d2c370adf --- /dev/null +++ b/packages/shared/src/machineCapacity.ts @@ -0,0 +1,97 @@ +import type { MachineStatus } from "@t3tools/contracts"; + +// Ported from Hub Power's `capacity()` (radys-s/hub-power, app.pyw), constants unchanged. +// Measured on hub2: an agent holds 120-400 MB, up to 0.7-1.7 GB while it builds or tests. +const MB = 1024 * 1024; +const AGENT_MEMORY_BYTES = 700 * MB; +const RESERVE_SHARE = 0.15; +const RESERVE_MIN_BYTES = 512 * MB; +// Hub Power reads PSI avg60 for memory and CPU; the IO gate is avg10, as in the hubs' rules. +const MEMORY_PRESSURE_MAX = 10; +const CPU_PRESSURE_MAX = 25; +const IO_PRESSURE_MAX = 50; +const LOAD_PER_CORE_MAX = 0.85; + +/** What sets `more`: free memory, a pressure gate, or the owner's cap. */ +export type MachineLimit = "memory" | "memoryPressure" | "cpu" | "io" | "cap"; + +export interface MachineCapacity { + /** How many more agents fit. */ + readonly more: number; + readonly limit: MachineLimit; + /** room: an agent fits; full: at the cap or the memory reserve; pressure: the machine is strained. */ + readonly level: "room" | "full" | "pressure"; +} + +export type MachineCapacityInput = Pick< + MachineStatus, + "cores" | "load" | "cpuUtilization" | "memory" | "pressure" | "working" | "maxWorkingAgents" +>; + +function pressureLimit(status: MachineCapacityInput): MachineLimit | null { + const { pressure } = status; + if (pressure !== null && pressure.memory.avg60 > MEMORY_PRESSURE_MAX) return "memoryPressure"; + // Windows has no load average; its sampled CPU share stands in for load per core. + const cpuBusy = + status.load !== null + ? status.load[1] >= status.cores * LOAD_PER_CORE_MAX + : status.cpuUtilization !== null && status.cpuUtilization >= LOAD_PER_CORE_MAX; + if (cpuBusy || (pressure !== null && pressure.cpu.avg60 > CPU_PRESSURE_MAX)) return "cpu"; + if (pressure !== null && pressure.io.avg10 > IO_PRESSURE_MAX) return "io"; + return null; +} + +export function machineCapacity(status: MachineCapacityInput): MachineCapacity { + const strained = pressureLimit(status); + if (strained !== null) return { more: 0, limit: strained, level: "pressure" }; + const { memory, maxWorkingAgents, working } = status; + const reserve = Math.max(RESERVE_MIN_BYTES, memory.totalBytes * RESERVE_SHARE); + let more = Math.max(0, Math.floor((memory.availableBytes - reserve) / AGENT_MEMORY_BYTES)); + let limit: MachineLimit = "memory"; + if (maxWorkingAgents !== null && maxWorkingAgents - working < more) { + more = Math.max(0, maxWorkingAgents - working); + limit = "cap"; + } + return { more, limit, level: more > 0 ? "room" : "full" }; +} + +export interface MachineCandidate { + readonly id: string; + /** null when the machine is offline or sent nothing. */ + readonly status: MachineCapacityInput | null; +} + +export type NextMachine = + | { readonly kind: "start"; readonly id: string; readonly more: number } + /** Nothing fits; `limits` holds each reporting machine's reason, empty when none reported. */ + | { readonly kind: "wait"; readonly limits: ReadonlyArray }; + +/** + * The machine with the most room. Ties go to the larger share of free memory, then to the + * earlier candidate. + */ +export function recommendNextMachine(candidates: ReadonlyArray): NextMachine { + let best: { readonly id: string; readonly more: number; readonly freeShare: number } | null = + null; + const limits = new Set(); + for (const { id, status } of candidates) { + if (status === null) continue; + const capacity = machineCapacity(status); + if (capacity.more === 0) { + limits.add(capacity.limit); + continue; + } + const freeShare = + status.memory.totalBytes > 0 ? status.memory.availableBytes / status.memory.totalBytes : 0; + if ( + best === null || + capacity.more > best.more || + (capacity.more === best.more && freeShare > best.freeShare) + ) { + best = { id, more: capacity.more, freeShare }; + } + } + return best === null + ? { kind: "wait", limits: [...limits] } + : { kind: "start", id: best.id, more: best.more }; +} From 2d65f8c5ffc8a1cc1b92983a81627208e5fba37d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 21 Nov 2026 21:50:26 +0100 Subject: [PATCH 130/230] feat(web): machine bar under the header MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A 22 px strip under the window's header row, across the sidebar, chat and right panel, answers where the next thread should start: - one chip per machine the client is connected to, deduped by host name: working agents over the machine's agent limit, free memory, and how many more agents fit, with a green/amber/red/grey dot (room, full, pressure, offline). Hover or click opens CPU load, memory, swap, disk, pressure, room, the agent limit and the machine's working and open agents. - each Claude account's 5-hour and weekly use, named A and B the way the Auto picker names them, amber from 90% and red at 100%. - `Next → · Auto: `, the machine with the most room and the route Auto would take there, or `Next → wait ()`. The columns' top-row headers reserve `--machine-bar-height` under themselves, which the shell sets to 22 px only from the md breakpoint and only while the bar shows, so narrow windows and phones keep their layout. The bar polls each environment every 25 s while it is mounted. Settings: General → Machine bar hides it per device; Maintenance → Agent limit sets `machineStatus.maxWorkingAgents` per server. The A/B account rule moved into `claudeAccountLetter` so the bar and the picker share it. User docs gain a Machine bar section in usage.md. Origin: Tomáš's machine bar brief of 2026-11-18 (replace opening Hub Power to see machine load and where the next thread fits). --- apps/web/src/components/AppSidebarLayout.tsx | 10 +- apps/web/src/components/ChatView.tsx | 2 +- apps/web/src/components/DiffPanelShell.tsx | 2 +- apps/web/src/components/RightPanelTabs.tsx | 2 +- .../src/components/WorkspacePageHeader.tsx | 2 +- apps/web/src/components/chat/autoRoute.ts | 12 +- .../src/components/machineBar/MachineBar.tsx | 360 ++++++++++++++++++ .../machineBar/machineBar.logic.test.ts | 97 +++++ .../components/machineBar/machineBar.logic.ts | 64 ++++ .../components/settings/SettingsPanels.tsx | 84 ++++ .../src/components/settings/settingsSearch.ts | 13 + .../src/components/sidebar/SidebarChrome.tsx | 2 +- apps/web/src/i18n/translations/de.json | 45 ++- apps/web/src/i18n/translations/en.json | 45 ++- apps/web/src/i18n/translations/es.json | 45 ++- apps/web/src/i18n/translations/fr.json | 45 ++- apps/web/src/i18n/translations/ja.json | 45 ++- apps/web/src/i18n/translations/ko.json | 45 ++- apps/web/src/i18n/translations/pt-BR.json | 45 ++- apps/web/src/i18n/translations/ru.json | 45 ++- apps/web/src/i18n/translations/sv.json | 45 ++- apps/web/src/i18n/translations/zh.json | 45 ++- apps/web/src/index.css | 2 + apps/web/src/state/machineStatus.ts | 49 +++ docs/progress.md | 9 + docs/user/usage.md | 14 + 26 files changed, 1151 insertions(+), 23 deletions(-) create mode 100644 apps/web/src/components/machineBar/MachineBar.tsx create mode 100644 apps/web/src/components/machineBar/machineBar.logic.test.ts create mode 100644 apps/web/src/components/machineBar/machineBar.logic.ts create mode 100644 apps/web/src/state/machineStatus.ts diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index c7515485662a..1daff0df2538 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -33,7 +33,9 @@ import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore"; import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; import { cn, isMacPlatform } from "../lib/utils"; import { primaryServerKeybindingsAtom } from "../state/server"; -import { useEnvironmentIdentificationMode } from "../hooks/useSettings"; +import { useClientSettings, useEnvironmentIdentificationMode } from "../hooks/useSettings"; +import { machineBarAvailableAtom } from "../state/machineStatus"; +import { MachineBar } from "./machineBar/MachineBar"; import { PanelAnimationSuppressionProvider, usePanelAnimationSettings, @@ -459,6 +461,9 @@ export function AppSidebarLayout({ ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET } : {} ) as CSSProperties; + const machineBarEnabled = useClientSettings((settings) => settings.machineBarEnabled); + const machineBarAvailable = useAtomValue(machineBarAvailableAtom); + const machineBarShown = showSidebar && machineBarEnabled && machineBarAvailable; const sidebarProviderStyle = { "--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`, "--panel-animation-duration": `${panelAnimationDurationMs}ms`, @@ -468,7 +473,7 @@ export function AppSidebarLayout({ return ( ) : null} {children} + {machineBarShown ? : null} {isElectron ? : null} diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 44b115761b31..abf6552fa4d1 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -3497,7 +3497,7 @@ export default function ChatView(props: ChatViewProps) { ref={threadPanelPopoverAnchorRef} data-chat-header className={cn( - "relative bg-background [[data-panel-animations=true]_&]:motion-safe:transition-[padding-left] [[data-panel-animations=true]_&]:motion-safe:duration-(--panel-animation-duration) [[data-panel-animations=true]_&]:motion-safe:ease-out", + "relative mb-(--machine-bar-height) bg-background [[data-panel-animations=true]_&]:motion-safe:transition-[padding-left] [[data-panel-animations=true]_&]:motion-safe:duration-(--panel-animation-duration) [[data-panel-animations=true]_&]:motion-safe:ease-out", isElectron ? cn( "drag-region flex h-[var(--workspace-topbar-height)] min-h-[var(--workspace-topbar-height)] shrink-0 items-center px-3 sm:px-5", diff --git a/apps/web/src/components/DiffPanelShell.tsx b/apps/web/src/components/DiffPanelShell.tsx index effdb04b9f06..64ef4be015d4 100644 --- a/apps/web/src/components/DiffPanelShell.tsx +++ b/apps/web/src/components/DiffPanelShell.tsx @@ -13,7 +13,7 @@ function getDiffPanelHeaderRowClassName(mode: DiffPanelMode) { "@container/diff-header flex items-center justify-between gap-2", mode === "embedded" ? "px-2" : "px-4", shouldUseDragRegion - ? "drag-region h-[var(--workspace-topbar-height)] border-b border-border wco:pr-(--workspace-native-controls-inset)" + ? "drag-region mb-(--machine-bar-height) h-[var(--workspace-topbar-height)] border-b border-border wco:pr-(--workspace-native-controls-inset)" : "flex h-10 min-h-10 shrink-0 items-center border-b border-border/60 bg-background in-data-[preview-panel-mode=inline]:mb-3 in-data-[preview-panel-mode=inline]:h-7 in-data-[preview-panel-mode=inline]:min-h-7 in-data-[preview-panel-mode=inline]:border-b-transparent", ); } diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index 57ed98c49dfc..1284a430764d 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -1480,7 +1480,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { >
candidate.slug === resolution.selection.model); if (!entry || !model) return null; - // Claude instances are named "Auto" (account A) and "Auto B"; other providers keep their name. const account = - entry.driverKind === "claudeAgent" - ? /\bB$/.test(entry.displayName) - ? "B" - : "A" - : entry.displayName; + entry.driverKind === "claudeAgent" ? claudeAccountLetter(entry.displayName) : entry.displayName; return { driverKind: entry.driverKind, label: `${getTriggerDisplayModelName(model, entry.driverKind)} (${account})`, diff --git a/apps/web/src/components/machineBar/MachineBar.tsx b/apps/web/src/components/machineBar/MachineBar.tsx new file mode 100644 index 000000000000..487fa466372b --- /dev/null +++ b/apps/web/src/components/machineBar/MachineBar.tsx @@ -0,0 +1,360 @@ +import { useAtomValue } from "@effect/atom-react"; +import { resolveProviderInstanceDisplayName } from "@t3tools/client-runtime/state/provider-instance-display"; +import type { MachineStatus, ServerProvider } from "@t3tools/contracts"; +import { type MachineLimit, recommendNextMachine } from "@t3tools/shared/machineCapacity"; +import { collectLimitAccounts } from "@t3tools/shared/usageLimits"; +import { useGT } from "gt-react"; + +import { useNowMinute } from "../../hooks/useNowMinute"; +import { cn } from "../../lib/utils"; +import { deriveProviderInstanceEntries } from "../../providerInstances"; +import { machineEnvironmentsAtom } from "../../state/machineStatus"; +import { environmentPresentations } from "../../state/presentation"; +import { describeAutoRoute } from "../chat/autoRoute"; +import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; +import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; +import { + type AccountUsage, + claudeAccountUsage, + type MachineChip, + machineChips, +} from "./machineBar.logic"; + +type Translate = ReturnType; + +const GIB = 1024 ** 3; +const EMPTY_PROVIDERS: ReadonlyArray = []; + +function gigabytes(bytes: number): string { + return `${(bytes / GIB).toLocaleString(undefined, { + minimumFractionDigits: 1, + maximumFractionDigits: 1, + })} GB`; +} + +function dotClassName(chip: MachineChip): string { + switch (chip.capacity?.level) { + case "room": + return "bg-success"; + case "full": + return "bg-warning"; + case "pressure": + return "bg-destructive"; + default: + return "bg-muted-foreground/40"; + } +} + +function limitLabel(limit: MachineLimit, gt: Translate): string { + switch (limit) { + case "cap": + return gt("agent limit reached"); + case "memory": + return gt("memory reserve reached"); + case "memoryPressure": + return gt("memory pressure"); + case "cpu": + return gt("CPU busy"); + case "io": + return gt("disk busy"); + } +} + +function waitReason(limits: ReadonlyArray, gt: Translate): string { + if (limits.length === 0) return gt("no data"); + if (limits.every((limit) => limit === "cap" || limit === "memory")) return gt("all full"); + return limits.map((limit) => limitLabel(limit, gt)).join(", "); +} + +function percentClassName(percent: number | null): string | undefined { + if (percent === null) return undefined; + if (percent >= 100) return "text-destructive"; + return percent >= 90 ? "text-warning-foreground" : undefined; +} + +function Percent({ value }: { readonly value: number | null }) { + return ( + {value === null ? "–" : Math.round(value)} + ); +} + +function AccountChip({ account }: { readonly account: AccountUsage }) { + const gt = useGT(); + const summary = gt( + "Claude {account}: {session} of the 5-hour window and {weekly} of the week used", + { + account: account.label, + session: account.session === null ? "–" : `${Math.round(account.session)}%`, + weekly: account.weekly === null ? "–" : `${Math.round(account.weekly)}%`, + }, + ); + return ( + + } + > + {account.label} + + + · + + + + {summary} + + ); +} + +function DetailRow({ label, value }: { readonly label: string; readonly value: string }) { + return ( + <> +
{label}
+
{value}
+ + ); +} + +function MachineDetails({ + chip, + status, + providers, +}: { + readonly chip: MachineChip; + readonly status: MachineStatus; + readonly providers: ReadonlyArray; +}) { + const gt = useGT(); + const capacity = chip.capacity; + const providerName = (instanceId: string) => { + const provider = providers.find((candidate) => candidate.instanceId === instanceId); + return provider ? resolveProviderInstanceDisplayName(provider) : instanceId; + }; + const cpu = [ + status.load === null + ? null + : gt("load {one} · {five} · {fifteen} on {cores} cores", { + one: status.load[0].toFixed(2), + five: status.load[1].toFixed(2), + fifteen: status.load[2].toFixed(2), + cores: status.cores, + }), + status.cpuUtilization === null + ? null + : gt("{percent}% busy", { percent: Math.round(status.cpuUtilization * 100) }), + ].filter((part) => part !== null); + return ( +
+
+ {status.hostname} + {chip.environmentLabel !== status.hostname ? ( + {chip.environmentLabel} + ) : null} +
+
+ + + {status.swap !== null && status.swap.totalBytes > 0 ? ( + + ) : null} + {status.disk !== null ? ( + + ) : null} + {status.pressure !== null ? ( + + ) : null} + {capacity !== null ? ( + 0 + ? gt("{count, plural, one {# more agent} other {# more agents}}", { + count: capacity.more, + }) + : limitLabel(capacity.limit, gt) + } + /> + ) : null} + +
+ {status.agents.length > 0 ? ( +
    + {status.agents.map((agent) => ( +
  • + + {agent.title} + + {agent.state === "working" ? gt("working") : gt("open")} + {agent.providerInstanceId === null + ? null + : ` · ${providerName(agent.providerInstanceId)}`} + +
  • + ))} + {status.working + status.open > status.agents.length ? ( +
  • + {gt("{count, plural, one {# more} other {# more}}", { + count: status.working + status.open - status.agents.length, + })} +
  • + ) : null} +
+ ) : ( +

+ {gt("No agents are open.")} +

+ )} +
+ ); +} + +function MachineChipButton({ + chip, + providers, +}: { + readonly chip: MachineChip; + readonly providers: ReadonlyArray; +}) { + const gt = useGT(); + const { status, capacity } = chip; + const summary = + status === null || capacity === null + ? gt("{machine}: offline or no data", { machine: chip.name }) + : gt( + "{machine}: {working} working, {open} open, {free} free, {more, plural, =0 {no room for more agents} one {room for # more agent} other {room for # more agents}}", + { + machine: chip.name, + working: status.working, + open: status.open, + free: gigabytes(status.memory.availableBytes), + more: capacity.more, + }, + ); + return ( + + + } + > + {chip.name} + + {status === null || capacity === null ? ( + {gt("off")} + ) : ( + + {status.maxWorkingAgents === null + ? status.working + : `${status.working}/${status.maxWorkingAgents}`} + {` · ${gigabytes(status.memory.availableBytes)} · +${capacity.more}`} + + )} + + + {status === null ? ( +

+ {gt("{machine} is offline or sent no data.", { machine: chip.name })} +

+ ) : ( + + )} +
+
+ ); +} + +/** Fixed under the window's header row; the layout reserves `--machine-bar-height` for it. */ +export function MachineBar() { + const gt = useGT(); + const now = Date.parse(useNowMinute()); + const chips = machineChips(useAtomValue(machineEnvironmentsAtom)); + const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom); + const accounts = claudeAccountUsage(collectLimitAccounts(presentations)); + const providersOf = (chip: MachineChip) => + presentations.get(chip.environmentId)?.serverConfig?.providers ?? EMPTY_PROVIDERS; + const next = recommendNextMachine(chips.map((chip) => ({ id: chip.key, status: chip.status }))); + const nextChip = next.kind === "start" ? chips.find((chip) => chip.key === next.id) : undefined; + const route = nextChip + ? describeAutoRoute({ entries: deriveProviderInstanceEntries(providersOf(nextChip)), now }) + : null; + return ( +
+
+ {chips.map((chip) => ( + + ))} +
+ {accounts.length > 0 ? ( +
+ {accounts.map((account) => ( + + ))} +
+ ) : null} +
+ {nextChip + ? route + ? gt("Next → {machine} · Auto: {model}", { + machine: nextChip.name, + model: route.label, + }) + : gt("Next → {machine}", { machine: nextChip.name }) + : gt("Next → wait ({reason})", { + reason: waitReason(next.kind === "wait" ? next.limits : [], gt), + })} +
+
+ ); +} diff --git a/apps/web/src/components/machineBar/machineBar.logic.test.ts b/apps/web/src/components/machineBar/machineBar.logic.test.ts new file mode 100644 index 000000000000..fed4c32ff88a --- /dev/null +++ b/apps/web/src/components/machineBar/machineBar.logic.test.ts @@ -0,0 +1,97 @@ +import { EnvironmentId, type MachineStatus } from "@t3tools/contracts"; +import type { LimitAccount } from "@t3tools/shared/usageLimits"; +import { describe, expect, it } from "vite-plus/test"; + +import { claudeAccountUsage, machineChips } from "./machineBar.logic"; + +const GiB = 1024 ** 3; + +function status(hostname: string, working: number): MachineStatus { + return { + hostname, + platform: "linux", + sampledAt: 0, + cores: 4, + load: [0.2, 0.3, 0.4], + cpuUtilization: 0.1, + memory: { totalBytes: 7 * GiB, availableBytes: 4 * GiB }, + swap: null, + disk: null, + pressure: null, + working, + open: 0, + maxWorkingAgents: 2, + agents: [], + }; +} + +describe("machineChips", () => { + it("gives a machine reached through two environments one chip, and an offline one its label", () => { + const chips = machineChips([ + { environmentId: EnvironmentId.make("local"), label: "This PC", status: status("hub2", 1) }, + { environmentId: EnvironmentId.make("hub2"), label: "hub2", status: status("HUB2", 0) }, + { environmentId: EnvironmentId.make("hub"), label: "hub (backup)", status: null }, + ]); + expect( + chips.map(({ name, environmentLabel, capacity }) => ({ name, environmentLabel, capacity })), + ).toEqual([ + { + name: "hub2", + environmentLabel: "This PC", + capacity: { more: 1, limit: "cap", level: "room" }, + }, + { name: "hub (backup)", environmentLabel: "hub (backup)", capacity: null }, + ]); + }); +}); + +describe("claudeAccountUsage", () => { + const account = ( + key: string, + displayName: string | null, + windows: LimitAccount["limits"]["windows"], + driver: LimitAccount["driver"] = "claudeAgent" as LimitAccount["driver"], + ): LimitAccount => ({ + key, + driver, + displayName, + email: undefined, + plan: undefined, + accentColor: undefined, + environments: [], + sourceLabel: null, + redeem: null, + limits: { checkedAt: "2026-11-21T10:00:00.000Z", windows }, + }); + + it("reads each Claude account's 5-hour and all-model weekly windows", () => { + expect( + claudeAccountUsage([ + account("b", "Auto B", [ + { id: "five_hour", kind: "session", label: "5h", usedPercent: 99.4 }, + { id: "seven_day", kind: "weekly", label: "Week", usedPercent: 19 }, + ]), + account("a", "Auto", [ + { id: "five_hour", kind: "session", label: "5h", usedPercent: 45 }, + { + id: "seven_day_fable", + kind: "weekly", + label: "Fable week", + usedPercent: 100, + modelIds: ["claude-fable-5-2"], + }, + { id: "seven_day", kind: "weekly", label: "Week", usedPercent: 60 }, + ]), + account( + "codex", + "Codex", + [{ id: "5h", kind: "session", label: "5h", usedPercent: 10 }], + "codex" as LimitAccount["driver"], + ), + ]), + ).toEqual([ + { key: "a", label: "A", session: 45, weekly: 60 }, + { key: "b", label: "B", session: 99.4, weekly: 19 }, + ]); + }); +}); diff --git a/apps/web/src/components/machineBar/machineBar.logic.ts b/apps/web/src/components/machineBar/machineBar.logic.ts new file mode 100644 index 000000000000..69ceed6393ca --- /dev/null +++ b/apps/web/src/components/machineBar/machineBar.logic.ts @@ -0,0 +1,64 @@ +import type { EnvironmentId, MachineStatus } from "@t3tools/contracts"; +import { machineCapacity, type MachineCapacity } from "@t3tools/shared/machineCapacity"; +import type { LimitAccount } from "@t3tools/shared/usageLimits"; + +import type { MachineEnvironment } from "../../state/machineStatus"; +import { claudeAccountLetter } from "../chat/autoRoute"; + +export interface MachineChip { + readonly key: string; + readonly environmentId: EnvironmentId; + readonly environmentLabel: string; + /** The host name, or the environment's label while nothing is known. */ + readonly name: string; + readonly status: MachineStatus | null; + readonly capacity: MachineCapacity | null; +} + +/** One chip per machine: environments that reach the same host share the first one's chip. */ +export function machineChips(environments: ReadonlyArray): MachineChip[] { + const chips: MachineChip[] = []; + const hosts = new Set(); + for (const { environmentId, label, status } of environments) { + const key = status === null ? `environment:${environmentId}` : status.hostname.toLowerCase(); + if (hosts.has(key)) continue; + hosts.add(key); + chips.push({ + key, + environmentId, + environmentLabel: label, + name: status?.hostname ?? label, + status, + capacity: status === null ? null : machineCapacity(status), + }); + } + return chips; +} + +export interface AccountUsage { + readonly key: string; + readonly label: string; + /** Used percent of the 5-hour window. */ + readonly session: number | null; + /** Used percent of the weekly window that covers every model. */ + readonly weekly: number | null; +} + +/** Claude accounts as the Auto picker names them: "A", and "B" for an instance named "… B". */ +export function claudeAccountUsage(accounts: ReadonlyArray): AccountUsage[] { + return accounts + .filter((account) => account.driver === "claudeAgent") + .map((account) => { + const used = (kind: "session" | "weekly") => + account.limits.windows.find( + (window) => window.kind === kind && (window.modelIds?.length ?? 0) === 0, + )?.usedPercent ?? null; + return { + key: account.key, + label: claudeAccountLetter(account.displayName ?? ""), + session: used("session"), + weekly: used("weekly"), + }; + }) + .toSorted((left, right) => left.label.localeCompare(right.label)); +} diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index 1bb40cec4d45..aa9c70c744ec 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -532,6 +532,9 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.sidebarWorkingShelfEnabled !== DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled ? [gt("Working section")] : []), + ...(settings.machineBarEnabled !== DEFAULT_UNIFIED_SETTINGS.machineBarEnabled + ? [gt("Machine bar")] + : []), ...(settings.sidebarAutoSettleAfterDays !== DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays ? [gt("Auto-settle inactive threads")] : []), @@ -605,6 +608,10 @@ export function useSettingsRestore(onRestored?: () => void) { ...(settings.keepAwakeWhileAgentsWork !== DEFAULT_UNIFIED_SETTINGS.keepAwakeWhileAgentsWork ? [gt("Keep awake while agents work")] : []), + ...(settings.machineStatus.maxWorkingAgents !== + DEFAULT_UNIFIED_SETTINGS.machineStatus.maxWorkingAgents + ? [gt("Agent limit")] + : []), ...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode ? [gt("New thread mode")] : []), @@ -723,6 +730,7 @@ export function useSettingsRestore(onRestored?: () => void) { sidebarProjectGroupingMode: DEFAULT_UNIFIED_SETTINGS.sidebarProjectGroupingMode, sidebarProjectSortOrder: DEFAULT_UNIFIED_SETTINGS.sidebarProjectSortOrder, sidebarWorkingShelfEnabled: DEFAULT_UNIFIED_SETTINGS.sidebarWorkingShelfEnabled, + machineBarEnabled: DEFAULT_UNIFIED_SETTINGS.machineBarEnabled, sidebarAutoSettleAfterDays: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleAfterDays, sidebarAutoSettleKeepPullRequests: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleKeepPullRequests, sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge, @@ -734,6 +742,7 @@ export function useSettingsRestore(onRestored?: () => void) { continueThreadsAfterServerUpdate: DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate, backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity, keepAwakeWhileAgentsWork: DEFAULT_UNIFIED_SETTINGS.keepAwakeWhileAgentsWork, + machineStatus: DEFAULT_UNIFIED_SETTINGS.machineStatus, backgroundActivityProfile: DEFAULT_UNIFIED_SETTINGS.backgroundActivityProfile, automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval, providerHealthRefreshInterval: DEFAULT_UNIFIED_SETTINGS.providerHealthRefreshInterval, @@ -969,6 +978,32 @@ export function GeneralSettingsPanel() { /> } /> + + Show a strip under the header with each connected machine's load and room for more + agents, the Claude limits, and where the next thread fits. Hidden in narrow windows. + + } + resetAction={ + settings.machineBarEnabled !== DEFAULT_UNIFIED_SETTINGS.machineBarEnabled ? ( + + updateSettings({ machineBarEnabled: DEFAULT_UNIFIED_SETTINGS.machineBarEnabled }) + } + /> + ) : null + } + control={ + updateSettings({ machineBarEnabled: Boolean(checked) })} + aria-label={gt("Machine bar")} + /> + } + /> @@ -2369,6 +2404,13 @@ export function MaintenanceSettingsPanel() { const environmentId = environment?.environmentId ?? null; const isEnvironmentScope = scope.environmentIds.length === 1 && environmentId !== null; const hasServerTargets = connectedEnvironments.length > 0; + const mixedAgentLimit = useScopedSettingsMixed(["machineStatus"]); + const agentLimitLabel = (value: string | null) => + value === null + ? gt("Mixed") + : value === "none" + ? gt("Memory only") + : gt("{count, plural, one {# agent} other {# agents}}", { count: Number(value) }); return ( @@ -2478,6 +2520,48 @@ export function MaintenanceSettingsPanel() { /> } /> + + updateSettings({ machineStatus: DEFAULT_UNIFIED_SETTINGS.machineStatus }) + } + /> + ) : null + } + control={ + + } + /> diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index a3812b2ea198..922fccdd5649 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -491,6 +491,12 @@ export const SETTINGS_SEARCH_ITEMS = [ to: "/settings/general", searchTerms: [msg("hide fold running monitoring threads inbox sidebar shelf")], }, + { + id: "machine-bar", + title: msg("Machine bar"), + to: "/settings/general", + searchTerms: [msg("machines hub power load memory agents room next thread top strip")], + }, { id: "boring-sidebar", title: msg("Boring sidebar (group by project)"), @@ -846,6 +852,13 @@ export const SETTINGS_SEARCH_ITEMS = [ scope: "environment-defaults", searchTerms: [msg("caffeinate sleep prevent stay awake power laptop lid inhibit")], }, + { + id: "machine-agent-limit", + title: msg("Agent limit"), + to: "/settings/maintenance", + scope: "environment-defaults", + searchTerms: [msg("machine bar most agents working at once cap room memory")], + }, { id: "background-activity", title: msg("Background activity"), diff --git a/apps/web/src/components/sidebar/SidebarChrome.tsx b/apps/web/src/components/sidebar/SidebarChrome.tsx index 1dbc9b9fc636..3db61717dc88 100644 --- a/apps/web/src/components/sidebar/SidebarChrome.tsx +++ b/apps/web/src/components/sidebar/SidebarChrome.tsx @@ -63,7 +63,7 @@ export const SidebarChromeHeader = memo(function SidebarChromeHeader({ return (
diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index c2c9b8f27328..2a95b39e4c50 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12477,5 +12477,48 @@ "b7df38b7d8792d78": "Leitfaden öffnen", "9e91e9a77b664e4e": "Review-Leitfaden konnte nicht gestartet werden", "d8aaf932f90429c4": "Diesen Befehl an den Anfang der Warteschlange verschieben ({shortcut})", - "425ab15036aec8a4": "Diesen Befehl an den Anfang der Warteschlange verschieben" + "425ab15036aec8a4": "Diesen Befehl an den Anfang der Warteschlange verschieben", + "2c4153283b647365": "Claude {account}: {session} des 5-Stunden-Fensters und {weekly} der Woche verbraucht", + "0ebc6d14caaaca3b": "Last {one} · {five} · {fifteen} auf {cores} Kernen", + "578c5947c810f7b9": "{percent} % ausgelastet", + "6747e56c71b28ea1": "{available} von {total} frei", + "a18e7f80abd79843": "Swap", + "80682fbe81cd10ee": "{used} von {total} belegt", + "089330a81db5deeb": "Festplatte", + "1dc5027f9ca46697": "{free} von {total} frei", + "f556e846ea9b5ab2": "Druck", + "772e9a862e998238": "CPU {cpu} % · Speicher {memory} % · E/A {io} %", + "fdfedc3ae3a80450": "Platz", + "ed9d8a331fe775a3": "{count, plural, one {# weiterer Agent} other {# weitere Agenten}}", + "3bc98a10973fa8e9": "Agent-Limit erreicht", + "f7efba3086d98403": "Speicherreserve erreicht", + "c16fd379b3e7be81": "Speicherdruck", + "07485ce61880fb5f": "CPU ausgelastet", + "f778dcc5e5efbd46": "Festplatte ausgelastet", + "23c58afe110c0352": "Agent-Limit", + "a27d19aa7504f69a": "nur Speicher", + "710aada747770581": "{working} von {limit} arbeiten", + "30a5be40eb956663": "arbeitet", + "ac2c1a39608fc635": "offen", + "8a72bdb53d14db64": "{count, plural, one {# weiterer} other {# weitere}}", + "5f2d81b15ca48b42": "Keine Agenten offen.", + "e1933d2c7497f1af": "{machine}: offline oder keine Daten", + "c8940a9ca306ec4e": "{machine}: {working} arbeiten, {open} offen, {free} frei, {more, plural, =0 {kein Platz für weitere Agenten} one {Platz für # weiteren Agenten} other {Platz für # weitere Agenten}}", + "3066798aa7701f50": "aus", + "4ab3bd1158a8b315": "{machine} ist offline oder hat keine Daten gesendet.", + "7f99aaba0befc867": "Rechner", + "9616bf1650ea9772": "Nächster → {machine} · Auto: {model}", + "719cb5b7ca0f7c16": "Nächster → {machine}", + "053131a1f8331cff": "Nächster → warten ({reason})", + "448d0003f5f1210e": "keine Daten", + "0b9c7179abb1df86": "alle voll", + "b1dc16cc5d6c600d": "Rechnerleiste", + "aa9721463ad159f3": "Rechnerleiste auf Standard zurücksetzen", + "095fbfdfa2b4ecfc": "Nur Speicher", + "df1309a7a0bba600": "{count, plural, one {# Agent} other {# Agenten}}", + "a38f78946916317b": "Die Höchstzahl an Agenten, die dieser Rechner gleichzeitig ausführen soll. Die Rechnerleiste bietet nie mehr Platz an. Bei „Nur Speicher“ entscheiden allein freier Speicher und Last.", + "2258ffb7d1a1b24f": "Agent-Limit auf Standard zurücksetzen", + "ea78dc5af6e6903a": "Zeigt unter der Kopfzeile eine Leiste mit der Last jedes verbundenen Rechners und dem Platz für weitere Agenten, den Claude-Limits und wo der nächste Thread passt. In schmalen Fenstern ausgeblendet.", + "56dafe176c45523e": "rechner maschinen hub power last speicher agenten platz nächster thread leiste oben", + "2229ac1d24096dfa": "rechnerleiste höchstens agenten gleichzeitig limit platz speicher" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 863d74f8b15b..f6a872fd90d0 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12486,5 +12486,48 @@ "b7df38b7d8792d78": "Open guide", "9e91e9a77b664e4e": "Could not start a review guide", "d8aaf932f90429c4": "Move this command to the front of the queue ({shortcut})", - "425ab15036aec8a4": "Move this command to the front of the queue" + "425ab15036aec8a4": "Move this command to the front of the queue", + "2c4153283b647365": "Claude {account}: {session} of the 5-hour window and {weekly} of the week used", + "0ebc6d14caaaca3b": "load {one} · {five} · {fifteen} on {cores} cores", + "578c5947c810f7b9": "{percent}% busy", + "6747e56c71b28ea1": "{available} free of {total}", + "a18e7f80abd79843": "Swap", + "80682fbe81cd10ee": "{used} used of {total}", + "089330a81db5deeb": "Disk", + "1dc5027f9ca46697": "{free} free of {total}", + "f556e846ea9b5ab2": "Pressure", + "772e9a862e998238": "CPU {cpu}% · memory {memory}% · IO {io}%", + "fdfedc3ae3a80450": "Room", + "ed9d8a331fe775a3": "{count, plural, one {# more agent} other {# more agents}}", + "3bc98a10973fa8e9": "agent limit reached", + "f7efba3086d98403": "memory reserve reached", + "c16fd379b3e7be81": "memory pressure", + "07485ce61880fb5f": "CPU busy", + "f778dcc5e5efbd46": "disk busy", + "23c58afe110c0352": "Agent limit", + "a27d19aa7504f69a": "memory only", + "710aada747770581": "{working} of {limit} working", + "30a5be40eb956663": "working", + "ac2c1a39608fc635": "open", + "8a72bdb53d14db64": "{count, plural, one {# more} other {# more}}", + "5f2d81b15ca48b42": "No agents are open.", + "e1933d2c7497f1af": "{machine}: offline or no data", + "c8940a9ca306ec4e": "{machine}: {working} working, {open} open, {free} free, {more, plural, =0 {no room for more agents} one {room for # more agent} other {room for # more agents}}", + "3066798aa7701f50": "off", + "4ab3bd1158a8b315": "{machine} is offline or sent no data.", + "7f99aaba0befc867": "Machines", + "9616bf1650ea9772": "Next → {machine} · Auto: {model}", + "719cb5b7ca0f7c16": "Next → {machine}", + "053131a1f8331cff": "Next → wait ({reason})", + "448d0003f5f1210e": "no data", + "0b9c7179abb1df86": "all full", + "b1dc16cc5d6c600d": "Machine bar", + "aa9721463ad159f3": "Reset machine bar to default", + "095fbfdfa2b4ecfc": "Memory only", + "df1309a7a0bba600": "{count, plural, one {# agent} other {# agents}}", + "a38f78946916317b": "The most agents this machine should run at once. The machine bar never offers more room than this. With Memory only, free memory and load alone decide.", + "2258ffb7d1a1b24f": "Reset agent limit to default", + "ea78dc5af6e6903a": "Show a strip under the header with each connected machine's load and room for more agents, the Claude limits, and where the next thread fits. Hidden in narrow windows.", + "56dafe176c45523e": "machines hub power load memory agents room next thread top strip", + "2229ac1d24096dfa": "machine bar most agents working at once cap room memory" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 7e6789eeb872..54a9e8dde471 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12472,5 +12472,48 @@ "b7df38b7d8792d78": "Abrir guía", "9e91e9a77b664e4e": "No se pudo iniciar una guía de revisión", "d8aaf932f90429c4": "Mover este comando al principio de la cola ({shortcut})", - "425ab15036aec8a4": "Mover este comando al principio de la cola" + "425ab15036aec8a4": "Mover este comando al principio de la cola", + "2c4153283b647365": "Claude {account}: {session} de la ventana de 5 horas y {weekly} de la semana usados", + "0ebc6d14caaaca3b": "carga {one} · {five} · {fifteen} en {cores} núcleos", + "578c5947c810f7b9": "{percent} % ocupado", + "6747e56c71b28ea1": "{available} libres de {total}", + "a18e7f80abd79843": "Swap", + "80682fbe81cd10ee": "{used} usados de {total}", + "089330a81db5deeb": "Disco", + "1dc5027f9ca46697": "{free} libres de {total}", + "f556e846ea9b5ab2": "Presión", + "772e9a862e998238": "CPU {cpu} % · memoria {memory} % · E/S {io} %", + "fdfedc3ae3a80450": "Espacio", + "ed9d8a331fe775a3": "{count, plural, one {# agente más} other {# agentes más}}", + "3bc98a10973fa8e9": "límite de agentes alcanzado", + "f7efba3086d98403": "reserva de memoria alcanzada", + "c16fd379b3e7be81": "presión de memoria", + "07485ce61880fb5f": "CPU ocupada", + "f778dcc5e5efbd46": "disco ocupado", + "23c58afe110c0352": "Límite de agentes", + "a27d19aa7504f69a": "solo memoria", + "710aada747770581": "{working} de {limit} trabajando", + "30a5be40eb956663": "trabajando", + "ac2c1a39608fc635": "abierto", + "8a72bdb53d14db64": "{count, plural, one {# más} other {# más}}", + "5f2d81b15ca48b42": "No hay agentes abiertos.", + "e1933d2c7497f1af": "{machine}: sin conexión o sin datos", + "c8940a9ca306ec4e": "{machine}: {working} trabajando, {open} abiertos, {free} libres, {more, plural, =0 {sin espacio para más agentes} one {espacio para # agente más} other {espacio para # agentes más}}", + "3066798aa7701f50": "apagado", + "4ab3bd1158a8b315": "{machine} está sin conexión o no envió datos.", + "7f99aaba0befc867": "Máquinas", + "9616bf1650ea9772": "Siguiente → {machine} · Auto: {model}", + "719cb5b7ca0f7c16": "Siguiente → {machine}", + "053131a1f8331cff": "Siguiente → esperar ({reason})", + "448d0003f5f1210e": "sin datos", + "0b9c7179abb1df86": "todas llenas", + "b1dc16cc5d6c600d": "Barra de máquinas", + "aa9721463ad159f3": "Restablecer la barra de máquinas al valor predeterminado", + "095fbfdfa2b4ecfc": "Solo memoria", + "df1309a7a0bba600": "{count, plural, one {# agente} other {# agentes}}", + "a38f78946916317b": "El máximo de agentes que esta máquina debe ejecutar a la vez. La barra de máquinas nunca ofrece más espacio que esto. Con Solo memoria, deciden solo la memoria libre y la carga.", + "2258ffb7d1a1b24f": "Restablecer el límite de agentes al valor predeterminado", + "ea78dc5af6e6903a": "Muestra una franja bajo la cabecera con la carga de cada máquina conectada y el espacio para más agentes, los límites de Claude y dónde cabe el siguiente hilo. Se oculta en ventanas estrechas.", + "56dafe176c45523e": "máquinas hub power carga memoria agentes espacio siguiente hilo franja superior", + "2229ac1d24096dfa": "barra de máquinas máximo agentes a la vez límite espacio memoria" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index c33ddf62cd52..bd7216c25030 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12477,5 +12477,48 @@ "b7df38b7d8792d78": "Ouvrir le guide", "9e91e9a77b664e4e": "Impossible de démarrer un guide de revue", "d8aaf932f90429c4": "Placer cette commande en tête de la file d’attente ({shortcut})", - "425ab15036aec8a4": "Placer cette commande en tête de la file d’attente" + "425ab15036aec8a4": "Placer cette commande en tête de la file d’attente", + "2c4153283b647365": "Claude {account} : {session} de la fenêtre de 5 heures et {weekly} de la semaine utilisés", + "0ebc6d14caaaca3b": "charge {one} · {five} · {fifteen} sur {cores} cœurs", + "578c5947c810f7b9": "{percent} % occupé", + "6747e56c71b28ea1": "{available} libres sur {total}", + "a18e7f80abd79843": "Swap", + "80682fbe81cd10ee": "{used} utilisés sur {total}", + "089330a81db5deeb": "Disque", + "1dc5027f9ca46697": "{free} libres sur {total}", + "f556e846ea9b5ab2": "Pression", + "772e9a862e998238": "CPU {cpu} % · mémoire {memory} % · E/S {io} %", + "fdfedc3ae3a80450": "Place", + "ed9d8a331fe775a3": "{count, plural, one {# agent de plus} other {# agents de plus}}", + "3bc98a10973fa8e9": "limite d'agents atteinte", + "f7efba3086d98403": "réserve de mémoire atteinte", + "c16fd379b3e7be81": "pression mémoire", + "07485ce61880fb5f": "CPU occupé", + "f778dcc5e5efbd46": "disque occupé", + "23c58afe110c0352": "Limite d'agents", + "a27d19aa7504f69a": "mémoire seulement", + "710aada747770581": "{working} sur {limit} au travail", + "30a5be40eb956663": "au travail", + "ac2c1a39608fc635": "ouvert", + "8a72bdb53d14db64": "{count, plural, one {# de plus} other {# de plus}}", + "5f2d81b15ca48b42": "Aucun agent ouvert.", + "e1933d2c7497f1af": "{machine} : hors ligne ou sans données", + "c8940a9ca306ec4e": "{machine} : {working} au travail, {open} ouverts, {free} libres, {more, plural, =0 {plus de place pour d'autres agents} one {place pour # agent de plus} other {place pour # agents de plus}}", + "3066798aa7701f50": "éteint", + "4ab3bd1158a8b315": "{machine} est hors ligne ou n'a envoyé aucune donnée.", + "7f99aaba0befc867": "Machines", + "9616bf1650ea9772": "Suivant → {machine} · Auto : {model}", + "719cb5b7ca0f7c16": "Suivant → {machine}", + "053131a1f8331cff": "Suivant → attendre ({reason})", + "448d0003f5f1210e": "aucune donnée", + "0b9c7179abb1df86": "toutes pleines", + "b1dc16cc5d6c600d": "Barre des machines", + "aa9721463ad159f3": "Réinitialiser la barre des machines à la valeur par défaut", + "095fbfdfa2b4ecfc": "Mémoire seulement", + "df1309a7a0bba600": "{count, plural, one {# agent} other {# agents}}", + "a38f78946916317b": "Le nombre maximal d'agents que cette machine doit exécuter en même temps. La barre des machines n'offre jamais plus de place. Avec Mémoire seulement, seules la mémoire libre et la charge décident.", + "2258ffb7d1a1b24f": "Réinitialiser la limite d'agents à la valeur par défaut", + "ea78dc5af6e6903a": "Affiche sous l'en-tête une bande avec la charge de chaque machine connectée et la place pour d'autres agents, les limites de Claude et l'endroit où le prochain fil a sa place. Masquée dans les fenêtres étroites.", + "56dafe176c45523e": "machines hub power charge mémoire agents place prochain fil bande haut", + "2229ac1d24096dfa": "barre des machines maximum agents en même temps limite place mémoire" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index b3c9f49c888b..a7cba33eebdd 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12426,5 +12426,48 @@ "b7df38b7d8792d78": "ガイドを開く", "9e91e9a77b664e4e": "レビューガイドを開始できませんでした", "d8aaf932f90429c4": "このコマンドをキューの先頭に移動 ({shortcut})", - "425ab15036aec8a4": "このコマンドをキューの先頭に移動" + "425ab15036aec8a4": "このコマンドをキューの先頭に移動", + "2c4153283b647365": "Claude {account}: 5時間枠の{session}、週間枠の{weekly}を使用済み", + "0ebc6d14caaaca3b": "負荷 {one} · {five} · {fifteen}({cores} コア)", + "578c5947c810f7b9": "使用率 {percent}%", + "6747e56c71b28ea1": "{total} 中 {available} 空き", + "a18e7f80abd79843": "スワップ", + "80682fbe81cd10ee": "{total} 中 {used} 使用", + "089330a81db5deeb": "ディスク", + "1dc5027f9ca46697": "{total} 中 {free} 空き", + "f556e846ea9b5ab2": "プレッシャー", + "772e9a862e998238": "CPU {cpu}% · メモリ {memory}% · IO {io}%", + "fdfedc3ae3a80450": "余裕", + "ed9d8a331fe775a3": "{count, plural, other {あと # エージェント}}", + "3bc98a10973fa8e9": "エージェント上限に到達", + "f7efba3086d98403": "メモリ予備量に到達", + "c16fd379b3e7be81": "メモリ逼迫", + "07485ce61880fb5f": "CPU 高負荷", + "f778dcc5e5efbd46": "ディスク高負荷", + "23c58afe110c0352": "エージェント上限", + "a27d19aa7504f69a": "メモリのみ", + "710aada747770581": "{limit} 中 {working} が作業中", + "30a5be40eb956663": "作業中", + "ac2c1a39608fc635": "待機中", + "8a72bdb53d14db64": "{count, plural, other {他 # 件}}", + "5f2d81b15ca48b42": "開いているエージェントはありません。", + "e1933d2c7497f1af": "{machine}: オフラインまたはデータなし", + "c8940a9ca306ec4e": "{machine}: 作業中 {working}、待機中 {open}、空き {free}、{more, plural, =0 {これ以上エージェントを追加できません} other {あと # エージェント追加可能}}", + "3066798aa7701f50": "オフ", + "4ab3bd1158a8b315": "{machine} はオフラインか、データを送信していません。", + "7f99aaba0befc867": "マシン", + "9616bf1650ea9772": "次 → {machine} · Auto: {model}", + "719cb5b7ca0f7c16": "次 → {machine}", + "053131a1f8331cff": "次 → 待機({reason})", + "448d0003f5f1210e": "データなし", + "0b9c7179abb1df86": "すべて満杯", + "b1dc16cc5d6c600d": "マシンバー", + "aa9721463ad159f3": "マシンバーをデフォルトにリセット", + "095fbfdfa2b4ecfc": "メモリのみ", + "df1309a7a0bba600": "{count, plural, other {# エージェント}}", + "a38f78946916317b": "このマシンで同時に実行するエージェントの最大数です。マシンバーはこれを超える余裕を示しません。「メモリのみ」では、空きメモリと負荷だけで判断します。", + "2258ffb7d1a1b24f": "エージェント上限をデフォルトにリセット", + "ea78dc5af6e6903a": "ヘッダーの下に、接続中の各マシンの負荷と追加できるエージェント数、Claude の上限、次のスレッドを始められる場所を表示します。幅の狭いウィンドウでは非表示です。", + "56dafe176c45523e": "マシン hub power 負荷 メモリ エージェント 余裕 次 スレッド 上部 バー", + "2229ac1d24096dfa": "マシンバー 最大 エージェント 同時 上限 余裕 メモリ" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 31e4cb8c96a6..436ed5563b65 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12421,5 +12421,48 @@ "b7df38b7d8792d78": "가이드 열기", "9e91e9a77b664e4e": "검토 가이드를 시작할 수 없습니다", "d8aaf932f90429c4": "이 명령을 대기열 맨 앞으로 이동 ({shortcut})", - "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동" + "425ab15036aec8a4": "이 명령을 대기열 맨 앞으로 이동", + "2c4153283b647365": "Claude {account}: 5시간 창의 {session}, 주간 한도의 {weekly} 사용", + "0ebc6d14caaaca3b": "부하 {one} · {five} · {fifteen} ({cores}코어)", + "578c5947c810f7b9": "사용률 {percent}%", + "6747e56c71b28ea1": "{total} 중 {available} 여유", + "a18e7f80abd79843": "스왑", + "80682fbe81cd10ee": "{total} 중 {used} 사용", + "089330a81db5deeb": "디스크", + "1dc5027f9ca46697": "{total} 중 {free} 여유", + "f556e846ea9b5ab2": "압력", + "772e9a862e998238": "CPU {cpu}% · 메모리 {memory}% · IO {io}%", + "fdfedc3ae3a80450": "여유", + "ed9d8a331fe775a3": "{count, plural, other {에이전트 #개 더}}", + "3bc98a10973fa8e9": "에이전트 한도 도달", + "f7efba3086d98403": "메모리 예비량 도달", + "c16fd379b3e7be81": "메모리 압박", + "07485ce61880fb5f": "CPU 사용 중", + "f778dcc5e5efbd46": "디스크 사용 중", + "23c58afe110c0352": "에이전트 한도", + "a27d19aa7504f69a": "메모리만", + "710aada747770581": "{limit}개 중 {working}개 작업 중", + "30a5be40eb956663": "작업 중", + "ac2c1a39608fc635": "대기 중", + "8a72bdb53d14db64": "{count, plural, other {외 #개}}", + "5f2d81b15ca48b42": "열려 있는 에이전트가 없습니다.", + "e1933d2c7497f1af": "{machine}: 오프라인 또는 데이터 없음", + "c8940a9ca306ec4e": "{machine}: 작업 중 {working}, 대기 중 {open}, 여유 {free}, {more, plural, =0 {에이전트를 더 추가할 여유 없음} other {에이전트 #개 더 추가 가능}}", + "3066798aa7701f50": "꺼짐", + "4ab3bd1158a8b315": "{machine}이(가) 오프라인이거나 데이터를 보내지 않았습니다.", + "7f99aaba0befc867": "머신", + "9616bf1650ea9772": "다음 → {machine} · Auto: {model}", + "719cb5b7ca0f7c16": "다음 → {machine}", + "053131a1f8331cff": "다음 → 대기 ({reason})", + "448d0003f5f1210e": "데이터 없음", + "0b9c7179abb1df86": "모두 가득 참", + "b1dc16cc5d6c600d": "머신 바", + "aa9721463ad159f3": "머신 바 기본값으로 재설정", + "095fbfdfa2b4ecfc": "메모리만", + "df1309a7a0bba600": "{count, plural, other {에이전트 #개}}", + "a38f78946916317b": "이 머신에서 동시에 실행할 최대 에이전트 수입니다. 머신 바는 이보다 많은 여유를 표시하지 않습니다. '메모리만'을 선택하면 여유 메모리와 부하만으로 판단합니다.", + "2258ffb7d1a1b24f": "에이전트 한도 기본값으로 재설정", + "ea78dc5af6e6903a": "헤더 아래에 연결된 각 머신의 부하와 추가 에이전트 여유, Claude 한도, 다음 스레드를 시작할 위치를 보여 줍니다. 좁은 창에서는 숨겨집니다.", + "56dafe176c45523e": "머신 hub power 부하 메모리 에이전트 여유 다음 스레드 상단 바", + "2229ac1d24096dfa": "머신 바 최대 에이전트 동시 한도 여유 메모리" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index e410c03f5aba..38a8de480408 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12477,5 +12477,48 @@ "b7df38b7d8792d78": "Abrir guia", "9e91e9a77b664e4e": "Não foi possível iniciar um guia de revisão", "d8aaf932f90429c4": "Mover este comando para o início da fila ({shortcut})", - "425ab15036aec8a4": "Mover este comando para o início da fila" + "425ab15036aec8a4": "Mover este comando para o início da fila", + "2c4153283b647365": "Claude {account}: {session} da janela de 5 horas e {weekly} da semana usados", + "0ebc6d14caaaca3b": "carga {one} · {five} · {fifteen} em {cores} núcleos", + "578c5947c810f7b9": "{percent}% ocupado", + "6747e56c71b28ea1": "{available} livres de {total}", + "a18e7f80abd79843": "Swap", + "80682fbe81cd10ee": "{used} usados de {total}", + "089330a81db5deeb": "Disco", + "1dc5027f9ca46697": "{free} livres de {total}", + "f556e846ea9b5ab2": "Pressão", + "772e9a862e998238": "CPU {cpu}% · memória {memory}% · E/S {io}%", + "fdfedc3ae3a80450": "Espaço", + "ed9d8a331fe775a3": "{count, plural, one {mais # agente} other {mais # agentes}}", + "3bc98a10973fa8e9": "limite de agentes atingido", + "f7efba3086d98403": "reserva de memória atingida", + "c16fd379b3e7be81": "pressão de memória", + "07485ce61880fb5f": "CPU ocupada", + "f778dcc5e5efbd46": "disco ocupado", + "23c58afe110c0352": "Limite de agentes", + "a27d19aa7504f69a": "apenas memória", + "710aada747770581": "{working} de {limit} trabalhando", + "30a5be40eb956663": "trabalhando", + "ac2c1a39608fc635": "aberto", + "8a72bdb53d14db64": "{count, plural, one {mais #} other {mais #}}", + "5f2d81b15ca48b42": "Nenhum agente aberto.", + "e1933d2c7497f1af": "{machine}: offline ou sem dados", + "c8940a9ca306ec4e": "{machine}: {working} trabalhando, {open} abertos, {free} livres, {more, plural, =0 {sem espaço para mais agentes} one {espaço para mais # agente} other {espaço para mais # agentes}}", + "3066798aa7701f50": "desligado", + "4ab3bd1158a8b315": "{machine} está offline ou não enviou dados.", + "7f99aaba0befc867": "Máquinas", + "9616bf1650ea9772": "Próximo → {machine} · Auto: {model}", + "719cb5b7ca0f7c16": "Próximo → {machine}", + "053131a1f8331cff": "Próximo → aguardar ({reason})", + "448d0003f5f1210e": "sem dados", + "0b9c7179abb1df86": "todas cheias", + "b1dc16cc5d6c600d": "Barra de máquinas", + "aa9721463ad159f3": "Redefinir a barra de máquinas para o padrão", + "095fbfdfa2b4ecfc": "Apenas memória", + "df1309a7a0bba600": "{count, plural, one {# agente} other {# agentes}}", + "a38f78946916317b": "O máximo de agentes que esta máquina deve executar ao mesmo tempo. A barra de máquinas nunca oferece mais espaço que isso. Com Apenas memória, só a memória livre e a carga decidem.", + "2258ffb7d1a1b24f": "Redefinir o limite de agentes para o padrão", + "ea78dc5af6e6903a": "Mostra uma faixa abaixo do cabeçalho com a carga de cada máquina conectada e o espaço para mais agentes, os limites do Claude e onde cabe a próxima thread. Oculta em janelas estreitas.", + "56dafe176c45523e": "máquinas hub power carga memória agentes espaço próxima thread faixa superior", + "2229ac1d24096dfa": "barra de máquinas máximo agentes ao mesmo tempo limite espaço memória" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 1fb106a73b42..0e6b046929b3 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12477,5 +12477,48 @@ "b7df38b7d8792d78": "Открыть гид", "9e91e9a77b664e4e": "Не удалось запустить гид по ревью", "d8aaf932f90429c4": "Переместить эту команду в начало очереди ({shortcut})", - "425ab15036aec8a4": "Переместить эту команду в начало очереди" + "425ab15036aec8a4": "Переместить эту команду в начало очереди", + "2c4153283b647365": "Claude {account}: использовано {session} 5-часового окна и {weekly} недельного лимита", + "0ebc6d14caaaca3b": "нагрузка {one} · {five} · {fifteen} на {cores} ядрах", + "578c5947c810f7b9": "занято {percent}%", + "6747e56c71b28ea1": "свободно {available} из {total}", + "a18e7f80abd79843": "Подкачка", + "80682fbe81cd10ee": "использовано {used} из {total}", + "089330a81db5deeb": "Диск", + "1dc5027f9ca46697": "свободно {free} из {total}", + "f556e846ea9b5ab2": "Давление", + "772e9a862e998238": "ЦП {cpu}% · память {memory}% · ввод-вывод {io}%", + "fdfedc3ae3a80450": "Запас", + "ed9d8a331fe775a3": "{count, plural, one {ещё # агент} few {ещё # агента} many {ещё # агентов} other {ещё # агента}}", + "3bc98a10973fa8e9": "достигнут лимит агентов", + "f7efba3086d98403": "достигнут резерв памяти", + "c16fd379b3e7be81": "нехватка памяти", + "07485ce61880fb5f": "ЦП занят", + "f778dcc5e5efbd46": "диск занят", + "23c58afe110c0352": "Лимит агентов", + "a27d19aa7504f69a": "только память", + "710aada747770581": "работают {working} из {limit}", + "30a5be40eb956663": "работает", + "ac2c1a39608fc635": "открыт", + "8a72bdb53d14db64": "{count, plural, one {ещё #} few {ещё #} many {ещё #} other {ещё #}}", + "5f2d81b15ca48b42": "Открытых агентов нет.", + "e1933d2c7497f1af": "{machine}: не в сети или нет данных", + "c8940a9ca306ec4e": "{machine}: работают {working}, открыто {open}, свободно {free}, {more, plural, =0 {нет места для новых агентов} one {место ещё для # агента} few {место ещё для # агентов} many {место ещё для # агентов} other {место ещё для # агента}}", + "3066798aa7701f50": "выкл.", + "4ab3bd1158a8b315": "{machine} не в сети или не прислал данных.", + "7f99aaba0befc867": "Машины", + "9616bf1650ea9772": "Дальше → {machine} · Auto: {model}", + "719cb5b7ca0f7c16": "Дальше → {machine}", + "053131a1f8331cff": "Дальше → подождать ({reason})", + "448d0003f5f1210e": "нет данных", + "0b9c7179abb1df86": "все заняты", + "b1dc16cc5d6c600d": "Панель машин", + "aa9721463ad159f3": "Сбросить панель машин к значению по умолчанию", + "095fbfdfa2b4ecfc": "Только память", + "df1309a7a0bba600": "{count, plural, one {# агент} few {# агента} many {# агентов} other {# агента}}", + "a38f78946916317b": "Сколько агентов эта машина может запускать одновременно. Панель машин никогда не предлагает больше места. При «Только память» решают только свободная память и нагрузка.", + "2258ffb7d1a1b24f": "Сбросить лимит агентов к значению по умолчанию", + "ea78dc5af6e6903a": "Показывает под заголовком полосу с нагрузкой каждой подключённой машины и местом для новых агентов, лимитами Claude и тем, где поместится следующий тред. Скрыта в узких окнах.", + "56dafe176c45523e": "машины hub power нагрузка память агенты место следующий тред полоса сверху", + "2229ac1d24096dfa": "панель машин максимум агентов одновременно лимит место память" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index c748d1d9ae57..ff57ddd4e088 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12484,5 +12484,48 @@ "b7df38b7d8792d78": "Öppna guiden", "9e91e9a77b664e4e": "Kunde inte starta en granskningsguide", "d8aaf932f90429c4": "Flytta det här kommandot först i kön ({shortcut})", - "425ab15036aec8a4": "Flytta det här kommandot först i kön" + "425ab15036aec8a4": "Flytta det här kommandot först i kön", + "2c4153283b647365": "Claude {account}: {session} av 5-timmarsfönstret och {weekly} av veckan använt", + "0ebc6d14caaaca3b": "last {one} · {five} · {fifteen} på {cores} kärnor", + "578c5947c810f7b9": "{percent} % upptagen", + "6747e56c71b28ea1": "{available} ledigt av {total}", + "a18e7f80abd79843": "Swap", + "80682fbe81cd10ee": "{used} använt av {total}", + "089330a81db5deeb": "Disk", + "1dc5027f9ca46697": "{free} ledigt av {total}", + "f556e846ea9b5ab2": "Tryck", + "772e9a862e998238": "CPU {cpu} % · minne {memory} % · IO {io} %", + "fdfedc3ae3a80450": "Utrymme", + "ed9d8a331fe775a3": "{count, plural, one {# agent till} other {# agenter till}}", + "3bc98a10973fa8e9": "agentgränsen nådd", + "f7efba3086d98403": "minnesreserven nådd", + "c16fd379b3e7be81": "minnestryck", + "07485ce61880fb5f": "CPU upptagen", + "f778dcc5e5efbd46": "disken upptagen", + "23c58afe110c0352": "Agentgräns", + "a27d19aa7504f69a": "endast minne", + "710aada747770581": "{working} av {limit} arbetar", + "30a5be40eb956663": "arbetar", + "ac2c1a39608fc635": "öppen", + "8a72bdb53d14db64": "{count, plural, one {# till} other {# till}}", + "5f2d81b15ca48b42": "Inga agenter är öppna.", + "e1933d2c7497f1af": "{machine}: offline eller inga data", + "c8940a9ca306ec4e": "{machine}: {working} arbetar, {open} öppna, {free} ledigt, {more, plural, =0 {inget utrymme för fler agenter} one {utrymme för # agent till} other {utrymme för # agenter till}}", + "3066798aa7701f50": "av", + "4ab3bd1158a8b315": "{machine} är offline eller har inte skickat några data.", + "7f99aaba0befc867": "Datorer", + "9616bf1650ea9772": "Nästa → {machine} · Auto: {model}", + "719cb5b7ca0f7c16": "Nästa → {machine}", + "053131a1f8331cff": "Nästa → vänta ({reason})", + "448d0003f5f1210e": "inga data", + "0b9c7179abb1df86": "alla fulla", + "b1dc16cc5d6c600d": "Datorfält", + "aa9721463ad159f3": "Återställ datorfältet till standard", + "095fbfdfa2b4ecfc": "Endast minne", + "df1309a7a0bba600": "{count, plural, one {# agent} other {# agenter}}", + "a38f78946916317b": "Det högsta antalet agenter som den här datorn ska köra samtidigt. Datorfältet erbjuder aldrig mer utrymme än så. Med Endast minne avgör bara ledigt minne och last.", + "2258ffb7d1a1b24f": "Återställ agentgränsen till standard", + "ea78dc5af6e6903a": "Visar en remsa under rubrikraden med varje ansluten dators last och utrymme för fler agenter, Claude-gränserna och var nästa tråd får plats. Dold i smala fönster.", + "56dafe176c45523e": "datorer hub power last minne agenter utrymme nästa tråd remsa överst", + "2229ac1d24096dfa": "datorfält högst agenter samtidigt gräns utrymme minne" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 0e3984a2c10f..28477890cf3d 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12503,5 +12503,48 @@ "b7df38b7d8792d78": "打开导览", "9e91e9a77b664e4e": "无法开始生成审查导览", "d8aaf932f90429c4": "将此命令移到队列最前面 ({shortcut})", - "425ab15036aec8a4": "将此命令移到队列最前面" + "425ab15036aec8a4": "将此命令移到队列最前面", + "2c4153283b647365": "Claude {account}:已用 5 小时窗口的 {session},本周额度的 {weekly}", + "0ebc6d14caaaca3b": "负载 {one} · {five} · {fifteen}({cores} 核)", + "578c5947c810f7b9": "占用 {percent}%", + "6747e56c71b28ea1": "{total} 中可用 {available}", + "a18e7f80abd79843": "交换空间", + "80682fbe81cd10ee": "{total} 中已用 {used}", + "089330a81db5deeb": "磁盘", + "1dc5027f9ca46697": "{total} 中可用 {free}", + "f556e846ea9b5ab2": "压力", + "772e9a862e998238": "CPU {cpu}% · 内存 {memory}% · IO {io}%", + "fdfedc3ae3a80450": "余量", + "ed9d8a331fe775a3": "{count, plural, other {还可再开 # 个智能体}}", + "3bc98a10973fa8e9": "已达智能体上限", + "f7efba3086d98403": "已达内存预留", + "c16fd379b3e7be81": "内存紧张", + "07485ce61880fb5f": "CPU 繁忙", + "f778dcc5e5efbd46": "磁盘繁忙", + "23c58afe110c0352": "智能体上限", + "a27d19aa7504f69a": "仅看内存", + "710aada747770581": "{limit} 个中 {working} 个在工作", + "30a5be40eb956663": "工作中", + "ac2c1a39608fc635": "空闲中", + "8a72bdb53d14db64": "{count, plural, other {另有 # 个}}", + "5f2d81b15ca48b42": "没有打开的智能体。", + "e1933d2c7497f1af": "{machine}:离线或无数据", + "c8940a9ca306ec4e": "{machine}:{working} 个在工作,{open} 个空闲,可用 {free},{more, plural, =0 {无法再增加智能体} other {还可再开 # 个智能体}}", + "3066798aa7701f50": "离线", + "4ab3bd1158a8b315": "{machine} 已离线或未发送数据。", + "7f99aaba0befc867": "机器", + "9616bf1650ea9772": "下一个 → {machine} · Auto:{model}", + "719cb5b7ca0f7c16": "下一个 → {machine}", + "053131a1f8331cff": "下一个 → 等待({reason})", + "448d0003f5f1210e": "无数据", + "0b9c7179abb1df86": "全部已满", + "b1dc16cc5d6c600d": "机器栏", + "aa9721463ad159f3": "重置“机器栏”为默认值", + "095fbfdfa2b4ecfc": "仅看内存", + "df1309a7a0bba600": "{count, plural, other {# 个智能体}}", + "a38f78946916317b": "此机器同时运行的智能体上限。机器栏提供的余量不会超过此值。选择“仅看内存”时,只由可用内存和负载决定。", + "2258ffb7d1a1b24f": "重置“智能体上限”为默认值", + "ea78dc5af6e6903a": "在标题栏下方显示一条状态栏,包含每台已连接机器的负载和可再开的智能体数、Claude 限额,以及下一个会话适合在哪里启动。窄窗口中隐藏。", + "56dafe176c45523e": "机器 hub power 负载 内存 智能体 余量 下一个 会话 顶部 栏", + "2229ac1d24096dfa": "机器栏 最多 智能体 同时 上限 余量 内存" } diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 4ba107059f2b..c8e34b901ad9 100644 --- a/apps/web/src/index.css +++ b/apps/web/src/index.css @@ -121,6 +121,8 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil --glass-saturation: 1.14; --desktop-window-right-resize-inset: 0px; --workspace-topbar-height: 52px; + /* Space each column leaves under its header for the machine bar; the app shell sets it. */ + --machine-bar-height: 0px; --workspace-controls-top: 0px; --workspace-controls-left: calc(env(safe-area-inset-left) + 0.75rem); --workspace-controls-right: calc(env(safe-area-inset-right) + 0.75rem); diff --git a/apps/web/src/state/machineStatus.ts b/apps/web/src/state/machineStatus.ts new file mode 100644 index 000000000000..68d0c9291a0c --- /dev/null +++ b/apps/web/src/state/machineStatus.ts @@ -0,0 +1,49 @@ +import { createEnvironmentRpcQueryAtomFamily } from "@t3tools/client-runtime/state/runtime"; +import { type EnvironmentId, type MachineStatus, WS_METHODS } from "@t3tools/contracts"; +import { Atom } from "effect/reactivity"; + +import { connectionAtomRuntime } from "../connection/runtime"; +import { environmentPresentations } from "./presentation"; + +export interface MachineEnvironment { + readonly environmentId: EnvironmentId; + readonly label: string; + /** null while the environment is offline or its server sent nothing yet. */ + readonly status: MachineStatus | null; +} + +// Polls only while the machine bar reads it; servers cache a sample for 5 s. +const machineStatusQuery = createEnvironmentRpcQueryAtomFamily(connectionAtomRuntime, { + label: "environment-data:server:machine-status", + tag: WS_METHODS.serverGetMachineStatus, + staleTimeMs: 20_000, + refreshIntervalMs: 25_000, + idleTtlMs: 0, +}); + +/** True when an enabled environment's server reports its machine. */ +export const machineBarAvailableAtom = Atom.make((get) => + [...get(environmentPresentations.serverConfigsAtom).values()].some( + (config) => config.environment.capabilities.machineStatus === true, + ), +).pipe(Atom.withLabel("web-machine-bar-available")); + +/** Enabled environments that report their machine, in catalog order. */ +export const machineEnvironmentsAtom = Atom.make((get): ReadonlyArray => { + const environments: MachineEnvironment[] = []; + for (const [environmentId, presentation] of get(environmentPresentations.presentationsAtom)) { + if (!presentation.entry.enabled) continue; + if (presentation.serverConfig?.environment.capabilities.machineStatus !== true) continue; + // A query keeps its last answer through a reconnect; an offline machine must read "off". + const result = + presentation.connection.phase === "connected" + ? get(machineStatusQuery({ environmentId, input: {} })) + : null; + environments.push({ + environmentId, + label: presentation.entry.target.label, + status: result?._tag === "Success" ? result.value : null, + }); + } + return environments; +}).pipe(Atom.withLabel("web-machine-environments")); diff --git a/docs/progress.md b/docs/progress.md index 781bce4aedee..5731757cf8db 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -254,3 +254,12 @@ - Real run: `vp run migrate-dev-db --base-dir .t3` seeded the worktree's own `.t3` from a read-only snapshot (67.5 MB, 5 projects, 31 threads) and applied migrations `103_IssueTrackerAdditionalScopes`, `104_ProjectionProjectsTrackedFolders` and `105_TaskFolders`. The server then booted on that data dir on port 15168, answered HTTP 302 and was stopped by the PID this task started. No agent turn was sent. - Review: one read-only fallback review on the first Claude account (the second was at its weekly limit) found no bugs. It confirmed both conflict resolutions and each fork behavior named above. Its one nit, the catalog count in the conflicts line, is corrected here. - Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Migrations 103-105 add tracker scopes, a tracked-folders table and task folders. Recheck upstream main before the merge if it has moved during the sync. + +## 2026-11-21: Machine bar under the header + +- What: a 22 px strip under the window's header row (web and desktop, 768 px and wider) shows each connected machine as `hub2 ● 1/2 · 3.5 GB · +1` (working agents over the machine's agent limit, free memory, agents that still fit), each Claude account's 5-hour and weekly use as `A 48·19`, and `Next → hub2 · Auto: Opus 5.5 (A)`. Hovering or clicking a machine opens CPU load, memory, swap, disk, Linux pressure, room, the agent limit and the machine's working and open agents. Each server answers the new `server.getMachineStatus` (capability `machineStatus`): Linux reads `/proc/meminfo`, `/proc/loadavg` and `/proc/pressure/*`; Windows and macOS use Node `os` and HostResources (no load or pressure gates there). Working = threads with a run preparing, queued, starting or running, delegated children included; open = a live provider session without one. The server caches a sample for 5 s and the bar polls every 25 s only while it is shown. `machineCapacity()` and `recommendNextMachine()` in `packages/shared` port Hub Power's `capacity()` with its constants. New settings: Maintenance → Agent limit (`machineStatus.maxWorkingAgents`, per server, default memory only) and General → Machine bar (per device, default on). +- Why: Tomáš wants to see where the next thread should start without opening Hub Power. +- Differences from the brief: Hub Power reads PSI avg60 for memory and CPU, so the bar does too (the brief said avg10; the IO gate is avg10 as in the hubs' rules). The 800 MB gate needs no code: the reserve already leaves no room below about 1.2 GB. Ties go to the larger share of free memory, then list order, since nothing generic tells hub2, the notebook and hub apart. Machines the client is not connected to (`machineStatus.sshPeers` over SSH) are not in this change. +- Numbers: machineCapacity 19/19, MachineStatus (server) 5/5, machineBar.logic 2/2; `vp run i18n:check` pass with 43 new keys translated in the 9 other web locales. +- Real run (worktree `.t3`, seeded from a read-only snapshot of the live database): the hub2 chip read `0 · 3.9 GB · +4`; after Agent limit 2 and a Replay showcase turn it read `1/2 · 3.5 GB · +1` and the popover listed the working thread; the Auto label matched the picker. At 700 px the bar is hidden with no gap under the headers; at 900 px the Claude accounts drop out; the General switch removes the bar and its gap. +- Next: SSH peers for machines the client is not connected to (hub from the notebook; hub and the notebook from a browser on hub2). After deploying on Tomáš's word, set the agent limits (hub2 2, hub 2, notebook 3). diff --git a/docs/user/usage.md b/docs/user/usage.md index 1818c7da2374..ec7f368b35ac 100644 --- a/docs/user/usage.md +++ b/docs/user/usage.md @@ -201,6 +201,20 @@ Claude quotas. Tap it to open **Usage → Limits**; on Android this works while the background, otherwise open the app from the launcher. On iOS, use **Edit Widget** to choose Session, Weekly, or both for each provider. Reopen T3 to refresh expired readings. +## Machine bar + +On web and desktop windows wider than 768 px, a strip under the header shows each connected +machine: working agents (over its agent limit, when one is set), free memory, and how many more +agents fit. Green means room, amber means the machine is at its limit or its memory reserve, red +means memory, CPU, or disk pressure, and grey means offline. Hover or click a machine for its CPU +load, memory, swap, disk, pressure, and the agents it runs. The strip also shows each Claude +account's 5-hour and weekly use, and where the next thread fits, with the model Auto would pick +there. + +Room is free memory minus a reserve (15% of RAM, at least 512 MB), divided by 700 MB per agent, +and none while the machine is under pressure. Set each machine's limit in **Settings → +Maintenance → Agent limit**. Hide the strip on a device in **Settings → General → Machine bar**. + ## Keyboard shortcuts On web and desktop, open Usage from the command palette. While on Usage, From 62c623e705cdebd9d2976f70103b50de38f0368e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 21 Nov 2026 22:17:36 +0100 Subject: [PATCH 131/230] fix(server): machine status counts only running agents and bound sessions Two classification bugs from the review of the machine bar: - A thread whose only active run was queued counted as working. A queued run on an idle thread waits on a held queue (stop with hold, failed worktree setup), a usage limit (computed by usageLimitHoldsQueue, not a payload flag) or the user, so it runs no agent. A thread that limits hold for hours made the bar report the machine at its cap. Working is now a run preparing, starting or running. - A thread detached from a still-live session (handoff, stop) counted as open, because `provider-session.detached` deletes the binding but leaves `sessions.thread_id`. Open now follows the bindings only. The test table gains a queued-only thread with a live session and a detached session; it failed on the previous query (8 agents instead of 6). Origin: read-only review of the machine bar branch (findings 1 and 2). --- .../resourceTelemetry/MachineStatus.test.ts | 22 ++++++++++++++----- .../src/resourceTelemetry/MachineStatus.ts | 10 ++++----- apps/web/src/components/DiffPanelShell.tsx | 2 +- packages/contracts/src/machineStatus.ts | 4 ++-- 4 files changed, 23 insertions(+), 15 deletions(-) diff --git a/apps/server/src/resourceTelemetry/MachineStatus.test.ts b/apps/server/src/resourceTelemetry/MachineStatus.test.ts index 8e3708d2dcbf..828ff5af4d83 100644 --- a/apps/server/src/resourceTelemetry/MachineStatus.test.ts +++ b/apps/server/src/resourceTelemetry/MachineStatus.test.ts @@ -36,8 +36,15 @@ const seed = Effect.fn("seed")(function* ( readonly minute: number; readonly deleted?: boolean; readonly runs?: ReadonlyArray; - /** A session status, and whether the thread is bound only through the bindings table. */ - readonly session?: { readonly status: string; readonly boundOnly?: boolean }; + /** + * A session status. `boundOnly`: the session row names no thread, only its binding does. + * `detached`: the session row names the thread, but no binding is left. + */ + readonly session?: { + readonly status: string; + readonly boundOnly?: boolean; + readonly detached?: boolean; + }; }>, ) { const sql = yield* SqlClient.SqlClient; @@ -73,6 +80,7 @@ const seed = Effect.fn("seed")(function* ( ${thread.session.status}, ${at}, '{}' ) `; + if (thread.session.detached) continue; yield* sql` INSERT INTO orchestration_v2_projection_provider_session_bindings (provider_session_id, thread_id) VALUES (${sessionId}, ${thread.id}) @@ -82,7 +90,7 @@ const seed = Effect.fn("seed")(function* ( }); describe("MachineStatusReader", () => { - it.effect("counts threads with an active run as working and idle live sessions as open", () => + it.effect("counts threads with a starting or running run as working, live sessions as open", () => Effect.gen(function* () { yield* seed([ { id: "running", minute: 1, runs: ["completed", "running", "queued"] }, @@ -94,6 +102,8 @@ describe("MachineStatusReader", () => { { id: "stopped", minute: 7, runs: ["completed"], session: { status: "stopped" } }, { id: "failed", minute: 8, runs: ["failed"], session: { status: "error" } }, { id: "deleted", minute: 9, deleted: true, runs: ["running"] }, + { id: "queued-open", minute: 10, runs: ["queued"], session: { status: "ready" } }, + { id: "detached", minute: 11, session: { status: "ready", detached: true } }, ]); const status = yield* (yield* MachineStatus.MachineStatusReader).read; @@ -105,15 +115,15 @@ describe("MachineStatusReader", () => { })), [ { threadId: "preparing-child", state: "working", providerInstanceId: "claudeAgent" }, - { threadId: "queued", state: "working", providerInstanceId: "claudeAgent" }, { threadId: "running", state: "working", providerInstanceId: "claudeAgent" }, + { threadId: "queued-open", state: "open", providerInstanceId: "codex" }, { threadId: "bound", state: "open", providerInstanceId: "codex" }, { threadId: "idle", state: "open", providerInstanceId: "codex" }, { threadId: "waiting", state: "open", providerInstanceId: "codex" }, ], ); - assert.strictEqual(status.working, 3); - assert.strictEqual(status.open, 3); + assert.strictEqual(status.working, 2); + assert.strictEqual(status.open, 4); assert.strictEqual(status.agents[0]?.title, "Title preparing-child"); assert.strictEqual(status.maxWorkingAgents, 2); assert.strictEqual(status.cpuUtilization, 0.25); diff --git a/apps/server/src/resourceTelemetry/MachineStatus.ts b/apps/server/src/resourceTelemetry/MachineStatus.ts index b7acb21458c9..2060e8e8184c 100644 --- a/apps/server/src/resourceTelemetry/MachineStatus.ts +++ b/apps/server/src/resourceTelemetry/MachineStatus.ts @@ -74,7 +74,9 @@ const make = Effect.gen(function* () { const readFile = (path: string) => fs.readFileString(path).pipe(Effect.orElseSucceed(() => "")); - // Working: a run that is not waiting on the user. Open: a live session without one. + // Working: a run that is preparing, starting or running. A queued run on an idle thread + // waits on a hold, a usage limit or the user, so it runs no agent. Open: a live session + // still bound to the thread; detaching removes the binding but not `sessions.thread_id`. // The status list repeats the partial recovery index's predicate so SQLite can use it. const readAgents = SqlSchema.findAll({ Request: Schema.Void, @@ -84,7 +86,7 @@ const make = Effect.gen(function* () { SELECT thread_id, provider_instance_id, MIN(ordinal) FROM orchestration_v2_projection_runs WHERE status IN ('queued', 'preparing', 'starting', 'running', 'waiting') - AND status != 'waiting' + AND status IN ('preparing', 'starting', 'running') GROUP BY thread_id ), live_sessions AS ( @@ -93,10 +95,6 @@ const make = Effect.gen(function* () { JOIN orchestration_v2_projection_provider_session_bindings AS bindings ON bindings.provider_session_id = sessions.provider_session_id WHERE sessions.status NOT IN ('stopped', 'error') - UNION ALL - SELECT thread_id, provider_instance_id - FROM orchestration_v2_projection_provider_sessions - WHERE status NOT IN ('stopped', 'error') AND thread_id IS NOT NULL ) SELECT threads.thread_id AS "threadId", diff --git a/apps/web/src/components/DiffPanelShell.tsx b/apps/web/src/components/DiffPanelShell.tsx index 64ef4be015d4..effdb04b9f06 100644 --- a/apps/web/src/components/DiffPanelShell.tsx +++ b/apps/web/src/components/DiffPanelShell.tsx @@ -13,7 +13,7 @@ function getDiffPanelHeaderRowClassName(mode: DiffPanelMode) { "@container/diff-header flex items-center justify-between gap-2", mode === "embedded" ? "px-2" : "px-4", shouldUseDragRegion - ? "drag-region mb-(--machine-bar-height) h-[var(--workspace-topbar-height)] border-b border-border wco:pr-(--workspace-native-controls-inset)" + ? "drag-region h-[var(--workspace-topbar-height)] border-b border-border wco:pr-(--workspace-native-controls-inset)" : "flex h-10 min-h-10 shrink-0 items-center border-b border-border/60 bg-background in-data-[preview-panel-mode=inline]:mb-3 in-data-[preview-panel-mode=inline]:h-7 in-data-[preview-panel-mode=inline]:min-h-7 in-data-[preview-panel-mode=inline]:border-b-transparent", ); } diff --git a/packages/contracts/src/machineStatus.ts b/packages/contracts/src/machineStatus.ts index 5f57f22ac677..da18a7c583c9 100644 --- a/packages/contracts/src/machineStatus.ts +++ b/packages/contracts/src/machineStatus.ts @@ -35,9 +35,9 @@ export const MachineStatus = Schema.Struct({ pressure: Schema.NullOr( Schema.Struct({ cpu: MachinePressure, memory: MachinePressure, io: MachinePressure }), ), - /** Threads with a run preparing, queued, starting or running, delegated children included. */ + /** Threads with a run preparing, starting or running, delegated children included. */ working: NonNegativeInt, - /** Threads whose agent session is alive but has no such run. */ + /** Threads still bound to a live agent session but without such a run. */ open: NonNegativeInt, /** The server's `machineStatus.maxWorkingAgents`; null leaves the room to memory alone. */ maxWorkingAgents: Schema.NullOr(PositiveInt), From 2a46b45f6522daf5b4e66aa9d80048c1eb2b90a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1=C5=A1=20=C5=98=C3=A1dek?= Date: Sat, 21 Nov 2026 22:18:29 +0100 Subject: [PATCH 132/230] fix(web): machine bar mounts only when shown and never shows stale data Review follow-ups for the machine bar: - Below 768 px the bar was hidden with CSS but stayed mounted, so a phone on the web app polled every connected server while showing nothing. The shell now mounts it only when the md media query matches. - A connected machine read "off" until its first answer arrived; it now shows its name and a grey dot while loading. A server that stops answering keeps no last numbers: after about two minutes without a fresh answer the chip reads "off". - The popover showed PSI avg10 for every resource while the room gates use avg60 for CPU and memory; it now shows the averages the gates read. - Provider status pushes re-rendered the whole bar. The Claude accounts and the Next part now read provider data in their own components, and the popover reads provider names only while open. - Dropped the margin on DiffPanelShell's drag-region header: DiffPanel is only rendered embedded, so that header never shows. The progress entry records the review and these fixes. Origin: read-only review of the machine bar branch (findings 3, 4, 5, 7 and 8). --- apps/web/src/components/AppSidebarLayout.tsx | 5 +- .../src/components/machineBar/MachineBar.tsx | 109 ++++++++++-------- .../machineBar/machineBar.logic.test.ts | 44 +++++-- .../components/machineBar/machineBar.logic.ts | 14 ++- apps/web/src/i18n/translations/de.json | 3 +- apps/web/src/i18n/translations/en.json | 3 +- apps/web/src/i18n/translations/es.json | 3 +- apps/web/src/i18n/translations/fr.json | 3 +- apps/web/src/i18n/translations/ja.json | 3 +- apps/web/src/i18n/translations/ko.json | 3 +- apps/web/src/i18n/translations/pt-BR.json | 3 +- apps/web/src/i18n/translations/ru.json | 3 +- apps/web/src/i18n/translations/sv.json | 3 +- apps/web/src/i18n/translations/zh.json | 3 +- apps/web/src/state/machineStatus.ts | 6 + docs/progress.md | 7 +- 16 files changed, 146 insertions(+), 69 deletions(-) diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 1daff0df2538..3bb5bc7153d1 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -33,6 +33,7 @@ import { selectActiveRightPanel, useRightPanelStore } from "../rightPanelStore"; import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore"; import { cn, isMacPlatform } from "../lib/utils"; import { primaryServerKeybindingsAtom } from "../state/server"; +import { useMediaQuery } from "../hooks/useMediaQuery"; import { useClientSettings, useEnvironmentIdentificationMode } from "../hooks/useSettings"; import { machineBarAvailableAtom } from "../state/machineStatus"; import { MachineBar } from "./machineBar/MachineBar"; @@ -463,7 +464,9 @@ export function AppSidebarLayout({ ) as CSSProperties; const machineBarEnabled = useClientSettings((settings) => settings.machineBarEnabled); const machineBarAvailable = useAtomValue(machineBarAvailableAtom); - const machineBarShown = showSidebar && machineBarEnabled && machineBarAvailable; + // Narrow windows never show the bar, so they must not mount it and poll every machine. + const machineBarFits = useMediaQuery({ min: "md" }); + const machineBarShown = showSidebar && machineBarEnabled && machineBarAvailable && machineBarFits; const sidebarProviderStyle = { "--sidebar-width": `${clampThreadSidebarWidth(sidebarWidth, sidebarMinimumWidth, sidebarMaximumWidth)}px`, "--panel-animation-duration": `${panelAnimationDurationMs}ms`, diff --git a/apps/web/src/components/machineBar/MachineBar.tsx b/apps/web/src/components/machineBar/MachineBar.tsx index 487fa466372b..0fa47f4f971a 100644 --- a/apps/web/src/components/machineBar/MachineBar.tsx +++ b/apps/web/src/components/machineBar/MachineBar.tsx @@ -10,6 +10,7 @@ import { cn } from "../../lib/utils"; import { deriveProviderInstanceEntries } from "../../providerInstances"; import { machineEnvironmentsAtom } from "../../state/machineStatus"; import { environmentPresentations } from "../../state/presentation"; +import { providersIgnoringCheckedAtAtom } from "../../state/server"; import { describeAutoRoute } from "../chat/autoRoute"; import { Popover, PopoverPopup, PopoverTrigger } from "../ui/popover"; import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; @@ -105,6 +106,50 @@ function AccountChip({ account }: { readonly account: AccountUsage }) { ); } +// Usage limits ride on provider status pushes, so only this strip re-renders on them. +function ClaudeAccounts() { + const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom); + const accounts = claudeAccountUsage(collectLimitAccounts(presentations)); + if (accounts.length === 0) return null; + return ( +
+ {accounts.map((account) => ( + + ))} +
+ ); +} + +function NextMachine({ + chips, + now, +}: { + readonly chips: ReadonlyArray; + readonly now: number; +}) { + const gt = useGT(); + const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom); + const next = recommendNextMachine(chips.map((chip) => ({ id: chip.key, status: chip.status }))); + const nextChip = next.kind === "start" ? chips.find((chip) => chip.key === next.id) : undefined; + const providers = nextChip + ? (presentations.get(nextChip.environmentId)?.serverConfig?.providers ?? EMPTY_PROVIDERS) + : EMPTY_PROVIDERS; + const route = nextChip + ? describeAutoRoute({ entries: deriveProviderInstanceEntries(providers), now }) + : null; + return ( +
+ {nextChip + ? route + ? gt("Next → {machine} · Auto: {model}", { machine: nextChip.name, model: route.label }) + : gt("Next → {machine}", { machine: nextChip.name }) + : gt("Next → wait ({reason})", { + reason: waitReason(next.kind === "wait" ? next.limits : [], gt), + })} +
+ ); +} + function DetailRow({ label, value }: { readonly label: string; readonly value: string }) { return ( <> @@ -117,13 +162,12 @@ function DetailRow({ label, value }: { readonly label: string; readonly value: s function MachineDetails({ chip, status, - providers, }: { readonly chip: MachineChip; readonly status: MachineStatus; - readonly providers: ReadonlyArray; }) { const gt = useGT(); + const providers = useAtomValue(providersIgnoringCheckedAtAtom(chip.environmentId)); const capacity = chip.capacity; const providerName = (instanceId: string) => { const provider = providers.find((candidate) => candidate.instanceId === instanceId); @@ -178,11 +222,12 @@ function MachineDetails({ /> ) : null} {status.pressure !== null ? ( + // The averages the room gates read: 1 minute for CPU and memory, 10 s for IO. @@ -248,18 +293,14 @@ function MachineDetails({ ); } -function MachineChipButton({ - chip, - providers, -}: { - readonly chip: MachineChip; - readonly providers: ReadonlyArray; -}) { +function MachineChipButton({ chip }: { readonly chip: MachineChip }) { const gt = useGT(); const { status, capacity } = chip; const summary = status === null || capacity === null - ? gt("{machine}: offline or no data", { machine: chip.name }) + ? chip.loading + ? gt("{machine}: waiting for data", { machine: chip.name }) + : gt("{machine}: offline or no data", { machine: chip.name }) : gt( "{machine}: {working} working, {open} open, {free} free, {more, plural, =0 {no room for more agents} one {room for # more agent} other {room for # more agents}}", { @@ -287,7 +328,9 @@ function MachineChipButton({ {chip.name} {status === null || capacity === null ? ( - {gt("off")} + chip.loading ? null : ( + {gt("off")} + ) ) : ( {status.maxWorkingAgents === null @@ -300,10 +343,12 @@ function MachineChipButton({ {status === null ? (

- {gt("{machine} is offline or sent no data.", { machine: chip.name })} + {chip.loading + ? summary + : gt("{machine} is offline or sent no data.", { machine: chip.name })}

) : ( - + )}
@@ -314,16 +359,7 @@ function MachineChipButton({ export function MachineBar() { const gt = useGT(); const now = Date.parse(useNowMinute()); - const chips = machineChips(useAtomValue(machineEnvironmentsAtom)); - const presentations = useAtomValue(environmentPresentations.presentationsWithProvidersAtom); - const accounts = claudeAccountUsage(collectLimitAccounts(presentations)); - const providersOf = (chip: MachineChip) => - presentations.get(chip.environmentId)?.serverConfig?.providers ?? EMPTY_PROVIDERS; - const next = recommendNextMachine(chips.map((chip) => ({ id: chip.key, status: chip.status }))); - const nextChip = next.kind === "start" ? chips.find((chip) => chip.key === next.id) : undefined; - const route = nextChip - ? describeAutoRoute({ entries: deriveProviderInstanceEntries(providersOf(nextChip)), now }) - : null; + const chips = machineChips(useAtomValue(machineEnvironmentsAtom), now); return (
{chips.map((chip) => ( - + ))}
- {accounts.length > 0 ? ( -
- {accounts.map((account) => ( - - ))} -
- ) : null} -
- {nextChip - ? route - ? gt("Next → {machine} · Auto: {model}", { - machine: nextChip.name, - model: route.label, - }) - : gt("Next → {machine}", { machine: nextChip.name }) - : gt("Next → wait ({reason})", { - reason: waitReason(next.kind === "wait" ? next.limits : [], gt), - })} -
+ +
); } diff --git a/apps/web/src/components/machineBar/machineBar.logic.test.ts b/apps/web/src/components/machineBar/machineBar.logic.test.ts index fed4c32ff88a..31414a663d72 100644 --- a/apps/web/src/components/machineBar/machineBar.logic.test.ts +++ b/apps/web/src/components/machineBar/machineBar.logic.test.ts @@ -26,21 +26,49 @@ function status(hostname: string, working: number): MachineStatus { } describe("machineChips", () => { - it("gives a machine reached through two environments one chip, and an offline one its label", () => { - const chips = machineChips([ - { environmentId: EnvironmentId.make("local"), label: "This PC", status: status("hub2", 1) }, - { environmentId: EnvironmentId.make("hub2"), label: "hub2", status: status("HUB2", 0) }, - { environmentId: EnvironmentId.make("hub"), label: "hub (backup)", status: null }, - ]); + const now = Date.parse("2026-11-21T21:00:00.000Z"); + const environment = ( + id: string, + label: string, + reported: MachineStatus | null, + options: { readonly ageMs?: number; readonly loading?: boolean } = {}, + ) => ({ + environmentId: EnvironmentId.make(id), + label, + status: reported, + receivedAt: now - (options.ageMs ?? 1_000), + loading: options.loading ?? false, + }); + + it("gives one chip per host, and names machines without fresh data by their label", () => { + const chips = machineChips( + [ + environment("local", "This PC", status("hub2", 1)), + environment("hub2", "hub2", status("HUB2", 0)), + environment("hub", "hub (backup)", null), + environment("notebook", "Notebook", status("Tom_Notebook", 0), { ageMs: 120_000 }), + environment("starting", "Starting", null, { loading: true }), + ], + now, + ); expect( - chips.map(({ name, environmentLabel, capacity }) => ({ name, environmentLabel, capacity })), + chips.map(({ name, environmentLabel, capacity, loading }) => ({ + name, + environmentLabel, + capacity, + loading, + })), ).toEqual([ { name: "hub2", environmentLabel: "This PC", capacity: { more: 1, limit: "cap", level: "room" }, + loading: false, }, - { name: "hub (backup)", environmentLabel: "hub (backup)", capacity: null }, + { name: "hub (backup)", environmentLabel: "hub (backup)", capacity: null, loading: false }, + // A server that stopped answering two minutes ago reads as off, not as its last numbers. + { name: "Notebook", environmentLabel: "Notebook", capacity: null, loading: false }, + { name: "Starting", environmentLabel: "Starting", capacity: null, loading: true }, ]); }); }); diff --git a/apps/web/src/components/machineBar/machineBar.logic.ts b/apps/web/src/components/machineBar/machineBar.logic.ts index 69ceed6393ca..5c12f147644e 100644 --- a/apps/web/src/components/machineBar/machineBar.logic.ts +++ b/apps/web/src/components/machineBar/machineBar.logic.ts @@ -5,6 +5,9 @@ import type { LimitAccount } from "@t3tools/shared/usageLimits"; import type { MachineEnvironment } from "../../state/machineStatus"; import { claudeAccountLetter } from "../chat/autoRoute"; +// Three missed polls: the server is connected but no longer answering. +const STALE_AFTER_MS = 90_000; + export interface MachineChip { readonly key: string; readonly environmentId: EnvironmentId; @@ -13,13 +16,19 @@ export interface MachineChip { readonly name: string; readonly status: MachineStatus | null; readonly capacity: MachineCapacity | null; + /** No status yet because the first answer is on its way, not because the machine is off. */ + readonly loading: boolean; } /** One chip per machine: environments that reach the same host share the first one's chip. */ -export function machineChips(environments: ReadonlyArray): MachineChip[] { +export function machineChips( + environments: ReadonlyArray, + now: number, +): MachineChip[] { const chips: MachineChip[] = []; const hosts = new Set(); - for (const { environmentId, label, status } of environments) { + for (const { environmentId, label, status: reported, receivedAt, loading } of environments) { + const status = reported !== null && now - receivedAt <= STALE_AFTER_MS ? reported : null; const key = status === null ? `environment:${environmentId}` : status.hostname.toLowerCase(); if (hosts.has(key)) continue; hosts.add(key); @@ -30,6 +39,7 @@ export function machineChips(environments: ReadonlyArray): M name: status?.hostname ?? label, status, capacity: status === null ? null : machineCapacity(status), + loading: status === null && loading, }); } return chips; diff --git a/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 2a95b39e4c50..fcddeae4d8b1 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -12520,5 +12520,6 @@ "2258ffb7d1a1b24f": "Agent-Limit auf Standard zurücksetzen", "ea78dc5af6e6903a": "Zeigt unter der Kopfzeile eine Leiste mit der Last jedes verbundenen Rechners und dem Platz für weitere Agenten, den Claude-Limits und wo der nächste Thread passt. In schmalen Fenstern ausgeblendet.", "56dafe176c45523e": "rechner maschinen hub power last speicher agenten platz nächster thread leiste oben", - "2229ac1d24096dfa": "rechnerleiste höchstens agenten gleichzeitig limit platz speicher" + "2229ac1d24096dfa": "rechnerleiste höchstens agenten gleichzeitig limit platz speicher", + "dffec1f0549853b0": "{machine}: wartet auf Daten" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index f6a872fd90d0..e13b0869e4c4 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -12529,5 +12529,6 @@ "2258ffb7d1a1b24f": "Reset agent limit to default", "ea78dc5af6e6903a": "Show a strip under the header with each connected machine's load and room for more agents, the Claude limits, and where the next thread fits. Hidden in narrow windows.", "56dafe176c45523e": "machines hub power load memory agents room next thread top strip", - "2229ac1d24096dfa": "machine bar most agents working at once cap room memory" + "2229ac1d24096dfa": "machine bar most agents working at once cap room memory", + "dffec1f0549853b0": "{machine}: waiting for data" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index 54a9e8dde471..3962cc07a3dd 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -12515,5 +12515,6 @@ "2258ffb7d1a1b24f": "Restablecer el límite de agentes al valor predeterminado", "ea78dc5af6e6903a": "Muestra una franja bajo la cabecera con la carga de cada máquina conectada y el espacio para más agentes, los límites de Claude y dónde cabe el siguiente hilo. Se oculta en ventanas estrechas.", "56dafe176c45523e": "máquinas hub power carga memoria agentes espacio siguiente hilo franja superior", - "2229ac1d24096dfa": "barra de máquinas máximo agentes a la vez límite espacio memoria" + "2229ac1d24096dfa": "barra de máquinas máximo agentes a la vez límite espacio memoria", + "dffec1f0549853b0": "{machine}: esperando datos" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index bd7216c25030..4f0e493c7496 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -12520,5 +12520,6 @@ "2258ffb7d1a1b24f": "Réinitialiser la limite d'agents à la valeur par défaut", "ea78dc5af6e6903a": "Affiche sous l'en-tête une bande avec la charge de chaque machine connectée et la place pour d'autres agents, les limites de Claude et l'endroit où le prochain fil a sa place. Masquée dans les fenêtres étroites.", "56dafe176c45523e": "machines hub power charge mémoire agents place prochain fil bande haut", - "2229ac1d24096dfa": "barre des machines maximum agents en même temps limite place mémoire" + "2229ac1d24096dfa": "barre des machines maximum agents en même temps limite place mémoire", + "dffec1f0549853b0": "{machine} : en attente de données" } diff --git a/apps/web/src/i18n/translations/ja.json b/apps/web/src/i18n/translations/ja.json index a7cba33eebdd..cc5633afb7e4 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -12469,5 +12469,6 @@ "2258ffb7d1a1b24f": "エージェント上限をデフォルトにリセット", "ea78dc5af6e6903a": "ヘッダーの下に、接続中の各マシンの負荷と追加できるエージェント数、Claude の上限、次のスレッドを始められる場所を表示します。幅の狭いウィンドウでは非表示です。", "56dafe176c45523e": "マシン hub power 負荷 メモリ エージェント 余裕 次 スレッド 上部 バー", - "2229ac1d24096dfa": "マシンバー 最大 エージェント 同時 上限 余裕 メモリ" + "2229ac1d24096dfa": "マシンバー 最大 エージェント 同時 上限 余裕 メモリ", + "dffec1f0549853b0": "{machine}: データを待機中" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 436ed5563b65..4cfaa3a1ccc2 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -12464,5 +12464,6 @@ "2258ffb7d1a1b24f": "에이전트 한도 기본값으로 재설정", "ea78dc5af6e6903a": "헤더 아래에 연결된 각 머신의 부하와 추가 에이전트 여유, Claude 한도, 다음 스레드를 시작할 위치를 보여 줍니다. 좁은 창에서는 숨겨집니다.", "56dafe176c45523e": "머신 hub power 부하 메모리 에이전트 여유 다음 스레드 상단 바", - "2229ac1d24096dfa": "머신 바 최대 에이전트 동시 한도 여유 메모리" + "2229ac1d24096dfa": "머신 바 최대 에이전트 동시 한도 여유 메모리", + "dffec1f0549853b0": "{machine}: 데이터 기다리는 중" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 38a8de480408..0af69d4bc5ae 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -12520,5 +12520,6 @@ "2258ffb7d1a1b24f": "Redefinir o limite de agentes para o padrão", "ea78dc5af6e6903a": "Mostra uma faixa abaixo do cabeçalho com a carga de cada máquina conectada e o espaço para mais agentes, os limites do Claude e onde cabe a próxima thread. Oculta em janelas estreitas.", "56dafe176c45523e": "máquinas hub power carga memória agentes espaço próxima thread faixa superior", - "2229ac1d24096dfa": "barra de máquinas máximo agentes ao mesmo tempo limite espaço memória" + "2229ac1d24096dfa": "barra de máquinas máximo agentes ao mesmo tempo limite espaço memória", + "dffec1f0549853b0": "{machine}: aguardando dados" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index 0e6b046929b3..2c5e0b4c1fdf 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -12520,5 +12520,6 @@ "2258ffb7d1a1b24f": "Сбросить лимит агентов к значению по умолчанию", "ea78dc5af6e6903a": "Показывает под заголовком полосу с нагрузкой каждой подключённой машины и местом для новых агентов, лимитами Claude и тем, где поместится следующий тред. Скрыта в узких окнах.", "56dafe176c45523e": "машины hub power нагрузка память агенты место следующий тред полоса сверху", - "2229ac1d24096dfa": "панель машин максимум агентов одновременно лимит место память" + "2229ac1d24096dfa": "панель машин максимум агентов одновременно лимит место память", + "dffec1f0549853b0": "{machine}: ожидание данных" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index ff57ddd4e088..a40ecfd0d7cc 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -12527,5 +12527,6 @@ "2258ffb7d1a1b24f": "Återställ agentgränsen till standard", "ea78dc5af6e6903a": "Visar en remsa under rubrikraden med varje ansluten dators last och utrymme för fler agenter, Claude-gränserna och var nästa tråd får plats. Dold i smala fönster.", "56dafe176c45523e": "datorer hub power last minne agenter utrymme nästa tråd remsa överst", - "2229ac1d24096dfa": "datorfält högst agenter samtidigt gräns utrymme minne" + "2229ac1d24096dfa": "datorfält högst agenter samtidigt gräns utrymme minne", + "dffec1f0549853b0": "{machine}: väntar på data" } diff --git a/apps/web/src/i18n/translations/zh.json b/apps/web/src/i18n/translations/zh.json index 28477890cf3d..0fafb061e50c 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -12546,5 +12546,6 @@ "2258ffb7d1a1b24f": "重置“智能体上限”为默认值", "ea78dc5af6e6903a": "在标题栏下方显示一条状态栏,包含每台已连接机器的负载和可再开的智能体数、Claude 限额,以及下一个会话适合在哪里启动。窄窗口中隐藏。", "56dafe176c45523e": "机器 hub power 负载 内存 智能体 余量 下一个 会话 顶部 栏", - "2229ac1d24096dfa": "机器栏 最多 智能体 同时 上限 余量 内存" + "2229ac1d24096dfa": "机器栏 最多 智能体 同时 上限 余量 内存", + "dffec1f0549853b0": "{machine}:正在等待数据" } diff --git a/apps/web/src/state/machineStatus.ts b/apps/web/src/state/machineStatus.ts index 68d0c9291a0c..ccdff3124521 100644 --- a/apps/web/src/state/machineStatus.ts +++ b/apps/web/src/state/machineStatus.ts @@ -10,6 +10,10 @@ export interface MachineEnvironment { readonly label: string; /** null while the environment is offline or its server sent nothing yet. */ readonly status: MachineStatus | null; + /** When this client received `status`, so a server that stops answering goes grey. */ + readonly receivedAt: number; + /** Connected, and the first answer is still on its way. */ + readonly loading: boolean; } // Polls only while the machine bar reads it; servers cache a sample for 5 s. @@ -43,6 +47,8 @@ export const machineEnvironmentsAtom = Atom.make((get): ReadonlyArray