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/.github/workflows/ci.yml b/.github/workflows/ci.yml index 70208c7a1647..ac0012567489 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 @@ -288,8 +288,8 @@ jobs: name: Test needs: changes if: ${{ !cancelled() && needs.changes.outputs.test != 'false' }} - runs-on: blacksmith-8vcpu-ubuntu-2404 - timeout-minutes: 10 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} + timeout-minutes: ${{ github.repository == 'pingdotgg/t3code' && 10 || 30 }} steps: - name: Checkout uses: actions/checkout@d23441a48e516b6c34aea4fa41551a30e30af803 # v6.1.0 @@ -378,8 +378,8 @@ jobs: name: Test Web ${{ matrix.shard }} needs: changes if: ${{ !cancelled() && needs.changes.outputs.test_web != 'false' }} - runs-on: blacksmith-8vcpu-ubuntu-2404 - timeout-minutes: 10 + runs-on: ${{ github.repository == 'pingdotgg/t3code' && 'blacksmith-8vcpu-ubuntu-2404' || 'ubuntu-24.04' }} + timeout-minutes: ${{ github.repository == 'pingdotgg/t3code' && 10 || 20 }} strategy: fail-fast: false matrix: @@ -440,7 +440,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 @@ -570,7 +570,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 @@ -604,7 +604,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 @@ -637,7 +637,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 @@ -677,7 +677,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 835cac552cc4..f9b779782f9f 100644 --- a/.github/workflows/mobile-fingerprint-check.yml +++ b/.github/workflows/mobile-fingerprint-check.yml @@ -31,7 +31,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: diff --git a/.github/workflows/relay-preview-cleanup.yml b/.github/workflows/relay-preview-cleanup.yml index 936d19cadad5..9b38ee760764 100644 --- a/.github/workflows/relay-preview-cleanup.yml +++ b/.github/workflows/relay-preview-cleanup.yml @@ -99,7 +99,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: diff --git a/AGENTS.md b/AGENTS.md index a257e1a84a4f..1f18f5180bf7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -86,6 +86,14 @@ See [00_development.md](docs/operations/00_development.md) for setup, ports, see `evals/` checks how real models behave with T3 Code's model-facing text: agent instructions, MCP tool descriptions and schemas, and generated titles. Before changing that text, read [evals/README.md](evals/README.md) and run the evals it names. When fixing 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. @@ -94,6 +102,7 @@ See [00_development.md](docs/operations/00_development.md) for setup, ports, see - Body: the problem in a sentence or two, then how you fixed it. End with the model and harness that did the work. - 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. - One request is one PR. Split only when asked. Outside contributions follow [CONTRIBUTING.md](CONTRIBUTING.md#one-problem). +- 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. 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 bots are green on the latest commit. ## Documentation diff --git a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx index f2ce0ca47cb7..e7e6ea5e5fbe 100644 --- a/apps/mobile/src/features/settings/ThreadSettingsSections.tsx +++ b/apps/mobile/src/features/settings/ThreadSettingsSections.tsx @@ -141,7 +141,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/features/threads/ThreadQueueControl.tsx b/apps/mobile/src/features/threads/ThreadQueueControl.tsx index 41aed6dfd3d9..d3d6633df428 100644 --- a/apps/mobile/src/features/threads/ThreadQueueControl.tsx +++ b/apps/mobile/src/features/threads/ThreadQueueControl.tsx @@ -12,6 +12,7 @@ import { } from "@t3tools/client-runtime/state/runtime"; import { resolveUserMessagePresentation } from "@t3tools/client-runtime/user-message"; import type { ChatAttachment, EnvironmentId, RunId, ThreadId } from "@t3tools/contracts"; +import { autoLevelSelection } from "@t3tools/shared/autoModel"; import { Atom } from "effect/reactivity"; import { Image } from "expo-image"; import * as Haptics from "expo-haptics"; @@ -182,10 +183,13 @@ export function ThreadQueueSheet({ route }: StaticScreenProps) { runId, messageId: entry.messageId, originalText: entry.text, - modelSelection: entry.message?.followsThreadSelection - ? (appAtomRegistry.get(environmentThreadDetails.quietThreadAtom(target))?.projection - .thread.modelSelection ?? entry.run.modelSelection) - : entry.run.modelSelection, + // An Auto-routed pick opens as its Auto level, as in the picker. + modelSelection: autoLevelSelection( + entry.message?.followsThreadSelection + ? (appAtomRegistry.get(environmentThreadDetails.quietThreadAtom(target))?.projection + .thread.modelSelection ?? entry.run.modelSelection) + : entry.run.modelSelection, + ), followsThreadSelection: entry.message?.followsThreadSelection === true, existingAttachments: entry.attachments, ...(entry.context ? { context: entry.context } : {}), diff --git a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx index 8f509de9e674..8afa074d4d8a 100644 --- a/apps/mobile/src/features/threads/ThreadRouteScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadRouteScreen.tsx @@ -549,7 +549,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/mobile/src/features/threads/useSidebarRowThreadKey.test.tsx b/apps/mobile/src/features/threads/useSidebarRowThreadKey.test.tsx index ef58c0571ce0..ee3315abec4f 100644 --- a/apps/mobile/src/features/threads/useSidebarRowThreadKey.test.tsx +++ b/apps/mobile/src/features/threads/useSidebarRowThreadKey.test.tsx @@ -34,12 +34,14 @@ describe("useSidebarRowThreadKey", () => { using _registry = { [Symbol.dispose]: () => registry.dispose() }; const envId = EnvironmentId.make("env-1"); + // Fork: a thread launched from one in its own environment keeps its own row on mobile. + const parentEnvId = EnvironmentId.make("env-2"); const parentId = ThreadId.make("thread-parent"); const childId = ThreadId.make("thread-child"); - const parentKey = scopedThreadKey(envId, parentId); + const parentKey = scopedThreadKey(parentEnvId, parentId); const childKey = scopedThreadKey(envId, childId); const parentThread = makeThreadShellFixture({ - environmentId: envId, + environmentId: parentEnvId, id: parentId, title: "Parent", }); @@ -47,7 +49,7 @@ describe("useSidebarRowThreadKey", () => { environmentId: envId, id: childId, title: "Delegated child", - delegatedFrom: { environmentId: envId, threadId: parentId, title: "Parent" }, + delegatedFrom: { environmentId: parentEnvId, threadId: parentId, title: "Parent" }, }); const otherThread = (title: string) => makeThreadShellFixture({ environmentId: envId, id: ThreadId.make("thread-other"), title }); diff --git a/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts b/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts index a08efc2a0886..4ca0b69f2c56 100644 --- a/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts +++ b/apps/mobile/src/features/threads/useSidebarRowThreadKey.ts @@ -16,7 +16,9 @@ const sidebarRowThreadKeyAtom = Atom.family((openThreadKey: string) => const openThreadRef = parseScopedThreadKey(openThreadKey); if (openThreadRef === null) return openThreadKey; const threads = get(environmentThreadShells.quietThreadShellsAtom); - const rowRef = resolveListedAncestorThreadRef(openThreadRef, threads); + const rowRef = resolveListedAncestorThreadRef(openThreadRef, threads, { + nestLaunchedThreads: false, + }); return scopedThreadKey(rowRef.environmentId, rowRef.threadId); }), ); diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index cac4505162e9..653d308b2608 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -3856,7 +3856,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 1dd267ba82bc..72c02943df40 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -3858,7 +3858,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 679472146a88..577a91bf0b05 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -3851,7 +3851,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 2af32fe559da..9669719cab7f 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -3851,7 +3851,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 c97dfac87711..0b9f1c015182 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -3847,7 +3847,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 7eef38425d92..ca7c6d0725ae 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -3851,7 +3851,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 c73b1bb2db50..15ec6d8ad9b2 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -3851,7 +3851,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 d2291af246f7..d875c5f488fb 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -3905,7 +3905,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 cd9d9273535c..e775ffb7cd76 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -3857,7 +3857,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 6303a7178fb8..483cbf68afe2 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -3853,7 +3853,7 @@ "67937aa49179285e": "在 Mac 上,从缓存在 T3 主目录中的工作副本克隆新的工作树,无需逐个写入每个文件。无法使用时改为 Git 的常规检出。关闭后会删除缓存。", "d6ada5ec242e37ff": "用量限制", "62127e7b5c0f57a3": "用量限制解除后继续", - "4df30d44eb0b0728": "用量限制重置后自动继续会话。你可以在每个会话中取消自动继续。", + "4e8a6e262304c240": "达到用量限制后继续会话:使用 Auto 的会话会切换到下一个仍有余量的订阅,其他会话会在限制重置后继续。你可以在每个会话中取消自动继续。", "20e3a8aab5f9426a": "暂缓到用量限制重置", "0769f91ca46e3003": "将会话暂缓到用量限制重置。开启自动继续后,智能体会在重置后接着工作。", "7c27e91e75cce7a3": "自动收尾", diff --git a/apps/mobile/src/state/threads.ts b/apps/mobile/src/state/threads.ts index a0acea918724..ba3712b74abb 100644 --- a/apps/mobile/src/state/threads.ts +++ b/apps/mobile/src/state/threads.ts @@ -47,6 +47,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, @@ -64,6 +66,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/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.ts index 5033ef4e8e89..37df1c276d4d 100644 --- a/apps/mobile/src/state/use-thread-composer-state.ts +++ b/apps/mobile/src/state/use-thread-composer-state.ts @@ -9,6 +9,7 @@ import { compactBeforeSendTokens } from "@t3tools/client-runtime/state/context-w import { threadRuntimeIsActive } from "@t3tools/client-runtime/state/shell"; 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, @@ -345,14 +346,17 @@ export function useThreadComposerState(input: { const threadDraftSettings = 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( selectedThreadProjection?.projection, isModelSelectionUnavailable(serverConfig, modelSelection, selectedThread?.projectId ?? null) ? null : modelSelection, serverConfig?.providers ?? [], + nowMinuteMs, ); const runtimeMode = threadDraftSettings.runtimeMode ?? selectedThread?.runtimeMode ?? null; // Plan mode is not offered to users; every send runs in build mode. @@ -473,7 +477,6 @@ export function useThreadComposerState(input: { now, }) : null; - const nowMinuteMs = useNowMinuteMs(); const compactTokens = selectedDraft.freshContext === true ? null diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index c768b933e5e6..8453924ad8ae 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -122,6 +122,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/background/KeepAwake.test.ts b/apps/server/src/background/KeepAwake.test.ts index 628590930e47..320cffa7d435 100644 --- a/apps/server/src/background/KeepAwake.test.ts +++ b/apps/server/src/background/KeepAwake.test.ts @@ -1,5 +1,6 @@ import { describe, expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; +import * as Logger from "effect/Logger"; import * as Queue from "effect/Queue"; import * as Stream from "effect/Stream"; import * as TestClock from "effect/testing/TestClock"; @@ -35,6 +36,61 @@ describe("KeepAwake.holdWhileWanted", () => { ); }); +describe("KeepAwake.makeHold", () => { + const warningsLogger = (warnings: Array>) => + Logger.layer( + [Logger.make((entry) => (entry.logLevel === "Warn" ? warnings.push(entry) : undefined))], + { mergeWithExisting: false }, + ); + + it.effect( + "stops for good after logind denies the inhibitor, with one warning and no stack", + () => { + const warnings: Array> = []; + return Effect.gen(function* () { + const attempts = yield* Queue.unbounded(); + const hold = yield* KeepAwake.makeHold( + Queue.offer(attempts, 1).pipe( + Effect.andThen( + new KeepAwake.KeepAwakeInhibitorExited({ + exitCode: 1, + stderr: "Failed to inhibit: Access denied (interactive authentication required)", + }), + ), + ), + ); + + yield* hold; + yield* TestClock.adjust("1 hour"); + yield* hold; + + expect(yield* Queue.size(attempts)).toBe(1); + expect(warnings).toHaveLength(1); + expect(warnings[0]!.cause.reasons).toHaveLength(0); + }).pipe(Effect.provide(warningsLogger(warnings))); + }, + ); + + it.effect("retries any other inhibitor exit under backoff", () => + Effect.gen(function* () { + const attempts = yield* Queue.unbounded(); + const hold = yield* KeepAwake.makeHold( + Queue.offer(attempts, 1).pipe( + Effect.andThen(new KeepAwake.KeepAwakeInhibitorExited({ exitCode: 1, stderr: "" })), + ), + ); + yield* hold.pipe(Effect.forkScoped); + + yield* Queue.take(attempts); + yield* TestClock.adjust("5 seconds"); + yield* Queue.take(attempts); + yield* TestClock.adjust("10 seconds"); + yield* Queue.take(attempts); + expect(yield* Queue.size(attempts)).toBe(0); + }), + ); +}); + describe("KeepAwake.inhibitorCommand", () => { it("runs PowerShell by its System32 path on Windows", () => { expect( diff --git a/apps/server/src/background/KeepAwake.ts b/apps/server/src/background/KeepAwake.ts index 72e5c1fbf031..c63dbe063ee8 100644 --- a/apps/server/src/background/KeepAwake.ts +++ b/apps/server/src/background/KeepAwake.ts @@ -127,7 +127,7 @@ const retryWithBackoff = Effect.retry(backoff), ); -class KeepAwakeInhibitorExited extends Schema.TaggedError()( +export class KeepAwakeInhibitorExited extends Schema.TaggedError()( "KeepAwakeInhibitorExited", { exitCode: Schema.Number, stderr: Schema.String }, ) { @@ -136,6 +136,38 @@ class KeepAwakeInhibitorExited extends Schema.TaggedError( + error: E | KeepAwakeInhibitorExited, +): error is KeepAwakeInhibitorExited => + isInhibitorExit(error) && + /access denied|interactive authentication|not authorized/i.test(error.stderr); + +/** + * Retries `holdOnce` under backoff until interrupted, except after a permission denial, which + * makes this and every later hold a no-op. + */ +export const makeHold = (holdOnce: Effect.Effect) => + Ref.make(false).pipe( + Effect.map((denied) => + holdOnce.pipe( + Effect.catchIf(isPermissionDenied, (error) => + Ref.set(denied, true).pipe( + Effect.andThen( + Effect.logWarning(`keep-awake disabled until restart: ${error.message}`), + ), + ), + ), + retryWithBackoff("keep-awake sleep inhibitor stopped"), + Effect.ignore, + Effect.when(Effect.map(Ref.get(denied), (isDenied) => !isDenied)), + Effect.asVoid, + ), + ), + ); + export const layer = Layer.effectDiscard( Effect.gen(function* () { const platform = yield* HostProcess.Platform; @@ -240,10 +272,7 @@ export const layer = Layer.effectDiscard( stderr: (yield* Fiber.join(stderr)).trim(), }); }).pipe(Effect.scoped); - const hold = holdOnce.pipe( - retryWithBackoff("keep-awake sleep inhibitor stopped"), - Effect.ignore, - ); + const hold = yield* makeHold(holdOnce); yield* forkParked( holdWhileWanted( 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/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index a34003701627..ffc337f6933e 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -255,6 +255,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/mcp/linkOrigin.test.ts b/apps/server/src/mcp/linkOrigin.test.ts index 928fda0dd72f..ef8c4c4b6331 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,46 @@ 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; + 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.test.ts b/apps/server/src/mcp/toolkits/project/handlers.test.ts index 17fa4dd496fa..14802fa2df96 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.test.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.test.ts @@ -558,6 +558,78 @@ it.effect( }), ); +it.effect("a launch keeps the auto stamp of an Auto thread's selection", () => + Effect.gen(function* () { + const launched: Array = []; + const providers: ServerProvider[] = [ + { + instanceId: ProviderInstanceId.make("claudeAgent"), + driver: ProviderDriverKind.make("claudeAgent"), + enabled: true, + installed: true, + status: "ready", + version: null, + auth: { status: "authenticated" }, + checkedAt: "2026-01-01T00:00:00Z", + models: [ + { + slug: "claude-opus-5-5", + name: "Claude Opus 5.5", + isCustom: false, + capabilities: { + optionDescriptors: [ + { + id: "effort", + role: "reasoning", + label: "Effort", + type: "select", + options: [{ id: "xhigh", label: "Extra High" }], + }, + ], + }, + }, + ], + slashCommands: [], + skills: [], + }, + ]; + const { projectId, dependencies } = clientLaunchHarness({ + runtimeModeCeiling: "auto", + launched, + providers, + }); + const toolkit = yield* ProjectToolkit.pipe( + Effect.provide( + McpToolAccess.HandlersLayer.layer(ProjectHandlers.layer).pipe(Layer.provide(dependencies)), + ), + ); + // The model Auto routed to, plus the level stamp that keeps the thread on Auto. + const modelSelection = { + instanceId: ProviderInstanceId.make("claudeAgent"), + model: "claude-opus-5-5", + options: [ + { id: "effort", value: "xhigh" }, + { id: "auto", value: "high" }, + ], + }; + + for (const model of [modelSelection.model, "retired-auto-model"]) { + const selection = { ...modelSelection, model }; + const result = yield* toolkit + .handle("t3_thread_launch", { title: "Auto launch", projectId, modelSelection: selection }) + .pipe( + Stream.unwrap, + Stream.runCollect, + Effect.map((items) => items.at(-1)?.result), + Effect.provide(dependencies), + ); + expect(result).not.toMatchObject({ code: "invalid_request" }); + expect(launched.at(-1)?.modelSelection).toEqual(selection); + } + expect(launched).toHaveLength(2); + }), +); + it.effect("a launch retried with the same clientRequestId replays the first one", () => Effect.gen(function* () { const launched: Array = []; diff --git a/apps/server/src/mcp/toolkits/project/handlers.ts b/apps/server/src/mcp/toolkits/project/handlers.ts index deec936b62b5..b68f2fc42c90 100644 --- a/apps/server/src/mcp/toolkits/project/handlers.ts +++ b/apps/server/src/mcp/toolkits/project/handlers.ts @@ -31,6 +31,7 @@ import * as GitVcsDriver from "../../../vcs/GitVcsDriver.ts"; import * as ServerSettings from "../../../serverSettings.ts"; import * as ProviderRegistry from "../../../provider/ProviderRegistry.ts"; import * as DateTime from "effect/DateTime"; +import { isAutoModelSelection } from "@t3tools/shared/autoModel"; import { resolveNewThreadModelSelection } from "@t3tools/shared/usageLimits"; import { resolveProjectFileBackedSetting, @@ -340,6 +341,9 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { (candidate) => candidate.instanceId === instanceId, ); if (provider === undefined) return requestedSelection; + // Fork: Auto routing replaces an Auto selection's model and options when the thread + // runs, and a routed selection carries the `auto` level stamp that no model declares. + if (isAutoModelSelection(requestedSelection)) return requestedSelection; yield* OrchestrationMcp.requireAdvertisedModel(provider, model); const options = yield* OrchestrationMcp.validateModelOptions( provider, @@ -455,6 +459,16 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, { )?.supportedRuntimeModes, }); } + // 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?.environmentId === scope.environmentId + ? undefined + : input.delegatedFrom + : caller === undefined + ? undefined + : { environmentId: scope.environmentId, threadId: caller.id, title: caller.title }; const result = yield* ThreadMessageIntake.launchThread({ commandId, threadId, @@ -480,8 +494,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 }), // A link's word for it, like `delegatedFrom`: nothing else may name a run. ...(linkOrigin === undefined || input.workflowRun === undefined ? {} diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index cab2bfec7498..9bc314cae040 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/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index a7b110e851f0..a13d9532d3ab 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -8407,6 +8407,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 208406702514..2f7b67a75636 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -2355,7 +2355,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, @@ -2363,7 +2366,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 ); } @@ -2710,6 +2714,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/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..b73537e24393 --- /dev/null +++ b/apps/server/src/orchestration-v2/AutoFailoverService.test.ts @@ -0,0 +1,163 @@ +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, + lineage: { + rootThreadId: ThreadId.make("t1"), + parentThreadId: null, + relationshipToParent: null, + }, + creationSource: "user", + 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("benches a lapsed Claude plan like a limit without a reset", () => { + // A cancelled plan's token still says "pro", so Auto kept picking it and every turn failed. + const lapsed = shell({ + lastErrorClass: "provider_error", + lastErrorCode: "api_error_403", + lastError: + "Claude Code can't use your Claude subscription, usually because a payment is past due · Pay or renew at https://claude.ai/settings/billing (if you just paid, try again shortly), or use an Anthropic API key instead", + }); + expect(plan(lapsed)?.cooldownUntilMs).toBe(now + 30 * 60_000); + }); + + 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("gpt-6.1-sol"))?.command.modelSelection?.model).toBe("auto-medium"); + expect(plan(picked("gpt-6.2-sol"))?.command.modelSelection?.model).toBe("auto-medium"); + expect(plan(picked("gpt-6.2-astra"))?.command.modelSelection?.model).toBe("auto-high"); + expect(plan(picked("gpt-6.1-terra"))?.command.modelSelection?.model).toBe("auto-low"); + 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, stale runs and workflow steps alone", () => { + expect( + plan(shell({ lastErrorClass: "provider_error", lastErrorCode: "api_error_404" })), + ).toBeNull(); + expect( + plan( + shell({ + lastErrorClass: "provider_error", + lastErrorCode: "api_error_403", + lastError: "Request not allowed", + }), + ), + ).toBeNull(); + expect(plan(shell({ latestRunId: RunId.make("run:newer") }))).toBeNull(); + expect(plan(shell({ status: "idle" }))).toBeNull(); + expect(plan(shell({ settledOverride: "settled" }))).toBeNull(); + // The workflow retries a step whose turn died. + const step = { + rootThreadId: ThreadId.make("t1"), + parentThreadId: null, + relationshipToParent: null, + workflowStep: true, + }; + expect(plan(shell({ lineage: step }))).toBeNull(); + }); +}); + +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++) + 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..c87c035049a6 --- /dev/null +++ b/apps/server/src/orchestration-v2/AutoFailoverService.ts @@ -0,0 +1,193 @@ +import { + CommandId, + isDelegatedAppThread, + isProviderNativeSubagentThread, + 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 * as ServerSettings from "../serverSettings.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 cancelled or unpaid Claude plan: its token still looks valid, but every turn fails. */ +const LAPSED_PLAN_ERROR = /can.t use your Claude subscription/i; +/** 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, the thread is a delegated one not on Auto or a workflow's + * step, or the run is no longer the thread's latest. + */ +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 || + // A provider's own subagent cannot receive messages; its parent sees the failure. + isProviderNativeSubagentThread(shell) || + // A workflow retries a step whose turn died; a message here would do the step twice. + shell.lineage.workflowStep === true + ) + 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" || LAPSED_PLAN_ERROR.test(shell.lastError ?? ""); + 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" }, + }, + }; +} + +/** The Auto level whose orchestrator is closest to a hand-picked model. */ +function impliedAutoLevel(model: string): "low" | "medium" | "high" { + if (/astra/i.test(model)) return "high"; + if (/sonnet|haiku|flash|opencode\/|luna|terra/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); + 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 settings = yield* ServerSettings.ServerSettingsService; + 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; + // 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)) { + 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/LaunchedThreadNoticeReactor.test.ts b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.test.ts new file mode 100644 index 000000000000..84248f4ae05d --- /dev/null +++ b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.test.ts @@ -0,0 +1,320 @@ +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; + /** 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; + 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: input.typed === true ? "user" : "agent", + 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; + 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, 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", + 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); + 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); + }), + ); + + 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; + 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..b5a4bceca341 --- /dev/null +++ b/apps/server/src/orchestration-v2/LaunchedThreadNoticeReactor.ts @@ -0,0 +1,167 @@ +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 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; + 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, + ["runs", "messages", "turnItems", "providerTurns"], + { + messageRunIds: [run.id], + turnItemRunIds: [run.id], + turnItemTypes: ["assistant_message", "error", "system_notice"], + providerTurnAttemptIds: run.activeAttemptId === null ? [] : [run.activeAttemptId], + }, + ); + // 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?.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 = + 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/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 6d8245c81a41..e73b23fe7112 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -87,6 +87,9 @@ 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 { isAutoCoolingDown } from "./AutoCooldown.ts"; +import * as ProviderRegistry from "../provider/ProviderRegistry.ts"; import { modelSwitchSince } from "./modelSwitch.ts"; import { contextBoundaryOrdinal, @@ -1052,8 +1055,10 @@ function nextQueuedRun( return queuedRunsInDeliveryOrder(projection).find((run) => run.queueHeld !== true); } -// Delegated completions, monitor notifications and queued messages that name no model never choose a -// model, so a queued one runs on the thread's current pick rather than the one frozen at queue time. +// Delegated completions, monitor notifications, unpinned scheduled deliveries and queued messages +// that name no model never choose one, so they run on the thread's current pick. Auto-routed +// messages pick an instance at dispatch time too: a failover can move the thread while they wait, +// so they follow that pick rather than the one frozen at queue time. function followsCurrentConversation( message: | Pick< @@ -1073,12 +1078,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; } @@ -1089,10 +1101,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 ); } @@ -3674,6 +3683,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}`), @@ -3681,9 +3694,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio messageId: message.id, steerFollowUpOfRunId: run.id, steerFollowUpAfterRunOrdinal: afterRunOrdinal, - ...(message.followsThreadSelection === true - ? {} - : { modelSelection: steer?.modelSelection ?? run.modelSelection }), + ...(message.followsThreadSelection === true ? {} : { modelSelection }), text: message.text, ...(message.context ? { context: message.context } : {}), attachments: message.attachments, @@ -4139,10 +4150,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 }), ...(command.workflowRun === undefined ? {} : { workflowRun: command.workflowRun }), lineage: { parentThreadId: null, @@ -17680,6 +17689,67 @@ export const layer: Layer.Layer< | ServerSettings.ServerSettingsService | TaskFolderStore.TaskFolderStore | 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 now = DateTime.toEpochMillis(yield* DateTime.now); + const resolution = resolveAutoModelSelection({ + selection, + providers: Option.isSome(registry) ? yield* registry.value.getProviders : [], + now, + current, + blocked: (instanceId) => isAutoCoolingDown(instanceId, now), + }); + 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/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts index 460a6056eb7f..3a1550cf51c3 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.test.ts @@ -2393,7 +2393,8 @@ effectIt.effect("sends new steering text when restarting a manual continuation", }), ); -effectIt.effect("refuses unsupported resume instead of manufacturing a user prompt", () => +// 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({ text: "", @@ -2402,20 +2403,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 8051a4129095..2bc7574a02e3 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnStartService.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnStartService.ts @@ -1080,12 +1080,18 @@ export const layer: Layer.Layer< }); let effectiveHandoffs = handoffs; let resumeFellBack = false; + // 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 messageText = withMessageSenderNote( providerMessage, - projectComposerContextForProvider({ - text: providerMessage.text, - records: providerMessage.context?.records ?? [], - }), + continueInstead + ? RESUME_PROMPT + : projectComposerContextForProvider({ + text: providerMessage.text, + records: providerMessage.context?.records ?? [], + }), ); const slashCommand = isSlashCommandMessage(providerMessage); const goalDriver = @@ -1974,23 +1980,6 @@ export const layer: Layer.Layer< sideChatHandoff !== undefined || restartNote !== "" || noteContinuation; - // Pending context turns the resume into a prompted turn, which needs no native resume. - if ( - manualResume && - unsentResumeMessage === undefined && - session.resumeTurn === undefined && - !carriesPendingContext - ) { - yield* settleStartFailure({ - signal: "resume-unsupported", - title: "Native resume is unavailable", - error: new ProviderAdapter.ProviderResumeUnsupportedError({ - driver: session.driver, - providerThreadId: providerThread.id, - }), - }); - return; - } const runningProviderThread: OrchestrationV2ProviderThread = { ...loadedProviderThread, contextUsage: handoffUsage, @@ -2335,7 +2324,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/apps/server/src/orchestration-v2/ThreadForkService.ts b/apps/server/src/orchestration-v2/ThreadForkService.ts index 2981b4ccfb51..3141bdf712ae 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/server/src/orchestration-v2/ThreadSettlementService.test.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts index b17cb0070efb..35521d511451 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.test.ts @@ -50,6 +50,7 @@ import * as TerminalManager from "../terminal/Manager.ts"; import * as ProjectStore from "./ProjectStore.ts"; import * as Orchestrator from "./Orchestrator.ts"; import * as ProjectionStore from "./ProjectionStore.ts"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as ThreadSettlementService from "./ThreadSettlementService.ts"; const NOW_MS = Date.parse("2026-06-10T12:00:00.000Z"); @@ -689,6 +690,9 @@ const makeHarness = Effect.fn("makeThreadSettlementHarness")(function* (options: }); const layerDependencies = Layer.mergeAll( + Layer.succeed(ServerEnvironment.ServerEnvironmentIdentity)({ + getEnvironmentId: Effect.succeed(EnvironmentId.make("environment-here")), + }), Layer.mock(ProjectStore.ProjectStoreV2)({ listShells: () => Ref.get(snapshots).pipe(Effect.map((snapshot) => snapshot.projects)), getShell: (projectId) => @@ -1301,7 +1305,16 @@ describe("ThreadSettlementServiceV2 worker", () => { }, }; const ordinary = { ...appThread("ordinary", null), branch: "feature" }; - for (const thread of [delegated, ordinary]) { + const launched = { + ...delegated, + id: ThreadId.make("launched-here"), + delegatedFrom: { + threadId: ThreadId.make("parent-here"), + title: "Parent", + environmentId: EnvironmentId.make("environment-here"), + }, + }; + for (const thread of [delegated, ordinary, launched]) { yield* store.apply({ type: "thread.created", id: EventId.make(`created:${thread.id}`), diff --git a/apps/server/src/orchestration-v2/ThreadSettlementService.ts b/apps/server/src/orchestration-v2/ThreadSettlementService.ts index 2884600ceef6..38b87b2e9d1e 100644 --- a/apps/server/src/orchestration-v2/ThreadSettlementService.ts +++ b/apps/server/src/orchestration-v2/ThreadSettlementService.ts @@ -8,7 +8,6 @@ import { resolveProjectSettings } from "@t3tools/shared/projectSettings"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import { CommandId, - isDelegatedAppThread, isOrchestrationV2WorkActive, type ThreadId, type OrchestrationV2DomainEvent, @@ -29,6 +28,7 @@ import * as Semaphore from "effect/Semaphore"; import type * as Scope from "effect/Scope"; import * as Stream from "effect/Stream"; +import * as ServerEnvironment from "../environment/ServerEnvironment.ts"; import * as GitManager from "../git/GitManager.ts"; import * as ProjectSetupScriptRunner from "../project/ProjectSetupScriptRunner.ts"; import * as PullRequestService from "../pullRequest/PullRequestService.ts"; @@ -329,6 +329,15 @@ export function autoSettlementSettingsKey( } export const make = Effect.gen(function* () { + const identity = yield* ServerEnvironment.ServerEnvironmentIdentity; + const environmentId = yield* identity.getEnvironmentId; + // Local launches keep the ordinary thread's settlement policy; only remote tasks and + // subagents inherit immediate settlement when their work (or their parent's work) ends. + const settlesWithDelegator = ( + thread: Pick, + ) => + thread.lineage.relationshipToParent === "subagent" || + (thread.delegatedFrom != null && thread.delegatedFrom.environmentId !== environmentId); const orchestrator = yield* Orchestrator.OrchestratorV2; const projections = yield* ProjectionStore.ProjectionStoreV2; const projectStore = yield* ProjectStore.ProjectStoreV2; @@ -382,14 +391,14 @@ export const make = Effect.gen(function* () { // Merge events resweep all candidates because unlinked threads settle through branch lookup. const candidates = threads.filter( (thread) => - (automaticSettlementEnabled || isDelegatedAppThread(thread)) && + (automaticSettlementEnabled || settlesWithDelegator(thread)) && isAutoSettlementCandidate(thread, nowMs), ); // Runs per candidate thread, thousands per sweep on busy servers; the sweep owns the span. const settleThread = Effect.fnUntraced( function* (thread: (typeof candidates)[number], pullRequest: SettlementPullRequest | null) { - if (isDelegatedAppThread(thread)) { + if (settlesWithDelegator(thread)) { if (yield* terminals.hasActiveSubprocess({ threadId: thread.id })) return null; // The store returns a subagent only once its parent is done, so it settles with the // parent. A task delegated from a linked environment has no parent here, so it settles @@ -447,7 +456,7 @@ export const make = Effect.gen(function* () { const lookupCandidates = (yield* Effect.forEach( candidates, (thread) => { - if (isDelegatedAppThread(thread)) return settleThread(thread, null); + if (settlesWithDelegator(thread)) return settleThread(thread, null); const projectSettings = resolveProjectSettings(settings, thread.projectId).settings; // Skip no-op decisions; actual settlement still reads fresh settings before dispatch. const settledAt = resolveAutoSettlementAt({ diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 370fd7deb9ad..cc6d917e4abe 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -10022,6 +10022,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/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/GrokProvider.test.ts b/apps/server/src/provider/GrokProvider.test.ts index 3f28649f498b..f88964369b53 100644 --- a/apps/server/src/provider/GrokProvider.test.ts +++ b/apps/server/src/provider/GrokProvider.test.ts @@ -534,7 +534,12 @@ 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 } }, + { config: { currentPeriod: weeklyPeriod, isUnifiedBillingUser: true } }, + ]) { const limits = grokUsageResponseToLimits(response, checkedAt); expect(limits.windows).toEqual([]); expect(limits.unavailable).toBeUndefined(); @@ -542,6 +547,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/apps/server/src/provider/ProviderRegistry.test.ts b/apps/server/src/provider/ProviderRegistry.test.ts index 31ce877de6f7..48fbc33ba96a 100644 --- a/apps/server/src/provider/ProviderRegistry.test.ts +++ b/apps/server/src/provider/ProviderRegistry.test.ts @@ -46,6 +46,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"; @@ -4748,7 +4749,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/apps/server/src/resourceTelemetry/MachineStatus.test.ts b/apps/server/src/resourceTelemetry/MachineStatus.test.ts new file mode 100644 index 000000000000..828ff5af4d83 --- /dev/null +++ b/apps/server/src/resourceTelemetry/MachineStatus.test.ts @@ -0,0 +1,167 @@ +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. `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; + 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}, '{}' + ) + `; + if (thread.session.detached) continue; + 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 a starting or running run as working, 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"] }, + { 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; + + 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: "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, 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); + }).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..2060e8e8184c --- /dev/null +++ b/apps/server/src/resourceTelemetry/MachineStatus.ts @@ -0,0 +1,182 @@ +// @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 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, + 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 IN ('preparing', 'starting', 'running') + 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') + ) + 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 13db759c4895..ffde1e0c8aad 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -10,6 +10,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"; import * as MilestoneHub from "./milestones/MilestoneHub.ts"; import * as OrchestrationMilestones from "./milestones/OrchestrationMilestones.ts"; // Effect wraps this raw Node HTTP server after its startup and write-error guards attach. @@ -216,6 +217,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"; @@ -238,6 +240,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"; @@ -341,6 +344,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)), @@ -680,6 +684,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)); @@ -740,6 +748,7 @@ const layerRuntimeCoreDependenciesBase = Layer.mergeAll( HeldHooksWaker.layer, layerThreadSettlementWorker, layerIdleCompactionWorker, + layerAutoFailoverWorker, StorageCleanup.layer.pipe(Layer.provide(ProjectionStoreV2.layer)), DatabaseStorage.layer.pipe( Layer.provide(ProjectionMaintenance.layer), @@ -774,6 +783,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)), Layer.effectDiscard( Effect.gen(function* () { yield* (yield* OrchestrationMilestones.OrchestrationMilestones).start(); diff --git a/apps/server/src/ws.test.ts b/apps/server/src/ws.test.ts index e9c4d220fa65..e235f4dadb19 100644 --- a/apps/server/src/ws.test.ts +++ b/apps/server/src/ws.test.ts @@ -99,6 +99,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"; @@ -857,6 +858,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 a348af429d03..6d07fa4f65e8 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -262,6 +262,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"; @@ -1636,6 +1637,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; @@ -2872,6 +2874,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/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index 5d0383915f8c..c2c2a63564ac 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -33,7 +33,10 @@ 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 { useMediaQuery } from "../hooks/useMediaQuery"; +import { useClientSettings, useEnvironmentIdentificationMode } from "../hooks/useSettings"; +import { machineBarAvailableAtom } from "../state/machineStatus"; +import { MachineBar } from "./machineBar/MachineBar"; import { PanelAnimationSuppressionProvider, usePanelAnimationSettings, @@ -459,6 +462,11 @@ export function AppSidebarLayout({ ? { "--workspace-controls-left": MACOS_TRAFFIC_LIGHTS_LEFT_INSET } : {} ) as CSSProperties; + const machineBarEnabled = useClientSettings((settings) => settings.machineBarEnabled); + const machineBarAvailable = useAtomValue(machineBarAvailableAtom); + // 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`, @@ -468,7 +476,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 b720e53e828d..a5d578f7df2f 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -6,6 +6,7 @@ import { draftSupportedRuntimeModes } from "./chat/runtimeModeConfig"; 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"; @@ -941,7 +942,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 = @@ -1010,7 +1011,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 ? {} @@ -2650,6 +2656,7 @@ export default function ChatView(props: ChatViewProps) { serverProjection, pendingHandoffSelectionUsable ? pendingHandoffSelection : null, providerStatuses, + Date.parse(`${nowMinute}:00Z`), ); const compactThreadUnavailable = !canOperateThread || @@ -3005,7 +3012,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. @@ -3567,7 +3574,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", @@ -3943,7 +3950,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/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index f167d82b776d..75a1d0548729 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -1485,7 +1485,7 @@ export function RightPanelTabs(props: RightPanelTabsProps) { >
AutoRoute | null; selectedModels?: ReadonlyArray<{ instanceId: ProviderInstanceId; model: string }>; onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; lockedProvider: ProviderDriverKind | null; @@ -391,7 +396,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, ); @@ -729,11 +735,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 = (() => { @@ -897,6 +904,9 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { modelJumpLabelByKey, activeModelKey, selectedModelKeySet, + autoRouteLabels: ["auto", "auto-low", "auto-medium", "auto-high"] + .map((slug) => props.autoRouteFor?.(slug)?.label ?? "") + .join("|"), }; const onWindowKeyDown = (event: globalThis.KeyboardEvent) => { @@ -1210,15 +1220,18 @@ export const ModelPickerContent = memo(function ModelPickerContent(props: { } const disabledReason = getModelDisabledReason?.(model.instanceId, model.slug) ?? null; + const autoRoute = isAutoModelSlug(model.slug) + ? (props.autoRouteFor?.(model.slug) ?? null) + : null; return ( )} - {isCustomEndpoint ? null : props.showBadge ? ( + {isCustomEndpoint ? null : isAutoModelSlug(props.modelSlug) ? ( + // Auto keeps the logo of the provider it routes to and marks it with a route badge. + + + + ) : props.showBadge ? ( { 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/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index 254b1ffeac93..078433557f9b 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -2,6 +2,7 @@ import { ANTIGRAVITY_DEFAULT_MODEL, type ProviderInstanceId, type EnvironmentId, + type ModelSelection, type ProviderDriverKind, type ResolvedKeybindingsConfig, } from "@t3tools/contracts"; @@ -26,6 +27,9 @@ import { ModelPickerContent, resolveModelPickerSelectedModel } from "./ModelPick import { retainedModelWhileProviderLocked } from "./ProviderModelPicker.logic"; import { ChatGptSharingControl } from "./ChatGptSharingControl"; import { ProviderInstanceIcon } from "./ProviderInstanceIcon"; +import { isAutoModelSlug } from "@t3tools/shared/autoModel"; +import { describeAutoRoute } from "./autoRoute"; +import { useNowMinute } from "../../hooks/useNowMinute"; import { ModelEsque, getDisplayModelName, getTriggerDisplayModelName } from "./providerIconUtils"; import { shouldShowInstanceBadge, type ProviderInstanceEntry } from "../../providerInstances"; import { ComposerControl, type ComposerControlSize } from "./ComposerControl"; @@ -93,6 +97,8 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { workspaceCwd?: string | null; activeInstanceId: ProviderInstanceId; model: string; + /** The selection's options; for the `auto` model they carry its level. */ + modelSelectionOptions?: ModelSelection["options"]; selectedModels?: ReadonlyArray<{ instanceId: ProviderInstanceId; model: string }>; onToggleModel?: (instanceId: ProviderInstanceId, model: string) => void; lockedProvider: ProviderDriverKind | null; @@ -130,6 +136,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 +179,36 @@ 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 = isAutoModelSlug(props.model); + const now = Date.parse(nowMinute); + // Names the model Auto would pick now, at this selection's level (default level elsewhere). + const autoRoute = describeAutoRoute({ + entries: props.instanceEntries, + ...(isAuto ? { model: props.model } : {}), + ...(isAuto && props.modelSelectionOptions ? { options: props.modelSelectionOptions } : {}), + now, + }); + // Each Auto level row in the list names its own route. + const autoRouteFor = (slug: string) => + describeAutoRoute({ entries: props.instanceEntries, model: slug, now }); + // 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 = 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); @@ -297,6 +324,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { workspaceCwd={props.workspaceCwd ?? null} activeInstanceId={activeInstanceId} model={props.model} + autoRouteFor={autoRouteFor} {...(props.selectedModels !== undefined ? { selectedModels: props.selectedModels } : {})} {...(props.onToggleModel ? { @@ -398,6 +426,7 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { key={`${selection.instanceId}:${selection.model}`} driverKind={selection.entry.driverKind} displayName={selection.entry.displayName} + modelSlug={selection.model} accentColor={selection.entry.accentColor} acpRegistryAgentId={selection.entry.acpRegistryAgentId} acpRegistryIconUrl={selection.entry.acpRegistryIconUrl} @@ -416,8 +445,9 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { // Narrow compacted composers hide the provider icon before truncating the name. hiddenKeys.has(threadKey({ environmentId: props.environmentId, threadId })); // While hiding, an unloaded parent, fork or transfer may be hidden; unloaded subagent @@ -644,7 +653,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( @@ -673,8 +682,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 && @@ -806,6 +819,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 = @@ -814,7 +829,7 @@ export function ThreadRelationshipsPanel(props: { : undefined) ?? threadRelationshipRowStatus(graph, { threadId, edge }); const RelationshipIcon = isParent ? CornerLeftUpIcon - : isSubagent + : isAgent ? BotIcon : node?.thread?.lineage.sideChat === true ? MessagesSquareIcon @@ -894,7 +909,7 @@ export function ThreadRelationshipsPanel(props: { const relationshipContent = ( <> , + 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, 95), + 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 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", () => { + 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..24b9e863738f --- /dev/null +++ b/apps/web/src/components/chat/autoRoute.ts @@ -0,0 +1,56 @@ +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; +} + +/** Claude instances are named "Auto" (account A) and "Auto B"; other providers keep their name. */ +export function claudeAccountLetter(displayName: string): "A" | "B" { + return /\bB$/.test(displayName) ? "B" : "A"; +} + +/** + * 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; + /** `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: input.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; + const account = + 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/chat/useQueuedRunEdit.browser.test.tsx b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx index ca4118e0ff28..66d66cce0b84 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx +++ b/apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx @@ -35,7 +35,11 @@ import { readAttachmentUpload, useAttachmentUploadStore } from "../../lib/attach interface RunStatus { readonly id: RunId; readonly status: string; - readonly modelSelection?: { readonly instanceId: ProviderInstanceId; readonly model: string }; + readonly modelSelection?: { + readonly instanceId: ProviderInstanceId; + readonly model: string; + readonly options?: ReadonlyArray<{ readonly id: string; readonly value: string }>; + }; readonly activeAttemptId?: string; } @@ -133,6 +137,7 @@ function Harness(props: { readonly runStatus: string; readonly hookRef: RefObject; readonly messages: ReadonlyArray; + readonly runModelSelection?: RunStatus["modelSelection"]; }) { const result = useQueuedRunEdit({ environmentId: ENV, @@ -140,7 +145,13 @@ function Harness(props: { threadDraftTarget: props.threadRef, activeThreadId: props.threadRef.threadId, serverProjection: projection( - [{ id: RUN, status: props.runStatus, modelSelection: savedContent("").modelSelection }], + [ + { + id: RUN, + status: props.runStatus, + modelSelection: props.runModelSelection ?? savedContent("").modelSelection, + }, + ], props.messages, ), promptRef: { current: "" }, @@ -179,10 +190,17 @@ function view( runStatus: string, hook: { current: HookResult | null }, messages: ReadonlyArray = [], + runModelSelection?: RunStatus["modelSelection"], ) { return ( - + ); } @@ -692,3 +710,20 @@ it.each([false, true])( ); }, ); + +// Fork: the composer keeps only the options a model describes, so it would send an Auto-routed +// run's model without its `auto` stamp and pin the message off Auto. +it("opens an Auto-routed queued message on its Auto level", async () => { + const { hook } = setup(); + const instanceId = ProviderInstanceId.make("claudeAgent"); + await using _screen = await render( + view(THREAD_A, "queued", hook, [], { + instanceId, + model: "claude-opus-5-5", + options: [{ id: "auto", value: "medium" }], + }), + ); + await beginChangedEdit(hook); + const draft = useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget); + expect(draft?.modelSelectionByProvider[instanceId]).toEqual({ instanceId, model: "auto-medium" }); +}); diff --git a/apps/web/src/components/chat/useQueuedRunEdit.ts b/apps/web/src/components/chat/useQueuedRunEdit.ts index c8e5038e06db..43a1cb400c2a 100644 --- a/apps/web/src/components/chat/useQueuedRunEdit.ts +++ b/apps/web/src/components/chat/useQueuedRunEdit.ts @@ -30,6 +30,7 @@ import { restoreAttachmentOnlyBootstrapPrompt, stripAttachmentOnlyBootstrapPrompt, } from "@t3tools/shared/composerContextReferences"; +import { autoLevelSelection } from "@t3tools/shared/autoModel"; import { Atom } from "effect/reactivity"; import type { RefObject } from "react"; import { useAssetUrls } from "../../assets/assetUrls"; @@ -305,11 +306,15 @@ export function useQueuedRunEdit(input: { store.setPrompt(target, text); const run = serverProjection?.runs.find((run) => run.id === request.runId); const followsThreadSelection = message?.followsThreadSelection === true; - const originalModelSelection = followsThreadSelection - ? serverProjection?.thread.modelSelection - : run?.modelSelection; + // An Auto-routed pick opens as its Auto level, as in the picker, so saving routes it again. + const originalModelSelection = autoLevelSelection( + followsThreadSelection ? serverProjection?.thread.modelSelection : run?.modelSelection, + ); if (run && !followsThreadSelection) - store.setModelSelection(target, run.modelSelection, { explicit: true, replaceOptions: true }); + store.setModelSelection(target, autoLevelSelection(run.modelSelection), { + explicit: true, + replaceOptions: true, + }); store.setThreadContexts( target, records.filter((record): record is ThreadContextRecord => record.kind === "thread"), diff --git a/apps/web/src/components/machineBar/MachineBar.tsx b/apps/web/src/components/machineBar/MachineBar.tsx new file mode 100644 index 000000000000..0fa47f4f971a --- /dev/null +++ b/apps/web/src/components/machineBar/MachineBar.tsx @@ -0,0 +1,379 @@ +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 { providersIgnoringCheckedAtAtom } from "../../state/server"; +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} + + ); +} + +// 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 ( + <> +
{label}
+
{value}
+ + ); +} + +function MachineDetails({ + chip, + status, +}: { + readonly chip: MachineChip; + readonly status: MachineStatus; +}) { + 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); + 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 ? ( + // The averages the room gates read: 1 minute for CPU and memory, 10 s for IO. + + ) : 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 }: { readonly chip: MachineChip }) { + const gt = useGT(); + const { status, capacity } = chip; + const summary = + status === null || capacity === null + ? 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}}", + { + machine: chip.name, + working: status.working, + open: status.open, + free: gigabytes(status.memory.availableBytes), + more: capacity.more, + }, + ); + return ( + + + } + > + {chip.name} + + {status === null || capacity === null ? ( + chip.loading ? null : ( + {gt("off")} + ) + ) : ( + + {status.maxWorkingAgents === null + ? status.working + : `${status.working}/${status.maxWorkingAgents}`} + {` · ${gigabytes(status.memory.availableBytes)} · +${capacity.more}`} + + )} + + + {status === null ? ( +

+ {chip.loading + ? summary + : 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), now); + return ( +
+
+ {chips.map((chip) => ( + + ))} +
+ + +
+ ); +} 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..31414a663d72 --- /dev/null +++ b/apps/web/src/components/machineBar/machineBar.logic.test.ts @@ -0,0 +1,125 @@ +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", () => { + 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, 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, 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 }, + ]); + }); +}); + +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..5c12f147644e --- /dev/null +++ b/apps/web/src/components/machineBar/machineBar.logic.ts @@ -0,0 +1,74 @@ +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"; + +// 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; + 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; + /** 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, + now: number, +): MachineChip[] { + const chips: MachineChip[] = []; + const hosts = new Set(); + 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); + chips.push({ + key, + environmentId, + environmentLabel: label, + name: status?.hostname ?? label, + status, + capacity: status === null ? null : machineCapacity(status), + loading: status === null && loading, + }); + } + 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 10d4e2c6fab5..385827f08297 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -547,6 +547,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")] : []), @@ -620,6 +623,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")] : []), @@ -739,6 +746,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, @@ -750,6 +758,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, @@ -985,6 +994,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")} + /> + } + /> @@ -2068,7 +2103,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={ @@ -2385,6 +2420,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 ( @@ -2494,6 +2536,48 @@ export function MaintenanceSettingsPanel() { /> } /> + + updateSettings({ machineStatus: DEFAULT_UNIFIED_SETTINGS.machineStatus }) + } + /> + ) : null + } + control={ + + } + /> diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts index 2bbdd7867c3c..cc0bece75431 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.test.ts @@ -178,6 +178,26 @@ describe("editing scheduled task branch settings", () => { }); }); +// Fork: the effort picker keeps only options a model describes, so it would drop the `auto` +// option of a task scheduled from an Auto thread and pin the task off Auto. +describe("editing an Auto-routed scheduled task", () => { + it("opens the task on its Auto level", () => { + const instanceId = ProviderInstanceId.make("claudeAgent"); + const draft = taskToDraft({ + ...legacyTask, + modelSelection: { + instanceId, + model: "claude-opus-5-5", + options: [ + { id: "effort", value: "high" }, + { id: "auto", value: "medium" }, + ], + }, + }); + expect(draft.modelSelection).toEqual({ instanceId, model: "auto-medium" }); + }); +}); + describe("fixed-time scheduled tasks", () => { it("pads a stored single-digit hour so the time input shows it", () => { const draft = taskToDraft({ diff --git a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts index 0651d13ad7a7..ec82a24b648a 100644 --- a/apps/web/src/components/settings/scheduledTasksSettings.logic.ts +++ b/apps/web/src/components/settings/scheduledTasksSettings.logic.ts @@ -24,6 +24,7 @@ import { type WebhookFilterDraft, } from "@t3tools/client-runtime/scheduled-task-webhook"; import { scheduleTimeZoneLabel } from "@t3tools/client-runtime/scheduled-task-time-zone"; +import { autoLevelSelection } from "@t3tools/shared/autoModel"; import type { TimestampFormat } from "@t3tools/contracts/settings"; import { msg } from "gt-react"; @@ -342,7 +343,8 @@ export function taskToDraft(task: ScheduledTask): DraftState { task.workspaceStrategy.type === "existing_worktree" ? task.workspaceStrategy.worktreePath : "", - modelSelection: task.modelSelection, + // An Auto-routed pick opens as its Auto level, as in the picker, so saving keeps it on Auto. + modelSelection: autoLevelSelection(task.modelSelection), runtimeMode: task.runtimeMode, interactionMode: task.interactionMode, ...(schedule.type === "webhook" && schedule.signature !== null diff --git a/apps/web/src/components/settings/settingsSearch.ts b/apps/web/src/components/settings/settingsSearch.ts index a7629c16be08..ba5d17ff3dcf 100644 --- a/apps/web/src/components/settings/settingsSearch.ts +++ b/apps/web/src/components/settings/settingsSearch.ts @@ -498,7 +498,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", @@ -506,6 +510,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)"), @@ -878,6 +888,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/components/usage/UsageLimitsPooled.browser.test.tsx b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx index 886dc684a10d..c6fa95036003 100644 --- a/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx +++ b/apps/web/src/components/usage/UsageLimitsPooled.browser.test.tsx @@ -73,7 +73,16 @@ describe("UsageLimitsPooled next refill", () => { ...managedChatGpt(instanceId, instanceId), usageLimits: { checkedAt, - windows: [{ id: "weekly", label: "Weekly", kind: "weekly", usedPercent, resetsAt }], + windows: [ + { + id: "session", + label: "Session", + kind: "session", + usedPercent: 0, + resetsAt: "2026-10-25T20:00:00.000Z", + }, + { id: "weekly", label: "Weekly", kind: "weekly", usedPercent, resetsAt }, + ], }, }; } @@ -85,7 +94,8 @@ describe("UsageLimitsPooled next refill", () => { serverConfig: { providers: [ account("Work", 20, "2026-10-25T17:00:00.000Z"), - account("Personal", 60, "2026-10-25T18:00:00.000Z"), + account("Later", 40, "2026-10-25T18:10:00.000Z"), + account("Personal", 60, "2026-10-25T18:01:00.000Z"), ], }, }, @@ -94,12 +104,65 @@ describe("UsageLimitsPooled next refill", () => { await using screen = await render( , ); - await expect.element(screen.getByText("↻ +30%", { exact: true })).toBeVisible(); - await expect.element(screen.getByText("↻ +30% in 30m")).toBeVisible(); + // The fork's "Next reset" stat reads "+
+ {suggestion ? ( +
+
+ + + Reset advice: + + + {suggestion.actionLabel} + +
+ {suggestion.reason} +
+ ) : null} {choices.length > 0 && redeem ? (
{choices.map((choice) => ( @@ -312,6 +349,7 @@ function PoolSegment({ readonly now: number; readonly index: number; readonly showAccountName: boolean; + readonly poolMembers?: readonly LimitPoolMember[] | undefined; }) { return account.redeem ? ( @@ -354,6 +392,7 @@ function SegmentTriggers({ window, reset, redeem, + poolMembers, refillPercent, color, now, @@ -367,7 +406,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); @@ -573,6 +612,7 @@ function PoolBar({ now={now} index={position + 1} showAccountName={pool.columns.length > 1} + poolMembers={pool.members} /> ) : pool.kind === "monthly" && member.account.limits.zeroSpendCap ? (
+ {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 gt = useGT(); const m = useMessages(); - const nextRefill = pool.resets.find((reset) => reset.at > now && 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, undefined, m); + const nextRefill = projection.refills + .filter((refill) => refill.at > now) + .sort((left, right) => left.at - right.at)[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}% - {" "} - in {formatDuration(nextRefill.at - now, m)} - - ) : 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} + {(() => { + 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}
); } @@ -668,6 +790,7 @@ function PoolSection({ pool, now }: { readonly pool: LimitPool; readonly now: nu 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, @@ -691,6 +868,12 @@ export function UsageLimitsPooled({ const [segmentPopover] = useState(() => 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 quotaSources = collectHttpQuotaSources(presentations); const notices = collectLimitNotices(presentations, m); const externalLinks = collectExternalUsageLinks(presentations, m); @@ -704,6 +887,7 @@ export function UsageLimitsPooled({ No provider on the selected environments reports subscription limits.

) : null} + {pools.map((pool) => ( 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/apps/web/src/i18n/translations/de.json b/apps/web/src/i18n/translations/de.json index 7e649c108dd5..ffd8b37ff533 100644 --- a/apps/web/src/i18n/translations/de.json +++ b/apps/web/src/i18n/translations/de.json @@ -4334,6 +4334,7 @@ "94124ad2133e3aed": "Unbekannt", "000646e27e304b8b": "Nebenchat öffnen", "56567586cbe00c86": "Kontextübergabe in diesem Chat öffnen", + "ec77e9d3bc2b6d99": "Gestarteten Thread in diesem Chat öffnen", "405e76cdd602bbcf": "Subagent öffnen", "520c15dbd507b804": "Übergeordneten Agenten in diesem Chat öffnen", "309b160785f6c473": "Fork in diesem Chat öffnen", @@ -10225,7 +10226,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.", @@ -11863,7 +11864,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", @@ -12280,30 +12281,20 @@ "4df3ff1be768a7ab": "{name}: {remaining} % übrig", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "0-$-Limit", + "98947080075a0e9f": "von {capacity} %", + "319d956d8dc9626e": "Kontingent leer", + "7edac2c4173fee09": "Nicht bis {date}", + "649af7801ecb5d6c": "Jetzt leer", + "7b3b4057463829e0": "Zuerst leer", + "0cc4fd1cf5ac9270": "jetzt", + "ade42d3734d25cb8": "in {duration}", + "94fcce9e98d053ad": "Keins", + "e7c90232ad94f3ca": "Nächstes Zurücksetzen", + "22f3ae62c7a65e0f": "Verbrauch, letzte 3 h", + "737171d0d80cb0d0": "Verbrauch, Fensterschnitt", "a16b48709357a5a7": "Nutzung verwalten", - "a00e74aaa421c524": "übrig", - "0e34c3076c08feb2": [ - { - "t": "span", - "i": 1, - "c": [ - "↻ +", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - }, - "%" - ] - }, - " ", - "in ", - { - "i": 3, - "k": "_gt_value_3", - "v": "v" - } - ], + "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", @@ -12394,6 +12385,10 @@ "b11af3f3da3d494e": "Die Summen sind unvollständig, während ausgewählte Umgebungen scannen.", "8062808b87ce6032": "Modellpreise", "cf5409d12fc3f53b": "Alle Anbieter", + "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.", @@ -12971,5 +12966,48 @@ }, " braucht eine Begründung." ], - "91aadfc843c600de": "Google-Konto bestätigen" + "91aadfc843c600de": "Google-Konto bestätigen", + "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", + "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", + "dffec1f0549853b0": "{machine}: wartet auf Daten" } diff --git a/apps/web/src/i18n/translations/en.json b/apps/web/src/i18n/translations/en.json index 1a6537d2ed87..58413fe5f02a 100644 --- a/apps/web/src/i18n/translations/en.json +++ b/apps/web/src/i18n/translations/en.json @@ -4333,6 +4333,7 @@ "94124ad2133e3aed": "Unknown", "000646e27e304b8b": "Open side chat", "56567586cbe00c86": "Open context transfer in this chat", + "ec77e9d3bc2b6d99": "Open launched thread in this chat", "405e76cdd602bbcf": "Open subagent", "520c15dbd507b804": "Open parent agent in this chat", "309b160785f6c473": "Open fork in this chat", @@ -10234,7 +10235,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.", @@ -11871,7 +11872,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", @@ -12288,30 +12289,20 @@ "4df3ff1be768a7ab": "{name}: {remaining}% 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", - "0e34c3076c08feb2": [ - { - "t": "span", - "i": 1, - "c": [ - "↻ +", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - }, - "%" - ] - }, - " ", - "in ", - { - "i": 3, - "k": "_gt_value_3", - "v": "v" - } - ], + "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", @@ -12402,6 +12393,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.", @@ -12980,5 +12975,48 @@ }, " needs a reason." ], - "91aadfc843c600de": "Verify Google account" + "91aadfc843c600de": "Verify Google account", + "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", + "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", + "dffec1f0549853b0": "{machine}: waiting for data" } diff --git a/apps/web/src/i18n/translations/es.json b/apps/web/src/i18n/translations/es.json index a2336220fa13..dcf7e9defee0 100644 --- a/apps/web/src/i18n/translations/es.json +++ b/apps/web/src/i18n/translations/es.json @@ -4331,6 +4331,7 @@ "94124ad2133e3aed": "Desconocido", "000646e27e304b8b": "Abrir chat lateral", "56567586cbe00c86": "Abrir la transferencia de contexto en este chat", + "ec77e9d3bc2b6d99": "Abrir el hilo iniciado en este chat", "405e76cdd602bbcf": "Abrir subagente", "520c15dbd507b804": "Abrir el agente principal en este chat", "309b160785f6c473": "Abrir la bifurcación en este chat", @@ -10222,7 +10223,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.", @@ -11856,7 +11857,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", @@ -12273,30 +12274,20 @@ "4df3ff1be768a7ab": "{name}: queda un {remaining}%", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Límite de 0 $", + "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", - "a00e74aaa421c524": "restante", - "0e34c3076c08feb2": [ - { - "t": "span", - "i": 1, - "c": [ - "↻ +", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - }, - "%" - ] - }, - " ", - "en ", - { - "i": 3, - "k": "_gt_value_3", - "v": "v" - } - ], + "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", @@ -12387,6 +12378,10 @@ "b11af3f3da3d494e": "Los totales son parciales mientras se escanean los entornos seleccionados.", "8062808b87ce6032": "Precios de modelos", "cf5409d12fc3f53b": "Todos los proveedores", + "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.", @@ -12966,5 +12961,48 @@ }, " necesita un motivo." ], - "91aadfc843c600de": "Verificar cuenta de Google" + "91aadfc843c600de": "Verificar cuenta de Google", + "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", + "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", + "dffec1f0549853b0": "{machine}: esperando datos" } diff --git a/apps/web/src/i18n/translations/fr.json b/apps/web/src/i18n/translations/fr.json index 112747b24d0f..0b311be124d6 100644 --- a/apps/web/src/i18n/translations/fr.json +++ b/apps/web/src/i18n/translations/fr.json @@ -4332,6 +4332,7 @@ "94124ad2133e3aed": "Inconnu", "000646e27e304b8b": "Ouvrir la discussion annexe", "56567586cbe00c86": "Ouvrir le transfert de contexte dans cette discussion", + "ec77e9d3bc2b6d99": "Ouvrir le fil lancé dans cette discussion", "405e76cdd602bbcf": "Ouvrir le sous-agent", "520c15dbd507b804": "Ouvrir l’agent parent dans cette discussion", "309b160785f6c473": "Ouvrir le fork dans cette discussion", @@ -10224,7 +10225,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.", @@ -11861,7 +11862,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", @@ -12278,30 +12279,20 @@ "4df3ff1be768a7ab": "{name} : {remaining} % restant", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Plafond de 0 $", + "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", - "a00e74aaa421c524": "restant", - "0e34c3076c08feb2": [ - { - "t": "span", - "i": 1, - "c": [ - "↻ +", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - }, - "%" - ] - }, - " ", - "dans ", - { - "i": 3, - "k": "_gt_value_3", - "v": "v" - } - ], + "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", @@ -12392,6 +12383,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} : 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.", @@ -12971,5 +12966,48 @@ }, " nécessite une raison." ], - "91aadfc843c600de": "Vérifier le compte Google" + "91aadfc843c600de": "Vérifier le compte Google", + "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", + "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", + "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 05b85292e7ae..bcfd93572c33 100644 --- a/apps/web/src/i18n/translations/ja.json +++ b/apps/web/src/i18n/translations/ja.json @@ -4321,6 +4321,7 @@ "94124ad2133e3aed": "不明", "000646e27e304b8b": "サイドチャットを開く", "56567586cbe00c86": "このチャットでコンテキストの引き継ぎを開く", + "ec77e9d3bc2b6d99": "このチャットで起動したスレッドを開く", "405e76cdd602bbcf": "サブエージェントを開く", "520c15dbd507b804": "このチャットで親エージェントを開く", "309b160785f6c473": "このチャットでフォークを開く", @@ -10176,7 +10177,7 @@ "6fc9e5e722cf3c73": "ghq と同様に、上のフォルダーの下の github.com/owner/repo にクローンします。", "bee548d674abd0d2": "「ホスト別フォルダーにクローン」をデフォルトにリセット", "ef27c4211844aef9": "スヌーズ", - "4df30d44eb0b0728": "使用量の上限がリセットされたら、スレッドを自動的に再開します。自動再開は各スレッドでキャンセルできます。", + "4e8a6e262304c240": "使用量の上限に達したスレッドを続行します。Auto のスレッドは余裕のある次のサブスクリプションに移り、それ以外のスレッドは上限のリセット時に再開します。自動再開は各スレッドでキャンセルできます。", "0769f91ca46e3003": "使用量の上限がリセットされるまでスレッドをスヌーズします。リセット後にエージェントを続行するには、自動再開を有効にしてください。", "7c27e91e75cce7a3": "自動で対応済みにする", "cf6c5aa9b63957e6": "プルリクエストがマージされたらスレッドを対応済みにします。クローズされたプルリクエストは引き続き自動的に対応済みになります。", @@ -11811,7 +11812,7 @@ "c437e0f28c6d4a4b": "並べ替え プロジェクト サイドバー 手動 作成日 最近 sort", "cb309dc06cf679ae": "スヌーズ プリセット 時刻 後で 今夜 明日 来週 リマインド snooze", "6751449c6188912d": "使用量 クォータ レート制限 リセット 再開 復旧 続行 usage limit", - "0aedae6a82c09429": "使用量 クォータ レート制限 リセット 復旧 続行 usage limit", + "5190923c9a9d6a2e": "使用量 クォータ レート制限 リセット 復旧 続行 auto フェイルオーバー 切り替え サブスクリプション アカウント", "85dbcfec2d41f534": "非表示 折りたたみ 実行中 監視中 スレッド 受信トレイ サイドバー 棚 作業中 working", "405a2295152c9d77": "ベータ フォルダー プロジェクト ツリー クラシック サイドバー beta folders", "de42c4690914cee4": "ベータ シンプルなサイドバー フォルダー 行 複数行 ブランチ プルリクエスト 詳細 beta boring sidebar", @@ -12228,30 +12229,20 @@ "4df3ff1be768a7ab": "{name}: 残り {remaining}%", "7aaaff1c6484f25c": "セグメント", "8bcab2ef61de6518": "上限 $0", + "98947080075a0e9f": "/ {capacity}%", + "319d956d8dc9626e": "プールが空になる", + "7edac2c4173fee09": "{date} までは空にならない", + "649af7801ecb5d6c": "今すぐ空", + "7b3b4057463829e0": "最初に空になる", + "0cc4fd1cf5ac9270": "今", + "ade42d3734d25cb8": "{duration}後", + "94fcce9e98d053ad": "なし", + "e7c90232ad94f3ca": "次のリセット", + "22f3ae62c7a65e0f": "消費量(直近 3 時間)", + "737171d0d80cb0d0": "消費量(期間平均)", "a16b48709357a5a7": "使用量を管理", - "a00e74aaa421c524": "残り", - "0e34c3076c08feb2": [ - { - "t": "span", - "i": 1, - "c": [ - "↻ +", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - }, - "%" - ] - }, - " ", - { - "i": 3, - "k": "_gt_value_3", - "v": "v" - }, - "後" - ], + "e20b23cc4eee52c1": "リセットのアドバイス:", + "aca138d5adaa5f69": "サブスクリプション", "8bd6f07136317c8f": "選択した環境には、サブスクリプションの上限を報告するプロバイダーがありません。", "87f5d0c61b335f38": "接続したアカウントで ChatGPT の使用量を表示します。", "5b4c71b36b979e80": "コスト", @@ -12342,6 +12333,10 @@ "b11af3f3da3d494e": "選択した環境のスキャン中は、合計は一部のみです。", "8062808b87ce6032": "モデルの価格", "cf5409d12fc3f53b": "すべてのプロバイダー", + "498a69c10b2ed2d9": "{label}: プールの残りクォータ(記録と予測)", + "b05ed15d19d4a485": "{time} に空", + "56fb015730a158bc": "予測", + "fc3a1241f943cae6": "現在", "55e99aaf3d0e6af4": "価格が読み込まれていません", "ed447281261f2d0e": "読み取り専用アクセス", "67633defded66bf7": "モデル ID を入力してください。", @@ -12907,5 +12902,48 @@ }, "には理由が必要です。" ], - "91aadfc843c600de": "Google アカウントを確認" + "91aadfc843c600de": "Google アカウントを確認", + "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} が作業中", + "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": "マシンバー 最大 エージェント 同時 上限 余裕 メモリ", + "dffec1f0549853b0": "{machine}: データを待機中" } diff --git a/apps/web/src/i18n/translations/ko.json b/apps/web/src/i18n/translations/ko.json index 646f0b25db18..46521b6cd314 100644 --- a/apps/web/src/i18n/translations/ko.json +++ b/apps/web/src/i18n/translations/ko.json @@ -4318,6 +4318,7 @@ "94124ad2133e3aed": "알 수 없음", "000646e27e304b8b": "사이드 채팅 열기", "56567586cbe00c86": "이 채팅에서 컨텍스트 전달 열기", + "ec77e9d3bc2b6d99": "이 채팅에서 시작한 스레드 열기", "405e76cdd602bbcf": "서브에이전트 열기", "520c15dbd507b804": "이 채팅에서 상위 에이전트 열기", "309b160785f6c473": "이 채팅에서 포크 열기", @@ -10178,7 +10179,7 @@ "6fc9e5e722cf3c73": "ghq처럼 위 폴더 아래 github.com/owner/repo에 복제합니다.", "bee548d674abd0d2": "호스트 폴더로 복제 기본값으로 재설정", "ef27c4211844aef9": "다시 알림", - "4df30d44eb0b0728": "사용량 한도가 초기화되면 스레드를 자동으로 재개합니다. 각 스레드에서 자동 재개를 취소할 수 있습니다.", + "4e8a6e262304c240": "사용량 한도 후 스레드를 계속합니다. Auto 스레드는 여유가 있는 다음 구독으로 옮겨지고, 다른 스레드는 한도가 초기화되면 다시 시작됩니다. 각 스레드에서 자동 재개를 취소할 수 있습니다.", "0769f91ca46e3003": "사용량 한도가 초기화될 때까지 스레드를 미룹니다. 초기화 후 에이전트를 계속하려면 자동 재개를 사용하세요.", "7c27e91e75cce7a3": "자동 정리", "cf6c5aa9b63957e6": "풀 리퀘스트가 병합되면 스레드를 정리합니다. 닫힌 풀 리퀘스트는 계속 자동으로 정리됩니다.", @@ -11807,7 +11808,7 @@ "c437e0f28c6d4a4b": "프로젝트 정렬 사이드바 수동 생성일 최근", "cb309dc06cf679ae": "다시 알림 프리셋 시간 나중에 오늘 밤 내일 다음 주 알림", "6751449c6188912d": "사용량 할당량 속도 제한 초기화 깨우기 복구 계속", - "0aedae6a82c09429": "사용량 할당량 속도 제한 초기화 복구 계속", + "5190923c9a9d6a2e": "사용량 할당량 속도 제한 초기화 복구 계속 auto 장애 조치 전환 구독 계정", "85dbcfec2d41f534": "숨기기 접기 실행 중 모니터링 스레드 인박스 사이드바 선반 작업 중", "405a2295152c9d77": "베타 폴더 프로젝트 트리 클래식 사이드바", "de42c4690914cee4": "베타 단순 사이드바 폴더 행 여러 줄 브랜치 풀 리퀘스트 세부 정보", @@ -12224,30 +12225,20 @@ "4df3ff1be768a7ab": "{name}: {remaining}% 남음", "7aaaff1c6484f25c": "구간", "8bcab2ef61de6518": "$0 한도", + "98947080075a0e9f": "/ {capacity}%", + "319d956d8dc9626e": "풀 소진", + "7edac2c4173fee09": "{date}까지 소진 안 됨", + "649af7801ecb5d6c": "지금 소진", + "7b3b4057463829e0": "가장 먼저 소진", + "0cc4fd1cf5ac9270": "지금", + "ade42d3734d25cb8": "{duration} 후", + "94fcce9e98d053ad": "없음", + "e7c90232ad94f3ca": "다음 초기화", + "22f3ae62c7a65e0f": "소비량, 최근 3시간", + "737171d0d80cb0d0": "소비량, 기간 평균", "a16b48709357a5a7": "사용량 관리", - "a00e74aaa421c524": "남음", - "0e34c3076c08feb2": [ - { - "t": "span", - "i": 1, - "c": [ - "↻ +", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - }, - "%" - ] - }, - " ", - { - "i": 3, - "k": "_gt_value_3", - "v": "v" - }, - " 후" - ], + "e20b23cc4eee52c1": "초기화 조언:", + "aca138d5adaa5f69": "구독", "8bd6f07136317c8f": "선택한 환경에 구독 한도를 보고하는 제공자가 없습니다.", "87f5d0c61b335f38": "연결된 계정으로 ChatGPT에서 사용량을 확인하세요.", "5b4c71b36b979e80": "비용", @@ -12338,6 +12329,10 @@ "b11af3f3da3d494e": "선택한 환경을 스캔하는 동안에는 합계가 일부만 표시됩니다.", "8062808b87ce6032": "모델 가격", "cf5409d12fc3f53b": "모든 제공자", + "498a69c10b2ed2d9": "{label}: 풀의 남은 할당량, 기록 및 예측", + "b05ed15d19d4a485": "{time} 소진", + "56fb015730a158bc": "예측", + "fc3a1241f943cae6": "현재", "55e99aaf3d0e6af4": "가격을 불러오지 않음", "ed447281261f2d0e": "읽기 전용 액세스", "67633defded66bf7": "모델 ID를 입력하세요.", @@ -12904,5 +12899,48 @@ }, "에는 이유가 필요합니다." ], - "91aadfc843c600de": "Google 계정 확인" + "91aadfc843c600de": "Google 계정 확인", + "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}개 작업 중", + "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": "머신 바 최대 에이전트 동시 한도 여유 메모리", + "dffec1f0549853b0": "{machine}: 데이터 기다리는 중" } diff --git a/apps/web/src/i18n/translations/pt-BR.json b/apps/web/src/i18n/translations/pt-BR.json index 1263f2eb5ce1..e21faaf458a0 100644 --- a/apps/web/src/i18n/translations/pt-BR.json +++ b/apps/web/src/i18n/translations/pt-BR.json @@ -4331,6 +4331,7 @@ "94124ad2133e3aed": "Desconhecido", "000646e27e304b8b": "Abrir chat paralelo", "56567586cbe00c86": "Abrir a transferência de contexto neste chat", + "ec77e9d3bc2b6d99": "Abrir a thread iniciada neste chat", "405e76cdd602bbcf": "Abrir subagente", "520c15dbd507b804": "Abrir o agente principal neste chat", "309b160785f6c473": "Abrir o fork neste chat", @@ -10224,7 +10225,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.", @@ -11861,7 +11862,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", @@ -12278,30 +12279,20 @@ "4df3ff1be768a7ab": "{name}: {remaining}% restante", "7aaaff1c6484f25c": "Segmento", "8bcab2ef61de6518": "Limite de $0", + "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", - "a00e74aaa421c524": "restante", - "0e34c3076c08feb2": [ - { - "t": "span", - "i": 1, - "c": [ - "↻ +", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - }, - "%" - ] - }, - " ", - "em ", - { - "i": 3, - "k": "_gt_value_3", - "v": "v" - } - ], + "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", @@ -12392,6 +12383,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}: 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.", @@ -12971,5 +12966,48 @@ }, " precisa de um motivo." ], - "91aadfc843c600de": "Verificar conta Google" + "91aadfc843c600de": "Verificar conta Google", + "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", + "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", + "dffec1f0549853b0": "{machine}: aguardando dados" } diff --git a/apps/web/src/i18n/translations/ru.json b/apps/web/src/i18n/translations/ru.json index bc27cf1f5695..1e71b847d7c9 100644 --- a/apps/web/src/i18n/translations/ru.json +++ b/apps/web/src/i18n/translations/ru.json @@ -4331,6 +4331,7 @@ "94124ad2133e3aed": "Неизвестно", "000646e27e304b8b": "Открыть боковой чат", "56567586cbe00c86": "Открыть передачу контекста в этом чате", + "ec77e9d3bc2b6d99": "Открыть запущенный тред в этом чате", "405e76cdd602bbcf": "Открыть субагента", "520c15dbd507b804": "Открыть родительского агента в этом чате", "309b160785f6c473": "Открыть ответвление в этом чате", @@ -10227,7 +10228,7 @@ "6fc9e5e722cf3c73": "Клоны попадают в github.com/owner/repo внутри папки выше, как в ghq.", "bee548d674abd0d2": "Сбросить клонирование в папки хоста к значению по умолчанию", "ef27c4211844aef9": "Отложить", - "4df30d44eb0b0728": "Автоматически возобновлять треды при сбросе лимитов использования. Автовозобновление можно отменить в каждом треде.", + "4e8a6e262304c240": "Продолжать треды после лимита использования: треды на Auto переходят на следующую подписку с запасом, остальные возобновляются после сброса лимита. Автовозобновление можно отменить в каждом треде.", "0769f91ca46e3003": "Откладывать треды до сброса лимитов использования. Включите автовозобновление, чтобы агент продолжил после сброса.", "7c27e91e75cce7a3": "Авторазбор", "cf6c5aa9b63957e6": "Отмечать тред разобранным при слиянии его пул-реквеста. Треды с закрытыми пул-реквестами по-прежнему разбираются автоматически.", @@ -11862,7 +11863,7 @@ "c437e0f28c6d4a4b": "сортировка проекты боковая панель вручную создание недавние", "cb309dc06cf679ae": "отложить пресеты время позже вечером завтра на следующей неделе напомнить", "6751449c6188912d": "использование квота лимит запросов сброс пробуждение восстановить продолжить", - "0aedae6a82c09429": "использование квота лимит запросов сброс восстановить продолжить", + "5190923c9a9d6a2e": "использование квота лимит запросов сброс восстановить продолжить auto переключение подписка аккаунт", "85dbcfec2d41f534": "скрыть свернуть выполняющиеся отслеживающие треды входящие боковая панель полка в работе", "405a2295152c9d77": "бета папки дерево проектов классическая боковая панель", "de42c4690914cee4": "бета простая боковая панель строки папок многострочные ветка пул-реквест подробности", @@ -12279,30 +12280,20 @@ "4df3ff1be768a7ab": "{name}: осталось {remaining}%", "7aaaff1c6484f25c": "Сегмент", "8bcab2ef61de6518": "Лимит $0", + "98947080075a0e9f": "из {capacity}%", + "319d956d8dc9626e": "Пул исчерпан", + "7edac2c4173fee09": "Не раньше {date}", + "649af7801ecb5d6c": "Исчерпан сейчас", + "7b3b4057463829e0": "Первым исчерпается", + "0cc4fd1cf5ac9270": "сейчас", + "ade42d3734d25cb8": "через {duration}", + "94fcce9e98d053ad": "Нет", + "e7c90232ad94f3ca": "Следующий сброс", + "22f3ae62c7a65e0f": "Расход, последние 3 ч", + "737171d0d80cb0d0": "Расход, среднее за окно", "a16b48709357a5a7": "Управление использованием", - "a00e74aaa421c524": "осталось", - "0e34c3076c08feb2": [ - { - "t": "span", - "i": 1, - "c": [ - "↻ +", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - }, - "%" - ] - }, - " ", - "через ", - { - "i": 3, - "k": "_gt_value_3", - "v": "v" - } - ], + "e20b23cc4eee52c1": "Совет по сбросу:", + "aca138d5adaa5f69": "Подписки", "8bd6f07136317c8f": "Ни один провайдер в выбранных окружениях не сообщает лимиты подписки.", "87f5d0c61b335f38": "Смотрите использование в ChatGPT через подключённый аккаунт.", "5b4c71b36b979e80": "Стоимость", @@ -12393,6 +12384,10 @@ "b11af3f3da3d494e": "Итоги неполные, пока выбранные окружения сканируются.", "8062808b87ce6032": "Цены моделей", "cf5409d12fc3f53b": "Все провайдеры", + "498a69c10b2ed2d9": "{label}: остаток общей квоты, записанный и прогнозный", + "b05ed15d19d4a485": "Исчерпан {time}", + "56fb015730a158bc": "прогноз", + "fc3a1241f943cae6": "Сейчас", "55e99aaf3d0e6af4": "Цены не загружены", "ed447281261f2d0e": "Доступ только для чтения", "67633defded66bf7": "Введите ID модели.", @@ -12971,5 +12966,48 @@ }, " нужна причина." ], - "91aadfc843c600de": "Подтвердить аккаунт Google" + "91aadfc843c600de": "Подтвердить аккаунт Google", + "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}", + "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": "панель машин максимум агентов одновременно лимит место память", + "dffec1f0549853b0": "{machine}: ожидание данных" } diff --git a/apps/web/src/i18n/translations/sv.json b/apps/web/src/i18n/translations/sv.json index e4e0e428cc4d..cd47664c821a 100644 --- a/apps/web/src/i18n/translations/sv.json +++ b/apps/web/src/i18n/translations/sv.json @@ -4332,6 +4332,7 @@ "94124ad2133e3aed": "Okänd", "000646e27e304b8b": "Öppna sidochatt", "56567586cbe00c86": "Öppna kontextöverföringen i den här chatten", + "ec77e9d3bc2b6d99": "Öppna den startade tråden i den här chatten", "405e76cdd602bbcf": "Öppna subagent", "520c15dbd507b804": "Öppna den överordnade agenten i den här chatten", "309b160785f6c473": "Öppna forken i den här chatten", @@ -10232,7 +10233,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.", @@ -11869,7 +11870,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", @@ -12286,30 +12287,20 @@ "4df3ff1be768a7ab": "{name}: {remaining} % kvar", "7aaaff1c6484f25c": "Segment", "8bcab2ef61de6518": "Tak på 0 $", + "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", - "a00e74aaa421c524": "kvar", - "0e34c3076c08feb2": [ - { - "t": "span", - "i": 1, - "c": [ - "↻ +", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - }, - "%" - ] - }, - " ", - "om ", - { - "i": 3, - "k": "_gt_value_3", - "v": "v" - } - ], + "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", @@ -12400,6 +12391,10 @@ "b11af3f3da3d494e": "Summorna är ofullständiga medan valda miljöer genomsöks.", "8062808b87ce6032": "Modellpriser", "cf5409d12fc3f53b": "Alla leverantörer", + "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.", @@ -12978,5 +12973,48 @@ }, " kräver en anledning." ], - "91aadfc843c600de": "Verifiera Google-konto" + "91aadfc843c600de": "Verifiera Google-konto", + "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", + "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", + "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 291c7dd9432f..53275d8e2125 100644 --- a/apps/web/src/i18n/translations/zh.json +++ b/apps/web/src/i18n/translations/zh.json @@ -4337,6 +4337,7 @@ "94124ad2133e3aed": "未知", "000646e27e304b8b": "打开侧聊", "56567586cbe00c86": "在此对话中打开上下文转移", + "ec77e9d3bc2b6d99": "在此对话中打开已启动的会话", "405e76cdd602bbcf": "打开子智能体", "520c15dbd507b804": "在此对话中打开父智能体", "309b160785f6c473": "在此对话中打开分叉", @@ -10239,7 +10240,7 @@ "6fc9e5e722cf3c73": "克隆的仓库会放到上方文件夹下的 github.com/owner/repo 中,与 ghq 相同。", "bee548d674abd0d2": "重置克隆到主机文件夹为默认值", "ef27c4211844aef9": "暂缓", - "4df30d44eb0b0728": "用量限制重置后自动继续会话。你可以在每个会话中取消自动继续。", + "4e8a6e262304c240": "达到用量限制后继续会话:使用 Auto 的会话会切换到下一个仍有余量的订阅,其他会话会在限制重置后继续。你可以在每个会话中取消自动继续。", "0769f91ca46e3003": "将会话暂缓到用量限制重置。开启自动继续后,智能体会在重置后接着工作。", "7c27e91e75cce7a3": "自动收尾", "cf6c5aa9b63957e6": "Pull request 合并后收尾会话。已关闭的 pull request 仍会自动收尾。", @@ -11885,7 +11886,7 @@ "c437e0f28c6d4a4b": "排序 项目 侧边栏 手动 创建 最近", "cb309dc06cf679ae": "暂缓 预设 时间 稍后 今晚 明天 下周 提醒", "6751449c6188912d": "用量 配额 速率限制 重置 唤醒 恢复 继续", - "0aedae6a82c09429": "用量 配额 速率限制 重置 恢复 继续", + "5190923c9a9d6a2e": "用量 配额 速率限制 重置 恢复 继续 auto 故障转移 切换 订阅 账户", "85dbcfec2d41f534": "隐藏 收起 运行中 监控中 会话 收件箱 侧边栏 分组", "405a2295152c9d77": "测试版 文件夹 项目 树 经典 侧边栏", "de42c4690914cee4": "测试版 简洁侧边栏 文件夹 行 多行 分支 PR 详情", @@ -12303,30 +12304,20 @@ "4df3ff1be768a7ab": "{name}:剩余 {remaining}%", "7aaaff1c6484f25c": "分段", "8bcab2ef61de6518": "上限 $0", + "98947080075a0e9f": "/ {capacity}%", + "319d956d8dc9626e": "共享池耗尽", + "7edac2c4173fee09": "{date} 前不会耗尽", + "649af7801ecb5d6c": "现已耗尽", + "7b3b4057463829e0": "最先耗尽", + "0cc4fd1cf5ac9270": "现在", + "ade42d3734d25cb8": "{duration}后", + "94fcce9e98d053ad": "无", + "e7c90232ad94f3ca": "下次重置", + "22f3ae62c7a65e0f": "消耗(最近 3 小时)", + "737171d0d80cb0d0": "消耗(窗口平均)", "a16b48709357a5a7": "管理用量", - "a00e74aaa421c524": "剩余", - "0e34c3076c08feb2": [ - { - "t": "span", - "i": 1, - "c": [ - "↻ +", - { - "i": 2, - "k": "_gt_value_2", - "v": "v" - }, - "%" - ] - }, - " ", - "还需 ", - { - "i": 3, - "k": "_gt_value_3", - "v": "v" - } - ], + "e20b23cc4eee52c1": "重置建议:", + "aca138d5adaa5f69": "订阅", "8bd6f07136317c8f": "选中的环境上没有提供方报告订阅限制。", "87f5d0c61b335f38": "用已连接的账户在 ChatGPT 中查看用量。", "5b4c71b36b979e80": "费用", @@ -12417,6 +12408,10 @@ "b11af3f3da3d494e": "选中的环境仍在扫描,总计暂不完整。", "8062808b87ce6032": "模型价格", "cf5409d12fc3f53b": "所有提供方", + "498a69c10b2ed2d9": "{label}:共享池剩余额度(已记录与预测)", + "b05ed15d19d4a485": "{time} 耗尽", + "56fb015730a158bc": "预测", + "fc3a1241f943cae6": "现在", "55e99aaf3d0e6af4": "价格未加载", "ed447281261f2d0e": "只读权限", "67633defded66bf7": "请输入模型 ID。", @@ -12985,5 +12980,48 @@ }, "需要填写理由。" ], - "91aadfc843c600de": "验证 Google 账户" + "91aadfc843c600de": "验证 Google 账户", + "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} 个在工作", + "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": "机器栏 最多 智能体 同时 上限 余量 内存", + "dffec1f0549853b0": "{machine}:正在等待数据" } diff --git a/apps/web/src/index.css b/apps/web/src/index.css index 6ce3f831c9ea..5434c6aafad7 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/entities.relationshipShells.test.ts b/apps/web/src/state/entities.relationshipShells.test.ts index 0a39f4a78658..21d8be25c15b 100644 --- a/apps/web/src/state/entities.relationshipShells.test.ts +++ b/apps/web/src/state/entities.relationshipShells.test.ts @@ -1,6 +1,7 @@ -import type { - OrchestrationV2ThreadProjection, - OrchestrationV2ThreadShell, +import { + EnvironmentId, + type OrchestrationV2ThreadProjection, + type OrchestrationV2ThreadShell, } from "@t3tools/contracts"; import { describe, expect, it } from "vite-plus/test"; @@ -16,6 +17,12 @@ const shell = (id: string, parentThreadId: string | null = null) => }) 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 e2205c7c2d78..040f689fd1c3 100644 --- a/apps/web/src/state/entities.ts +++ b/apps/web/src/state/entities.ts @@ -400,12 +400,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. */ @@ -413,10 +417,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); @@ -430,10 +435,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, ); } @@ -445,6 +451,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/apps/web/src/state/machineStatus.test.ts b/apps/web/src/state/machineStatus.test.ts new file mode 100644 index 000000000000..036898e27bc0 --- /dev/null +++ b/apps/web/src/state/machineStatus.test.ts @@ -0,0 +1,68 @@ +import { EnvironmentId, type MachineStatus } from "@t3tools/contracts"; +import * as Cause from "effect/Cause"; +import * as Option from "effect/Option"; +import { AsyncResult } from "effect/reactivity"; +import { describe, expect, it } from "vite-plus/test"; + +import { machineEnvironmentFromResult } from "./machineStatus"; + +const environmentId = EnvironmentId.make("environment-1"); +const receivedAt = 1_800_000_000_000; +const status: MachineStatus = { + hostname: "hub2", + platform: "linux", + sampledAt: receivedAt, + cores: 4, + load: [0.2, 0.3, 0.4], + cpuUtilization: 0.1, + memory: { totalBytes: 7 * 1024 ** 3, availableBytes: 4 * 1024 ** 3 }, + swap: null, + disk: null, + pressure: null, + working: 1, + open: 0, + maxWorkingAgents: 2, + agents: [], +}; + +const machine = (result: AsyncResult.AsyncResult | null) => + machineEnvironmentFromResult(environmentId, "hub2", result); + +describe("machineEnvironmentFromResult", () => { + it("reads a successful sample", () => { + expect(machine(AsyncResult.success(status, { timestamp: receivedAt }))).toEqual({ + environmentId, + label: "hub2", + status, + receivedAt, + loading: false, + }); + }); + + it("keeps the last sample when a poll fails", () => { + const previousSuccess = Option.some(AsyncResult.success(status, { timestamp: receivedAt })); + const result = AsyncResult.failure(Cause.fail("timeout"), { previousSuccess }); + + expect(machine(result)).toEqual({ + environmentId, + label: "hub2", + status, + receivedAt, + loading: false, + }); + }); + + it("reads off when failure has no previous sample", () => { + expect(machine(AsyncResult.failure(Cause.fail("timeout")))).toEqual({ + environmentId, + label: "hub2", + status: null, + receivedAt: 0, + loading: false, + }); + }); + + it("reads off when the environment is disconnected", () => { + expect(machine(null).status).toBeNull(); + }); +}); diff --git a/apps/web/src/state/machineStatus.ts b/apps/web/src/state/machineStatus.ts new file mode 100644 index 000000000000..4a5ca1af0ccf --- /dev/null +++ b/apps/web/src/state/machineStatus.ts @@ -0,0 +1,69 @@ +import { createEnvironmentRpcQueryAtomFamily } from "@t3tools/client-runtime/state/runtime"; +import { type EnvironmentId, type MachineStatus, WS_METHODS } from "@t3tools/contracts"; +import * as Option from "effect/Option"; +import { AsyncResult, 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; + /** 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. +const machineStatusQuery = createEnvironmentRpcQueryAtomFamily(connectionAtomRuntime, { + label: "environment-data:server:machine-status", + tag: WS_METHODS.serverGetMachineStatus, + staleTimeMs: 20_000, + refreshIntervalMs: 25_000, + idleTtlMs: 0, +}); + +/** A failed poll keeps the last sample, so a brief outage does not read as "off". */ +export function machineEnvironmentFromResult( + environmentId: EnvironmentId, + label: string, + result: AsyncResult.AsyncResult | null, +): MachineEnvironment { + const previousSuccess = + result?._tag === "Failure" ? Option.getOrNull(result.previousSuccess) : null; + return { + environmentId, + label, + status: result === null ? null : Option.getOrNull(AsyncResult.value(result)), + receivedAt: result?._tag === "Success" ? result.timestamp : (previousSuccess?.timestamp ?? 0), + loading: result?._tag === "Initial", + }; +} + +/** 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( + machineEnvironmentFromResult(environmentId, presentation.entry.target.label, result), + ); + } + return environments; +}).pipe(Atom.withLabel("web-machine-environments")); diff --git a/docs/progress.md b/docs/progress.md new file mode 100644 index 000000000000..48ca05fdb3ea --- /dev/null +++ b/docs/progress.md @@ -0,0 +1,385 @@ +# 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. + +## 2026-11-13 — Auto gets its own icon in the model picker + +- What: the `auto` model shows a Route icon in the theme's primary color (picker rows and the composer button) instead of the Claude logo, and drops the account badge, since Auto picks the account itself. +- Why: Tomáš could not tell Auto apart from the concrete Claude models at a glance. +- 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. + +## 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. + +## 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). + +## 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. + +## 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. + +## 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. + +## 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. + +## 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. + +## 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. + +## 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. + +## 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. + +## 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). #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. +- 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. + +## 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 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, 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). + +## 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`) 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 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. + +## 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. + +## 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. + +## 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. + +## 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. + +## 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. + +## 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. + +## 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. + +## 2026-11-21: Fork synced with upstream `194025ef11` by a merge + +- 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 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: 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, starting or running, delegated children included; open = a live provider session still bound to the thread without such a run. 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. A queued run on an idle thread is not working (the brief counted queued): it waits on a held queue, a usage limit or the user and runs no agent. Machines the client is not connected to (`machineStatus.sshPeers` over SSH) are not in this change. +- Numbers: machineCapacity 19/19, MachineStatus (server) 5/5 (its table failed on the first SQL with the review's rows), machineBar.logic 2/2. `vp run check:changed`: format, lint, knip, graphql, typecheck (43 packages), 290 tests in 22 files and react compiler pass. `vp run i18n:check` pass with 44 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. +- Review: one read-only review on the first Claude account (the second was at its weekly limit until Nov 25). Fixed: threads with only a held or limit-blocked queued run counted as working, and threads detached from a live session still counted as open (both with failing rows first); the popover now shows the pressure averages the gates use; the bar no longer mounts below 768 px, where it polled while hidden; a chip no longer reads "off" while its first answer loads and goes grey when a server stops answering for about two minutes; provider status pushes re-render only the accounts and Next parts; a margin on a header that never renders was dropped. Left as is: two T3 servers on one host show the first server's counts; account letters assume instances named "Auto" and "Auto B"; a new agent limit shows within about 30 s. +- 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). + +## 2026-11-22: Fork synced with upstream `dac6422b89` by a merge + +- What: upstream main `dac6422b89`, 26 commits newer than the last sync base `194025ef11` (82 files, +3531/-693), was merged into `tomas/sync-upstream-2026-11-21b` at fork main `a4d52b0275` with a real merge (`e7b0fff049`), as in the last four syncs. Fork main stays the first parent, so the PR needs no force-push; `origin/main` was already an ancestor when the merge was staged, so no `-s ours` merge was needed. +- Why: fork main was 26 upstream commits behind after #28 (the machine bar). +- Conflicts: none in the text. Three files changed on both sides and git merged them: `ChatView.tsx` (fork's Auto level, lineage and machine bar next to upstream's queued-dictation capture), `usageLimitsCopy.ts` (fork's reset advice beside upstream's unsupported-limit notice) and `usageLimits.test.ts` (fork's advice rows beside upstream's notice test). Both behavior sets are present in the merged files. +- Fork behavior kept: the fork's diff against upstream is 119 files before (`194025ef11..a4d52b0275`) and after the merge; per-file added and removed line counts match everywhere. +- Numbers: `vp run check:changed upstream/main` (the fork's 119 files): unused patches, format, lint, knip, graphql, typecheck (43 packages), 1602 tests in 57 files and react compiler all pass. `vp run check:changed origin/main` (upstream's 82 files): every step passes except the test step, where 3 cases of the new upstream `browserHistoryStore.browser.test.ts` failed under the 44-file parallel run (two 15 s timeouts, one cascading assertion after them); that file alone passes 10/10, and the other 1756 tests pass. `vp run i18n:check` pass. CI owns the full suite. +- Real run: `vp run migrate-dev-db --base-dir .t3/verify` seeded a scratch data dir from a read-only snapshot of the live database (67.8 MB, 5 projects, 31 threads) and applied migrations 103-105 from earlier syncs. The server then booted on that dir on port 16257, completed V2 orchestration recovery and answered HTTP 302; it was stopped by the PIDs this task started and the port was released. No agent turn was sent. The dev runner had no Rust build for the resource monitor, so it started without process telemetry; the scratch home inside the Git repo also warns, as expected. +- Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Recheck upstream main before the merge if it moved during the sync; no new migrations came with these 26 commits. + +## 2026-11-22: Fork synced with upstream `3b3f8808f4` by a merge + +- What: upstream main `3b3f8808f4`, 32 commits newer than the last sync base `dac6422b89` (231 files, +7455/-3026), was merged into `tomas/sync-upstream-2026-11-22` at fork main `cfbcb25a04` (#29) with a real merge (this commit), as in the last five syncs. Fork main is the first parent and was the branch head, so no `-s ours` merge was needed and the PR needs no force-push. +- Why: upstream main moved 32 commits while #29 was being checked. +- Conflicts: the 10 web catalogs, at their tails. Upstream moved the two "Move this command to the front of the queue" keys from the end into source order, and the fork had appended its keys after them. Resolved per JSON key: base, plus the fork's key changes (64 added, 3 removed), plus upstream's (4 added, 5 removed). No key was changed by both sides, and each catalog parses to exactly that merge with no duplicate keys. The other 14 files changed on both sides merged without conflicts: `Orchestrator.ts`, `ProviderTurnStartService.ts`, `server.ts`, `ws.ts` and its test, the MCP project `handlers.ts`, `orchestrationV2.ts`, `packages/shared/package.json`, `ChatView.tsx`, `ComposerFooterControls.tsx`, `settingsSearch.ts`, `index.css`, `docs/user/thread-sidebar.md` and mobile `use-thread-composer-state.ts`. +- Fork behavior kept: the fork's diff against upstream is 119 files, +6924/-308, before (`dac6422b89..cfbcb25a04`) and after the merge (`3b3f8808f4..HEAD`), with identical per-file added and removed line counts. In 109 of the files the added and removed lines themselves are identical; in each of the 10 web catalogs, only the line that gains a comma before the fork's appended keys differs. +- Checked and left alone: #40622 (a steer that missed its turn keeps its queue place) changes where such a steer queues, not which model it runs on: a queued Auto-stamped run still takes the thread's current pick when it starts (`queuedRunFollowsCurrent`), and the fork's unread-steer requeue still queues behind its source run. #40670 (a dropped Cursor prompt keeps its inline handoff) makes `unsentManualContinuationSource` skip dropped turns, so Resume re-sends a dropped prompt instead of the fork's "Continue where you left off."; only Cursor marks prompts dropped. #40567 (`t3_thread_launch` sets `titleRenamed`) sits beside the fork's `delegatedFrom` stamping. #40633 and #40604 change `t3_thread_wait` only for app-owned delegated tasks, not launched threads. #40594 moves the feature flags into one `T3CODE_FEATURE_FLAGS` list (`secret_providers`, `tanstack_source`, `github_app_client_id=…`) and restructures settings search; the Machine bar, Agent limit and failover search entries are intact, and neither hub sets the removed `T3CODE_FEATURE_SECRETS`, `T3CODE_TANSTACK_SOURCE` or `T3CODE_GITHUB_APP_CLIENT_ID`. #27866 drops `react-markdown` and remark from the web app; no fork file imports them. `OrchestratorV2Shape` did not change, so Auto routing still wraps every dispatch. Upstream did not touch `autoModel.ts`, `AutoFailoverService.ts`, `ClaudeAdapterV2.ts`, `ThreadMessageIntake.ts` or the Grok usage reader. +- Numbers: `vp run check:changed upstream/main` (the fork's 119 files): unused patches, format, lint, knip, graphql, typecheck (43 packages) and react compiler pass; tests 1603/1604 in 57 files. The one failure, the first case of `ChatView.browser.test.tsx`, hit its 15 s timeout under the parallel run while the review agent was also working; that file alone passes 18/18. `vp run check:changed origin/main` (upstream's 231 files): unused patches, format, lint, knip, graphql, typecheck (43 packages) and react compiler (65 files) pass. Its 114-file test step ran past the runner's 900 s timeout on the first run and was killed without output; rerun with `--timeout 2700`, it finished in 835 s with 3253 of 3266 tests passing (12 skipped). The one failure, a drag-scroll case in upstream's `FilePreviewPanel.browser.test.tsx` (a file the fork does not touch), missed its wait under that load; that file alone passes 15/15. `vp run i18n:check` pass. +- Real run: a copy of the live database was taken through a read-only connection (`VACUUM INTO`, 381 MB), and `vp run migrate-dev-db --base-dir .t3/verify --source ` seeded a scratch data dir from it (65.6 MB, 5 projects, 29 threads), applying migrations 103-105 from earlier syncs. The server booted on that dir on port 13990, completed V2 orchestration recovery and answered HTTP 302. The harness stopped its process tree and the port was released. No agent turn was sent. The only warnings were the expected two: no Rust build for the resource monitor, and the scratch home inside the Git repo. +- Review: one read-only review on the first Claude account found no bugs (the second account is at its weekly limit until Nov 25, and the Codex account had no quota for a GPT reviewer). It compared the fork's added and removed lines file by file, parsed the 10 catalogs per key, and confirmed each call above. +- Switching the hubs: these 32 commits add no migrations; hub2's live database is still at 102, so its switch applies 103-105 from earlier syncs. The lockfile changed (#27866 vendors `@pierre/words` as `apps/web/deps/pierre-words-0.2.2-t3.4-7c04b7f1.tgz`), so the new build needs `vp i`. +- Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Upstream main moved 6 commits during the sync (`4ac5e6e791`: #40693, #40676, #40702, #40701, #40699, #40682); they touch one fork file (`ProviderRegistry.test.ts`), merge without conflicts, and go in the next sync. + +## 2026-11-22: Fork synced with upstream `c9e9e7d36a` by a merge + +- What: upstream main `c9e9e7d36a`, 7 commits newer than the last sync base `3b3f8808f4` (17 files, +203/-33), was merged into `tomas/sync-upstream-2026-11-22b` at fork main `5a349ab4ae` (#30) with a real merge (this commit), as in the last six syncs. Fork main is the first parent and was the branch head, so no `-s ours` merge was needed and the PR needs no force-push. +- Why: the 6 upstream commits left for this sync by #30 (`4ac5e6e791`), plus #40708, which landed before the merge. +- Conflicts: none. The only file both sides changed is `ProviderRegistry.test.ts`, where the fork's Auto-slug filter in the Claude catalog case and upstream's login-shell PATH cases (#40693) are in different hunks. +- Fork behavior kept: the fork's diff against upstream is 119 files, +6937/-308, before (`3b3f8808f4..5a349ab4ae`) and after the merge (`c9e9e7d36a..HEAD`), and the added and removed lines are identical in every file. +- Checked and left alone: #40699 (text generation skips models marked `supportsTextGeneration: false` and tries the rejected instance's other models last) cannot pick an Auto slug: the fallback offers only each driver's default text model or a custom thread default, and the fork's Auto models leave `supportsTextGeneration` unset. #40693 makes a provider refresh re-read PATH from the login shell, beside the startup `fixPath`; it rebuilds only instances still missing their CLI, so installed Auto instances keep their sessions. The other five (#40676 mobile token, #40702 Antigravity command text, #40701 setup-script output, #40682 Windows drive listing, #40708 scheduled-task draft) touch no fork code. +- Numbers: `vp run check:changed upstream/main` (the fork's 119 files): unused patches, format, lint, knip, graphql, typecheck (43 packages), 1605 tests in 57 files and react compiler (27 files) pass in 10m54s. `vp run check:changed origin/main` (upstream's 17 files): format, lint, knip, graphql, typecheck (9 packages), 284 tests in 11 files and react compiler (5 files) pass in 3m02s. No browser test timed out in either run. `vp run i18n:check` pass. +- Real run: a copy of the live database was taken through a read-only connection (`VACUUM INTO`, 370 MB, written under the worktree's ignored `.t3` because `/tmp` is tmpfs on hub2, and deleted after seeding), and `vp run migrate-dev-db --base-dir .t3/verify --source ` seeded a scratch data dir from it (65.6 MB, 5 projects, 29 threads), applying migrations 103-105 from earlier syncs. The server booted on that dir on port 16615, completed V2 orchestration recovery and answered HTTP 302. The harness stopped its process tree and the port was released. No agent turn was sent. The only warnings were the expected two: no Rust build for the resource monitor, and the scratch home inside the Git repo. +- Switching the hubs: these 7 commits change no migrations, lockfile or package manifests; hub2's live database is still at 102, so its switch applies 103-105 from earlier syncs. +- Next: Tomáš merges the PR, then switches hub2 and hub to the new build. Upstream main moved 3 commits during the checks (`11224f63d2`: #39822, #40154, #40703); they touch 8 files the fork does not change (the Antigravity provider, `ChatView.browser.test.tsx`, client-runtime `commands.ts`), merge without conflicts, and go in the next sync. + +## 2026-11-22: Keep-awake stops retrying when logind denies the sleep inhibitor + +- What: `KeepAwake.ts` now treats a `systemd-inhibit` exit whose stderr says "Access denied", "interactive authentication" or "not authorized" as permanent. The hold logs one warning without a stack (`keep-awake disabled until restart: ...`) and every later hold in that process does nothing. Other inhibitor failures keep the old retry with exponential backoff (5 s, capped at 10 min). `keepAwakeWhileAgentsWork`, the platform commands and run detection are unchanged. +- Why: the hubs run T3 as a systemd user service with no interactive session, so polkit refuses `--mode=block` every time. The old hold logged a full stack on every retry, forever: about 7,600 lines in hub's `boot-service.log` on 2026-11-19. +- Numbers: `KeepAwake.test.ts` gains two `makeHold` cases on the TestClock: a denied hold run twice across an hour spawns once and logs one warning with an empty cause; a plain non-zero exit retries at 5 s and again 10 s later. Both failed before the change (no `makeHold`), 3/3 pass after. +- What worked: pulling the retry policy into an exported `makeHold(holdOnce)` with a `denied` Ref, so the test drives it with a fake `holdOnce` instead of spawning `systemd-inhibit`. +- Next: Tomáš merges the PR and switches hub2 and hub to the new build; their logs should show one `keep-awake disabled until restart` line per server start instead of a stack every few minutes. + +## 2026-11-22: Fork synced with upstream `c198f73b37` by a merge + +- What: upstream main `c198f73b37`, 17 commits newer than the last sync base `c9e9e7d36a` (88 files, +1878/-318), was merged into `tomas/sync-upstream-2026-11-22c` at fork main `2479ed911e` (#32) with a real merge (this commit), as in the last seven syncs. Fork main is the first parent and was the branch head, so no `-s ours` merge was needed and the PR needs no force-push. +- Why: upstream changed 27 files the fork also changes: `Orchestrator.ts`, `ProviderTurnStartService.ts` and its test, `runtimeLayer.test.ts`, `ChatView.tsx`, client-runtime `threadWorkflows.ts` and its test, and the 10 web and 10 mobile catalogs. The sync was asked for at `70b5e489b9` (15 commits); #40767 and #40776 landed during the work and are included. +- Conflict: one, in `ProviderTurnStartService.ts`. Upstream #40764 keeps the "Native resume is unavailable" refusal for a Resume on a provider without native resume and skips it only when pending context goes with the resume (handoffs, missed attachments, side chat, a restart note); that resume then becomes a prompted turn with "Continue where you left off.". The fork never refuses there: since 2026-11-15 such a Resume starts a normal turn with that text (`continueInstead`, `resume: false`), and that start already carried pending context through the delivery session. Kept upstream's `carriesPendingContext`, which now picks the delivery session, and dropped the refusal. +- Proof: with upstream's refusal kept, the fork's "asks to continue when the provider cannot resume natively" fails (93/94 in `ProviderTurnStartService.test.ts`); with the resolution the file passes 94/94, including upstream's two new pending-context cases, which expect the same text the fork's start sends. +- Catalogs: the 20 catalogs merged without conflicts. Each parses to base plus the fork's key changes (+64/-3 keys per web catalog, +1/-1 per mobile catalog) plus upstream's (-2 per web catalog, +1 per mobile catalog), with no key changed by both sides and no duplicate keys. `vp run i18n:generate` in apps/web and apps/mobile changed no key or value: it only moved the fork's keys from the catalog tails into source order and rewrapped arrays, so the merged layout was kept. `vp run i18n:check` passes. +- Fork behavior kept: the fork's diff against upstream is 121 files before (`c9e9e7d36a..2479ed911e`) and after the merge (`c198f73b37..HEAD`). The added and removed lines are identical in every file except `ProviderTurnStartService.ts`, where the removed refusal is now upstream's longer form of the same check (+11/-16 before, +11/-22 after). In the other direction, `2479ed911e..HEAD` holds upstream's 88-file change line for line except that refusal. +- Checked and left alone: #40767 (Queue instead of Steer for sessions that cannot steer) changes `ChatView.tsx` and `threadWorkflows.ts` away from the fork's hunks (Auto level, lineage and machine bar; `threadSupportsProviderHandoff`). #40745 (Edit from here after a failed checkpoint capture) changes `Orchestrator.ts` at the rewind check, apart from the fork's Auto routing; `OrchestratorV2Shape` did not change, so Auto routing still wraps every dispatch. #40738 makes `t3 thread list` include delegated threads (all but subagents), so threads launched with the fork's `delegatedFrom` show there too. #40154 and #39822 concern Antigravity's own Auto runtime mode, not the fork's `auto-*` model slugs. #40734, #40703, #40736, #40759, #40741, #40726, #40739, #40744, #40758, #40755 and #40776 touch no fork code. +- Agent context: #40741 adds TanStack Source text to the pull-request MCP tools, so `mcpToolListJsonBytes` grows 59052 -> 59192 (+140); `AgentContextBudget.test.ts` passes 2/2. The PR needs the `agent-context-increase` label for the Agent context budget check. +- Numbers: `vp run check:changed upstream/main --timeout 2700` (the fork's 121 files): unused patches, format, lint, knip, graphql, typecheck (43 packages), 1616 tests in 58 files and react compiler (27 files) pass in 11m02s. `vp run check:changed origin/main --timeout 2700` (upstream's files): format, lint, knip, graphql, typecheck (39 packages), 1677 tests in 54 files and react compiler (13 files) pass in 11m43s. Both ran on the merge with `c3a330d834`; #40776 landed meanwhile, so the unpushed merge was redone on `c198f73b37` with the same resolution (the trees differ only by #40776's 2 files), and `vp run check:changed ` checked those 2 files: format, lint, knip, typecheck (2 packages), its browser test 2/2 and react compiler pass in 2m07s. `vp run i18n:check` passes on the final tree. +- What worked: `check:changed` diffs against `git merge-base HEAD `, so to check only the files a redone merge adds, detach at a throwaway commit with the new tree whose parent is the first merge (`git commit-tree HEAD^{tree} -p `); the working tree does not change. The per-key catalog check must compare nested plural values by their JSON text and look for duplicate keys per object. +- Real run: a copy of the live database was taken through a read-only connection (`VACUUM INTO`, 405 MB, written under the worktree's ignored `.t3` and deleted after seeding), and `vp run migrate-dev-db --base-dir .t3/verify --source ` seeded a scratch data dir from it (62.2 MB, 5 projects, 28 threads), applying migrations 103-105 from earlier syncs. `vp run dev:server --home-dir .t3/verify` with seeding off booted on that dir on port 14254, completed V2 orchestration recovery and answered HTTP 302. The harness stopped its process tree and the port was released. No agent turn was sent. Warnings: the expected two (no Rust build for the resource monitor, the scratch home inside the Git repo), plus, on stop, upstream's keep-awake run event stream logging its interrupt; this sync does not change that code. +- Review: one independent read-only review found no bugs. It confirmed that in `ProviderTurnStartService.ts` the merge differs from upstream by exactly the fork's three changes (`continueInstead`, the dropped refusal, `resume: false` for it), that `resume: false` keeps upstream's new delivery-session `resumeTurn` and resume `operation` branch unreachable for these sessions, that pending context is delivered once, and that the other shared files differ from fork main by exactly upstream's lines. +- Switching the hubs: these 17 commits add no migrations and change no lockfile or package manifests; hub2's live database is still at 102, so its switch applies 103-105 from earlier syncs. +- Next: Tomáš merges the PR, then switches hub2 and hub to the new build. + +## 2026-11-23: Fork synced with upstream `ba588ef663` by a merge + +- What: upstream main `ba588ef663`, 163 commits newer than the last sync base `c198f73b37` (696 files, +58498/-3997), was merged into `tomas/sync-upstream-2026-11-23` at fork main `0830f64a0f` (#33) with a real merge (`658ba99ae7`), as in the last eight syncs. Fork main is the first parent and was the branch head, so no `-s ours` merge was needed and the PR needs no force-push. The upstream commits bring durable workflows (#38882, #38884), milestones over MCP (#40774, #41141), more Linear accounts (#39179) and agent feedback (#35871). +- Why: fork main was 156 upstream commits behind when the sync was asked for. Seven more landed during the checks (#41263, #25208, #41256, #41264, #26965, #41258, #24034). They touch none of the fork's files, so the unpushed merge was redone on `ba588ef663` with the same resolutions: `git merge-tree` of the first merge (`d67b02a55c`) and the new head, committed with fork main and `ba588ef663` as parents. Its tree differs from the first merge by exactly those seven commits, and the fork's diff against upstream is byte-identical. +- Conflicts: four code files and the 10 web catalogs, each resolved by keeping both sides. `useSidebarRowThreadKey.ts` (mobile): upstream #41143 moved the lookup into an atom family, and the fork's `nestLaunchedThreads: false` moved with it. MCP project `handlers.ts`: the fork's computed `delegatedFrom` (a local launch's caller is its parent) beside upstream's link-only `workflowRun`. `Orchestrator.ts` `thread.create`: the fork's unconditional `delegatedFrom` beside upstream's `workflowRun`; `withCreationProvenance` strips both from client commands. `server.ts`: the fork's `LaunchedThreadNoticeReactor` beside upstream's `MilestoneHub` and `OrchestrationMilestones` reactor. The web catalogs conflicted at their tails: upstream's 4 tracker-account keys come first, then the fork's keys. +- Shared catalog key: upstream's workflow feed added `gt("working")`, and the fork's machine bar had already appended the same key (`30a5be40eb956663`; a key is the hash of its source text). Git kept both copies, so the fork's tail copy was dropped and upstream's entry, in source order, serves both. The values match in 9 locales; fr now reads upstream's "en cours" instead of the fork's "au travail". Each of the 20 catalogs parses to base plus the fork's key changes (+64/-3 per web catalog, +1/-1 per mobile catalog) plus upstream's (+210/-6 per web catalog, +133/-1 per mobile catalog), with no duplicate keys and no other key changed by both sides. +- Fork behavior kept: the fork's diff against upstream is 121 files before (`c198f73b37..0830f64a0f`, +7064/-319) and after the merge (`ba588ef663..658ba99ae7`, +7054/-319). The added and removed lines are identical in 110 files. The other 11 are the mobile hook (the same change, one level deeper) and the 10 web catalogs (the comma anchor moved to upstream's last key, and the shared key left the fork's tail). In the other direction, `0830f64a0f..658ba99ae7` carries upstream's change line for line in all but those 11 files. +- Follow-ups, one commit each after the merge. `fix(server): Auto failover leaves workflow steps to their workflow`: a workflow retries a step whose turn died, on a new thread or the same one, and the fork's failover would also have sent "Continue where you left off" to the dead step's thread 1.5 s later, so the step ran twice and a step model the workflow pinned moved to Auto. `autoFailoverPlan` now returns null for `lineage.workflowStep`; the new row in `AutoFailoverService.test.ts` failed before the fix and the file passes 8/8 after. `test(mobile)`: upstream's new `useSidebarRowThreadKey.test.tsx` (#41143) uses a delegated child whose parent is in the same environment. In the fork that is a launched thread, which keeps its own row on mobile, so the test failed on the merge (the child's key instead of the parent's). Its parent now lives in a linked environment, the case upstream's `delegatedFrom` stands for; 1/1. +- Checked and left alone: #41086 restarts the updated Claude CLI on a model change and #41174 releases idle sessions after 2 minutes; the fork's Auto level is part of the query identity and of `canApplyClaudeSelectionLive`, so a new process gets it from the selection again. #30261 (slash commands go verbatim) and #34499 (a stopped parent hears which tasks its Stop interrupted) sit beside `continueInstead`, whose resume prompt and dropped refusal are unchanged. #25537's new "no child asks" short-circuit in `threadShell.ts` uses `asksParent`, which already counts launched threads through `delegatedFrom`. In ChatView, the workflow-run parent link takes precedence over `delegatedFrom`, and `ThreadForkService` strips both from forks. `OrchestratorV2Shape` did not change, so Auto routing still wraps every dispatch, and workflow step launches go through `ThreadLaunchService` and get Auto-routed. Upstream did not touch `autoModel.ts`, `AutoFailoverService.ts`, `KeepAwake.ts`, `MachineStatus.ts`, `ThreadMessageIntake.ts`, `LaunchedThreadNoticeReactor.ts` or the usage-limit helpers. +- Review: one read-only review on the Auto instance (the Codex reviewer was unavailable) confirmed all five resolutions and found the failover bug above. Its second point was left as is: a thread launched by a workflow step's agent nests under that step thread, which lives in the run's view, not the sidebar. That is the fork's nesting rule (a launched thread shows under its launcher, as under a subagent launcher). The thread stays reachable from the run's step thread, and its notice waking the step is wanted, since a workflow step may end its turn and be woken to submit its result. +- Agent context: `mcpToolListJsonBytes` grows 59192 -> 61724 (+2532), all from upstream: #35871 agent feedback +1206, #38882 workflows +1350, #40806 and #41005 -24. The fork's tool text is unchanged: `AgentContextBudget.test.ts` passes 2/2 against upstream's budget file. The PR needs the `agent-context-increase` label for the Agent context budget check. +- Numbers: `vp run check:changed upstream/main --timeout 2700` on the first merge (the fork's 121 files): unused patches, format, lint, knip, graphql, typecheck (43 packages) and react compiler (27 files) pass; tests 1641/1642 in 59 files in 11m39s. The one failure was the mobile test above. `vp run check:changed origin/main --timeout 3600` on the final head (upstream's 696 files and the two follow-ups): unused patches, format, lint, knip, graphql (2), typecheck (43 packages) and react compiler (166 files) pass; tests 8600/8601 in 293 files (8 skipped) in 30m08s of a 34m36s run. The one failure, upstream's "a mounted thread view lets go of the thread structures it has replaced" in `ChatView.browser.test.tsx`, hit its 15 s timeout under the parallel run; that file alone passes 19/19. `vp run check:changed upstream/main --timeout 2700` on the final head (the fork's 122 files, the follow-ups included): every step passes, tests 1642/1642 in 59 files, in 7m34s. `vp run i18n:check` passes. +- Real run: a copy of the live database was taken through a read-only connection (`VACUUM INTO`, 472 MB, under the worktree's ignored `.t3` and deleted after seeding). `vp run migrate-dev-db --base-dir .t3/verify --source ` seeded a scratch data dir from it (49.7 MB, 5 projects, 26 threads), applying migrations 103-105 from earlier syncs and upstream's new 106-110 (`WorktreePathKeyIndex`, `DeferredSlashCommandIndex`, `AgentFeedback`, `IssueTrackerAccounts`, `Workflows`). `vp run dev:server --home-dir .t3/verify --no-seed` booted on that dir on port 16306, completed V2 orchestration recovery and answered HTTP 302. The harness stopped its task; the port was released. No agent turn was sent. Warnings: the expected two (no Rust build for the resource monitor, the scratch home inside the Git repo), and on stop the keep-awake run event stream logged its interrupt, as in the last sync. +- Switching the hubs: hub2's live database is at migration 102, so its switch applies 103-110. The lockfile and package manifests changed (`pnpm-lock.yaml`, `pnpm-workspace.yaml`, client-runtime and shared `package.json`), so the new build needs `vp i`. Workflows stay off until **Settings → Labs** turns them on. +- Next: Tomáš adds the `agent-context-increase` label and merges the PR, then switches hub2 and hub to the new build. + +## 2026-11-24: Fork synced with upstream `d73e41a3fa` by a merge + +- What: upstream main `d73e41a3fa`, 278 commits newer than the last sync base `ba588ef663` (921 files, +41096/-17024), was merged into `tomas/sync-upstream-2026-11-24` at fork main `0b657fb4b2` (#34) with a real merge (`c7b3e1f78f`), as in the last nine syncs. Fork main is the first parent and was the branch head, so no `-s ours` merge was needed and the PR needs no force-push. The upstream commits bring the docs reorganisation (#41330: numbered `docs/internals/` and `docs/operations/` pages, `docs/orchestration-v2/` gone), runs that complete when the provider turn ends with the checkpoint captured afterwards (#41362), the model kept when a queued message is edited (#41814), reasoning effort for scheduled tasks (#30253), stack auto-merge (#41809) and many small fixes. +- Why: fork main was 278 upstream commits behind when the sync was asked for. +- Conflicts: 13 files, each resolved by keeping both sides. `AGENTS.md`: upstream condensed the pull request rules; the fork's "Commits" section and its merge-commit rule stay, the rule after "One request is one PR". `KeepAwake.test.ts`: the fork's two `makeHold` cases beside upstream's `inhibitorCommand` case (#41767, PowerShell by its System32 path); `KeepAwake.ts` merged cleanly with both. `docs/orchestration-v2/orchestrator-mcp-server.md`: upstream deleted it, and the fork's paragraph on launched threads went with it, since the documentation rules both sides share say not to document every feature; the one trap it named (a notice follows the live event stream, so a run that ends while the server is down sends none) is in the 2026-11-21 entry. The 10 web catalogs conflicted at their tails: upstream's 11 stack auto-merge keys come first, then the fork's keys. The other 39 files changed on both sides merged without conflicts, among them `Orchestrator.ts`, `ProviderTurnStartService.ts`, `ClaudeAdapterV2.ts`, `threadExecution.ts`, the MCP project `handlers.ts`, `server.ts`, `ws.ts`, `RpcAuthorization.ts`, `ChatView.tsx`, `ThreadRelationshipsControl.tsx`, the settings files, the 10 mobile catalogs and three CI workflows. +- Catalogs: each of the 20 catalogs parses to base plus the fork's key changes (+63/-3 per web catalog, +1/-1 per mobile catalog) plus upstream's (+27/-7 per web catalog, +2/-4 per mobile catalog), with no duplicate keys and no key changed by both sides. No source key changed, so `i18n:generate` was not run; `vp run i18n:check` passes. +- Fork behavior kept: the fork's diff against upstream is 122 files before (`ba588ef663..0b657fb4b2`, +7085/-322) and 121 after the merge (`d73e41a3fa..c7b3e1f78f`, +7072/-322). The added and removed lines are identical in 111 files; in the 10 web catalogs only the comma anchor moved to upstream's last key; the missing file is the deleted doc (13 lines). With the two follow-ups below it is 126 files, +7150/-334. +- Follow-up `282242cdf7`, `fix(web): editing a queued message on an Auto thread keeps it on Auto`: #41814 opens a queued message's edit on the run's model and saves it with the composer's pick. An Auto-routed run's model is the concrete one plus the `auto` option, and the composer keeps only options a model describes, so a save, even of the text alone, sent the concrete model: the message left Auto, stopped following a failover and ran on the subscription it was first routed to. The edit now opens on `autoLevelSelection(...)`, as the pickers already show a routed thread, so the save goes through Auto again; mobile's queue sheet does the same (it kept the option on save but showed the concrete model). The new case in `useQueuedRunEdit.browser.test.tsx` failed on the merge (the draft held `claude-opus-5-5` with the option) and passes, 19/19. The server needs no change: `withAutoModelRouting` routes any command's `auto-*` selection, and a routed run follows the thread's pick when it starts. +- Follow-up `beeef1ee21`, `fix(web): changing a scheduled task's effort keeps it on Auto`, from the review: #30253's effort picker rebuilds options from the model's descriptors, so it dropped the `auto` option of a task that `schedule_task` created from an Auto thread (it copies the thread's routed model), and the task left Auto. Before #30253 the editor saved the stored selection while the model stayed the same. `taskToDraft` now opens such a task on its Auto level; the new case in `scheduledTasksSettings.logic.test.ts` failed on the merge and passes, 29/29. +- Checked and left alone: #41362 makes a run `completed` at turn end and the checkpoint capture emit a second `run.updated` with status completed. Auto failover reacts only to `failed`, which is unchanged. `LaunchedThreadNoticeReactor` handles both completed events, but its dispatch has the deterministic command id `server:launched-thread-notice:`, so the second replays the receipt and no second notice is sent. #41814 also starts a queued run whose instance no longer matches its reserved provider thread on a thread of that instance; a queued Auto run that follows a failover now takes that path. #41521 (a declined steer follow-up is not steered again) covers the fork's notices, which take the delegated_task notice path. #33995 counts only user and MCP-agent messages as resuming; Auto failover and launched-thread notices are server-created. #41860's parent Stop walks subagent tasks, not launched threads. #41746 records each turn's `startedModes` on the common start path, which the fork's continue-prompt Resume also takes. #26946 credits run models in PR text only when the template asks, and routed runs carry concrete models. #41798 adds elapsed time only to remote subagent rows. The two new EAS workflows are `workflow_call` only. The machine bar counts preparing, starting and running runs, so #41362's earlier `completed` does not change it. `OrchestratorV2Shape` did not change, so Auto routing still wraps every dispatch. Upstream did not touch `autoModel.ts`, `AutoFailoverService.ts`, `LaunchedThreadNoticeReactor.ts`, `MachineStatus.ts`, `threadShell.ts` or the usage-limit helpers. +- Agent context: `mcpToolListJsonBytes` shrinks 61724 -> 61709 (-15), so the PR needs no `agent-context-increase` label. +- Numbers: `vp run check:changed upstream/main --timeout 2700` on `282242cdf7` (the fork's 124 files): unused patches, format, lint, knip, graphql, typecheck (43 packages), 1698 tests in 60 files and react compiler (29 files) pass in 11m47s. `vp run check:changed origin/main --timeout 3600` on the same head (926 files; a `.coderabbit.config.ts` change makes it run everything): unused patches, format, lint, knip, graphql (2), typecheck (43 packages), `node --test` (3 files) and react compiler (165 files) pass; tests 11065/11084 in 393 files (15 skipped) in 39m01s of a 41m55s run. The 4 failures were browser cases in upstream files under that load: two in `ChatView.browser.test.tsx` (a 15 s timeout, then a strict-mode locator error on two "Toggle right panel" buttons, most likely the timed-out case's view still mounted), the drag-scroll case in `FilePreviewPanel.browser.test.tsx` and one in `KeybindingsSettings.browser.test.tsx` (a 16 s timeout). The three files alone pass 43/43. `vp run check:changed 282242cdf7` (the second follow-up's 3 files): format, lint, knip, typecheck (2 packages), 29 tests in 1 file and react compiler (1 file) pass in 2m02s, and `ScheduledTasksSettings.browser.test.tsx` passes 11/11. `vp run i18n:check` passes. +- Real run: a copy of the live database was taken through a read-only connection (`VACUUM INTO`, 466 MB, under the worktree's ignored `.t3` and deleted after seeding). `vp run migrate-dev-db --base-dir .t3/verify --source ` seeded a scratch data dir (47.9 MB, 5 projects, 26 threads) and applied migrations 103-111, among them upstream's new `111_SupersededRunAttemptIndex`. `vp run dev --home-dir .t3/verify --no-seed` stopped itself on the first start: the dev tree passed the runner's 3.6 GiB cap (half of hub2's RAM) about 30 s into the first page load, while Vite built its dependency cache. The second start reused that cache and stayed near 2.7 GB. The pairing URL opened the app with the seeded sidebar, the machine bar (`hub2 0 · 3.6 GB · +3`, Claude A, `Next → hub2 · Auto: Opus 5.5 (A)`) and a seeded thread with its history. The harness stopped the task and both ports were released. No agent turn was sent. Warnings: the expected ones (no Rust build for the resource monitor, the scratch home inside the Git repo, keep-awake's run event stream interrupted on stop). +- Review: one read-only review on OpenCode, since the second Claude account refused the session ("payment is past due") and the Codex account had no quota for a GPT reviewer. It confirmed the 13 resolutions, the catalogs and the queued-edit fix, and found the scheduled-task conflict fixed above. Each of its quoted lines was checked against the source. +- Switching the hubs: hub2's live database is at migration 102, so its switch applies 103-111. The lockfile and package manifests changed (`pnpm-lock.yaml`, `pnpm-workspace.yaml`, root, web, client-runtime and shared `package.json`), so the new build needs `vp i`. +- Next: Tomáš merges the PR, then switches hub2 and hub to the new build, and renews Claude B's subscription. Mobile's scheduled-task editor (unchanged by upstream) still rebuilds options without the `auto` option when effort changes; it is left for its own fix. Upstream main moved 20 commits during the sync (`27c2d01a83`, 97 files); they touch 23 fork files (the 20 catalogs, `ws.ts` and its test, contracts `settings.ts`), merge without conflicts, and go in the next sync. + +## 2026-11-24: Auto uses the ChatGPT Plus candidates by level + +- Request: use the Plus subscription before Antigravity Opus at high and medium, with separate Codex model lists and efforts to conserve the monthly allowance. Low keeps cheap/free candidates first. Unlisted models still fall through, including a listing without the newer models. +- Fix: updated the shared candidate order and existing routing test cases. Lapsed Claude subscriptions now receive the same cooldown as a usage limit instead of trapping Auto on an account whose token still looks valid. Unrelated provider errors still do not trigger failover. +- Review: an independent read-only review confirmed the candidate order and caught outdated hand-picked failover levels for Sol and Terra; aligned those with medium and low and extended the existing regression case. Added assertions for primary Claude and low-cost candidate precedence. Kept the existing generic continuation message for a separate copy change. +- Validation: the hand-picked level regression failed before the fix (Sol chose high instead of medium). `vp run check:changed --concurrency 1` passes: format, lint, both knip checks, server GraphQL, typechecks across 37 affected packages and 35/35 tests in 3 files. Initial checks caught an overlong comment and tuple inference in the added test; both were corrected before the passing run. +- Next: merge the PR after review; switching the running fork remains a separate action for Tomáš. + +## 2026-11-25: Local launches retain ordinary settlement settings + +- What: settlement distinguishes local launches from tasks delegated by a linked environment, using the server environment identity. Subagents and remote tasks keep upstream's immediate settlement policy; local launches use the ordinary thread settings. +- Why: upstream #42210 treated the fork's local `delegatedFrom` lineage as a remote task and hid finished launches even with automatic settlement disabled. +- Proof: extending the linked-task case with a local launch failed before the fix; `ThreadSettlementService.test.ts` passes 53/53 after it. The final sync checks pass all 1789 tests in 62 files and typecheck all 43 affected packages. Independent read-only review approved this fix. +- Next: merge with the upstream sync; deploying remains Tomáš's decision. + +## 2026-11-25: Fork replayed onto upstream `c5d6aa19de` + +- What: synced the 280 upstream commits since `d73e41a3fa` onto fork main `fd589583ee` (#36), using the 2026-11-18 replay method requested by the maintainer. Replayed 78 fork commits (one superseded), restored five progress entries held only in merges, and record fork main as an ancestor with this `-s ours` merge. No force-push is needed. +- Verification of replay: first built an oracle merge at `61c323fda9`, resolving AGENTS.md, the pooled usage view and ten web catalogs. Before integration fixes, the replay tree was byte-identical to that oracle. Of the old fork's 126 files, 115 preserve identical added/deleted lines; the other eleven are the pooled view and ten catalogs. Upstream changed 896 files, including 51 also changed by the fork. +- Integration: preserved the fork's pooled layout alongside upstream's HTTP usage sources. Dropped the obsolete pooled refill sentence from ten catalogs. Adapted the existing reset test and skipped elapsed resets. Launch option validation now passes Auto selections to routing, including a previously routed model that has retired from the catalog; concrete selections retain validation. Local launched threads keep ordinary settlement settings, as recorded above. +- Review: two independent read-only GPT review rounds in T3. The first found that reset projection order could select a later refill in the same step and that catalog validation could reject a retired Auto model. Both regressions failed before their fixes; the final round approved all changes with no open findings. The fixes choose the earliest future refill and check Auto before concrete-model catalog validation. +- Checks: `vp run check:changed upstream/main --concurrency 1 --timeout 2700` passes on the final code: unused patches, format, lint, both knip checks, server GraphQL, typecheck of 43 affected packages, 1789/1789 tests in 62 files, and React Compiler coverage of 30 files. Focused launch and pooled-browser files pass 26/26; settlement passes 53/53. `vp run i18n:check` passes for web, mobile and desktop. The first check run caught an overly broad settlement helper parameter and the new retired-model regression; both were corrected. No separate repo-wide check was run; upstream-only full suites remain for CI. +- Runtime: `vp run migrate-dev-db --base-dir .t3/verify --projects 3 --threads-per-project 3` reads the live source through a read-only SQLite attachment and creates isolated scratch data (9.2 MB, 3 projects, 5 retained threads, 1063 events), applying migrations 103-117. `vp run dev:server --home-dir .t3/verify --no-seed` completed V2 recovery and answered HTTP 302 on port 13872. Stopped only this task's processes after checking the port owner's cwd; the port is released. No paid agent turn, live database write, service restart or deployment. Expected warnings: Rust resource monitor unavailable and scratch home inside the repository. +- Surfaces: no new layout or transport contract is introduced by the integration fixes. Launch validation and settlement are shared server behavior across web, desktop, mobile, local and remote clients. Auto routing, queued-message failover, model-aware usage, machine bar, launch lineage, keep-awake denial handling and #36's candidate order remain in the fork delta. Translation consistency is checked across all clients. +- Next: Tomáš verifies and merges the fork PR, then separately decides deployment. Upstream raises MCP tool-list context from 61709 to 61914 bytes (+205), requiring the maintainer's `agent-context-increase` label. The lockfile and package manifests changed, so a later deployment needs dependency installation; a server at migration 102 will apply 103-117. This task does not switch either hub. diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.md index 00ee74cd704f..82ba61ac9def 100644 --- a/docs/user/thread-sidebar.md +++ b/docs/user/thread-sidebar.md @@ -293,6 +293,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. diff --git a/docs/user/usage.md b/docs/user/usage.md index d7a921454f54..e164b259918b 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. @@ -238,6 +239,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, diff --git a/packages/client-runtime/src/handoff.test.ts b/packages/client-runtime/src/handoff.test.ts index d2f5fb4e7890..a6054f21aa6e 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,61 @@ 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: [{ id: "five_hour", kind: "session", label: "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 +205,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..1ca0c09ed50e 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 { isAutoModelSlug, 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 (isAutoModelSlug(selection.model)) { + 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( diff --git a/packages/client-runtime/src/state/models.ts b/packages/client-runtime/src/state/models.ts index a57483fdd95c..10f7e4215661 100644 --- a/packages/client-runtime/src/state/models.ts +++ b/packages/client-runtime/src/state/models.ts @@ -166,7 +166,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; /** The workflow run this thread is an agent step of, if it is one. */ readonly workflowRun: OrchestrationV2ThreadShell["workflowRun"] | null; diff --git a/packages/client-runtime/src/state/threadExecution.test.ts b/packages/client-runtime/src/state/threadExecution.test.ts index a184c4bd037f..eba7a11b27d5 100644 --- a/packages/client-runtime/src/state/threadExecution.test.ts +++ b/packages/client-runtime/src/state/threadExecution.test.ts @@ -240,11 +240,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 3ce5f6604751..b913e91bd35d 100644 --- a/packages/client-runtime/src/state/threadExecution.ts +++ b/packages/client-runtime/src/state/threadExecution.ts @@ -40,7 +40,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"; @@ -423,10 +422,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); @@ -435,31 +431,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. diff --git a/packages/client-runtime/src/state/threadRelationships.test.ts b/packages/client-runtime/src/state/threadRelationships.test.ts index 90dc68c21dd8..7eed8798c669 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 { @@ -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, @@ -93,10 +101,40 @@ 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"); const graph = deriveThreadRelationshipGraph({ + environmentId: testEnvironmentId, threads: [ { id: child, @@ -124,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, @@ -154,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, @@ -237,6 +277,7 @@ describe("thread relationships", () => { } as const; const graph = deriveThreadRelationshipGraph({ + environmentId: testEnvironmentId, threads: [liveChild, staleArchivedChild] as never, projection: null, }); @@ -336,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 26ff658a5191..a0d38f7949c4 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; diff --git a/packages/client-runtime/src/state/threadShell.test.ts b/packages/client-runtime/src/state/threadShell.test.ts index 9210949afb73..51886d1ce9c1 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, }), }; } @@ -483,6 +487,123 @@ 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, + ]); + // 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(); + }); + 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 5aeda960facd..fbaf23f70150 100644 --- a/packages/client-runtime/src/state/threadShell.ts +++ b/packages/client-runtime/src/state/threadShell.ts @@ -57,8 +57,8 @@ const isChildRunLive = (thread: Pick[], + options: { readonly nestLaunchedThreads?: boolean } = {}, ): ScopedThreadRef { const findThread = (target: ScopedThreadRef) => threads.find( @@ -91,7 +92,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, @@ -150,11 +155,13 @@ const asksParent = (thread: OrchestrationV2ThreadShell) => /** * 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, + nestLaunchedThreads: boolean, threads: ReadonlyArray, delegated: ReadonlyArray<{ readonly parentThreadId: ThreadId; @@ -163,9 +170,22 @@ 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, + // 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, + 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)) { @@ -173,9 +193,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) { @@ -187,7 +209,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])); } @@ -271,7 +299,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< @@ -338,7 +369,11 @@ 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, + nestLaunchedThreads, + get(environmentThreadsAtom(environmentId)), + ); if (sameRequests(previous, next)) return previous; previous = next; return next; @@ -382,6 +417,8 @@ export function createEnvironmentThreadShellAtoms(input: { }); if (delegated.length === 0) continue; const requests = pendingSubagentRequestsByThread( + environmentId, + nestLaunchedThreads, get(environmentThreadsAtom(environmentId)), delegated, ); @@ -750,6 +787,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 diff --git a/packages/client-runtime/src/state/threadWorkflows.test.ts b/packages/client-runtime/src/state/threadWorkflows.test.ts index fd8092a996a6..68817c9c2a43 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, @@ -115,6 +115,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 9e3d1eb4512b..4905af1497fb 100644 --- a/packages/client-runtime/src/state/threadWorkflows.ts +++ b/packages/client-runtime/src/state/threadWorkflows.ts @@ -140,14 +140,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( diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index b07eeb04f5bb..3768833bcc47 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -130,6 +130,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 58863aaebd5e..da49cc4a1950 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -71,6 +71,7 @@ export * from "./milestones.ts"; export * from "./workflow.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..da18a7c583c9 --- /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, starting or running, delegated children included. */ + working: NonNegativeInt, + /** 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), + agents: Schema.Array(MachineAgent), +}); +export type MachineStatus = typeof MachineStatus.Type; diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 563479d00b85..4bc84a1fa141 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -606,7 +606,7 @@ export function applyOrchestrationV2ThreadVisit, ): boolean => @@ -3331,7 +3331,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), /** Only the server sets this, for a thread that is a workflow run's agent step. */ workflowRun: Schema.optional(OrchestrationV2WorkflowOrigin), diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 377d6d04f82a..cbe18d9e1df2 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -406,6 +406,7 @@ import { ResourceTelemetryRetryResult, ResourceTelemetrySnapshot, } from "./resourceTelemetry.ts"; +import { MachineStatus } from "./machineStatus.ts"; import { UsageLimitSourceError, ProviderConsumeResetCreditInput, @@ -627,6 +628,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", @@ -1137,6 +1139,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, @@ -2548,6 +2556,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 4922cceeda19..db504857915c 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, @@ -563,6 +564,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)), ), @@ -1390,6 +1392,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))), @@ -1420,6 +1430,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)), @@ -1895,6 +1908,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), @@ -2167,6 +2183,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), diff --git a/packages/provider-grok/src/server/usageLimits.ts b/packages/provider-grok/src/server/usageLimits.ts index d7e97518761f..6da757bdb1aa 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 even at the limit, 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)) { diff --git a/packages/shared/package.json b/packages/shared/package.json index 123da46863a9..7f88ed49bbce 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -439,10 +439,22 @@ "types": "./src/usageFormat.ts", "import": "./src/usageFormat.ts" }, + "./autoModel": { + "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" }, + "./usagePoolProjection": { + "types": "./src/usagePoolProjection.ts", + "import": "./src/usagePoolProjection.ts" + }, "./desktopAppControl": { "types": "./src/desktopAppControl.ts", "import": "./src/desktopAppControl.ts" diff --git a/packages/shared/src/autoModel.test.ts b/packages/shared/src/autoModel.test.ts new file mode 100644 index 000000000000..66c81c740bb7 --- /dev/null +++ b/packages/shared/src/autoModel.test.ts @@ -0,0 +1,763 @@ +import { + ProviderDriverKind, + ProviderInstanceId, + type ModelSelection, + type ServerProvider, +} from "@t3tools/contracts"; +import * as DateTime from "effect/DateTime"; +import { describe, expect, it } from "vite-plus/test"; + +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"; +const inHours = (hours: number) => DateTime.formatIso(DateTime.makeUnsafe(now + hours * 3_600_000)); + +const effortCapabilities = { + optionDescriptors: [ + { + id: "effort", + label: "Effort", + type: "select" as const, + options: ["low", "medium", "high", "xhigh", "max"].map((id) => ({ id, label: id })), + }, + ], +}; + +function claude(id: string, usedPercent: number, autoAware = true): ServerProvider { + return { + instanceId: ProviderInstanceId.make(id), + driver: ProviderDriverKind.make("claudeAgent"), + ...(autoAware ? { displayName: id.endsWith("B") ? "Auto B" : "Auto" } : {}), + 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, + })), + // 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: [], + usageLimits: { + windows: [{ id: "five_hour", kind: "session", label: "Session", usedPercent, resetsAt }], + }, + } as unknown as ServerProvider; +} + +function withWeekly( + provider: ServerProvider, + usedPercent: number, + weeklyResetsAt: string, + id = "seven_day", +) { + return { + ...provider, + usageLimits: { + windows: [ + ...(provider.usageLimits?.windows ?? []), + { id, kind: "weekly", label: "Weekly", usedPercent, resetsAt: weeklyResetsAt }, + ], + }, + } 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", + ...(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)]; + expect( + resolveAutoModelSelection({ selection: auto("high"), providers, now })?.selection, + ).toEqual({ + instanceId: "claudeAuto", + model: "claude-opus-5-5", + options: [ + { id: "effort", value: "max" }, + { id: "auto", 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" }, + { id: "auto", value: "low" }, + ], + }); + }); + + it("prefers Auto-aware instances", () => { + const providers = [claude("claudeAgent", 0, false), claude("claudeAutoB", 20)]; + expect( + 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", () => { + 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" } }); + + // 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", () => { + 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, + ).toMatchObject({ + instanceId: "grok", + model: "grok-4.7", + }); + }); + + 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", 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"); + // 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"); + + // 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", () => { + // 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("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"); + const spentPastPlan = withWindow(claude("claudeAuto", 92), { + id: "monthly_spend", + kind: "monthly", + label: "Monthly spend", + 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", () => { + 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)); + // Only a Fable allowance is reported, so nothing says how much Opus room is left. + const unknown = { + ...claude("claudeAutoB", 0), + usageLimits: { + windows: [ + { + id: "seven_day_fable", + kind: "weekly", + label: "Weekly · Fable", + usedPercent: 10, + resetsAt: inHours(100), + }, + ], + }, + } 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: undefined, + } 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( + 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"); + // 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", () => { + // 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), 50, "2026-11-17T12:00:00.000Z"), + ]; + expect( + resolveAutoModelSelection({ selection: auto(), providers, now })?.selection.instanceId, + ).toBe("claudeAuto"); + }); + + it("falls back to Claude on the Antigravity subscription", () => { + 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, + ).toMatchObject({ + instanceId: "antigravity", + model: "claude-opus-4-6-thinking", + options: [ + { id: "thinking_level", value: "medium" }, + { 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 Claude, spends ChatGPT Plus ahead of Claude on Antigravity, then Grok, then Gemini", () => { + const other = ( + id: string, + driver: string, + slugs: string | ReadonlyArray, + optionId: string, + ) => + ({ + ...claude(id, 0, false), + driver: ProviderDriverKind.make(driver), + models: [slugs].flat().map((slug) => ({ + 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)]; + // The models reported by the Plus account. + const plus = [ + "gpt-6.2-sol", + "gpt-6.2-astra", + "gpt-6.1-terra", + "gpt-6.1-sol", + "gpt-6-astra", + "gpt-6-sol", + "gpt-6-luna", + ]; + const without = (...dropped: string[]) => plus.filter((slug) => !dropped.includes(slug)); + const opus = other("agyOpus", "antigravity", "claude-opus-4-6-thinking", "thinking_level"); + const pick = (level: string, slugs: ReadonlyArray) => + resolveAutoModelSelection({ + selection: auto(level), + providers: [...claudeOut, opus, other("codex", "codex", slugs, "reasoningEffort")], + now, + })?.selection; + + // Each level has its own ChatGPT models at its own effort; unlisted ones are skipped. + expect(pick("high", plus)).toMatchObject({ + instanceId: "codex", + model: "gpt-6.2-astra", + options: [ + { id: "reasoningEffort", value: "high" }, + { id: "auto", value: "high" }, + ], + }); + expect(pick("high", without("gpt-6.2-astra"))?.model).toBe("gpt-6-astra"); + expect(pick("high", without("gpt-6.2-astra", "gpt-6-astra"))?.model).toBe("gpt-6.2-sol"); + expect(pick("medium", plus)).toMatchObject({ + instanceId: "codex", + model: "gpt-6.2-sol", + options: [ + { id: "reasoningEffort", value: "medium" }, + { id: "auto", value: "medium" }, + ], + }); + expect(pick("medium", without("gpt-6.2-sol"))?.model).toBe("gpt-6.1-sol"); + // Low reaches ChatGPT only after the free models, none of which are listed here. + expect(pick("low", plus)).toMatchObject({ + instanceId: "codex", + model: "gpt-6-luna", + options: [ + { id: "reasoningEffort", value: "low" }, + { id: "auto", value: "low" }, + ], + }); + expect(pick("low", without("gpt-6-luna"))?.model).toBe("gpt-6.1-terra"); + // A listing with only Luna is skipped at high and medium. + expect(pick("high", ["gpt-6-luna"])?.instanceId).toBe("agyOpus"); + expect(pick("medium", ["gpt-6-luna"])?.instanceId).toBe("agyOpus"); + + for (const level of ["high", "medium", "low"]) { + expect( + resolveAutoModelSelection({ + selection: auto(level), + providers: [other("codex", "codex", plus, "reasoningEffort"), claude("claudeAuto", 0)], + now, + })?.selection.instanceId, + ).toBe("claudeAuto"); + } + for (const [id, driver, model, option] of [ + ["agy", "antigravity", "claude-sonnet-4-6", "thinking_level"], + ["free", "opencode", "opencode/big-pickle", "variant"], + ] as const) { + expect( + resolveAutoModelSelection({ + selection: auto("low"), + providers: [ + other("codex", "codex", plus, "reasoningEffort"), + other(id, driver, model, option), + ], + now, + })?.selection.instanceId, + ).toBe(id); + } + + 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])?.instanceId).toBe("grok"); + expect(route([...claudeOut, gemini])).toMatchObject({ + instanceId: "antigravity", + model: "gemini-3.8-flash", + options: [ + { id: "thinking_level", value: "high" }, + { id: "auto", value: "high" }, + ], + }); + }); + + 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-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); + 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("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 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 new file mode 100644 index 000000000000..f6bf8f319c11 --- /dev/null +++ b/packages/shared/src/autoModel.ts @@ -0,0 +1,386 @@ +import { + isProviderAvailable, + type ModelSelection, + type ProviderDriverKind, + type ServerProvider, +} from "@t3tools/contracts"; + +import { exhaustedUsageWindow, usageWindowLimitsModel } 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"; +/** 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"; +/** 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 { + 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 }); +/** 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, + effort, +}); + +/** + * High and medium prefer Claude, then ChatGPT (Codex), then Claude on Antigravity. + * Low spends Claude, Antigravity and free OpenCode models before ChatGPT and Grok. + * Each level has its own ChatGPT models and effort to conserve the plan's allowance. + * Unlisted models are skipped, including paid models after the plan ends. + */ +const AUTO_CANDIDATES: Readonly>> = { + high: [ + claude("claude-opus-5-5", "max"), + codex("gpt-6.2-astra", "high"), + codex("gpt-6-astra", "high"), + codex("gpt-6.2-sol", "high"), + antigravity("claude-opus-4-6-thinking", "high"), + grok("high"), + antigravity("gemini-3.8-flash", "high"), + ], + medium: [ + claude("claude-opus-5-5", "medium"), + claude("claude-fable-5-2", "medium"), + codex("gpt-6.2-sol", "medium"), + codex("gpt-6.1-sol", "medium"), + antigravity("claude-opus-4-6-thinking", "medium"), + claude("claude-sonnet-5-5", "medium"), + antigravity("claude-sonnet-4-6", "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"), + codex("gpt-6.1-terra", "low"), + grok("low"), + ], +}; + +/** The option each driver uses for reasoning effort. */ +const EFFORT_OPTION_ID: Readonly> = { + claudeAgent: "effort", + 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}`) + ); +} + +/** 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)}`, + })); + +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) || stampedLevel(selection) !== undefined; +} + +/** 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 { + 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; + return AUTO_LEVELS.find((level) => level === value) ?? DEFAULT_LEVEL; +} + +/** 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; + +/** 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) { + const percents = roomPercents(provider, model, now, "session"); + return percents.length > 0 ? Math.max(...percents) : undefined; +} + +/** + * Weekly windows that limit `model` (a one-model window counts only for it) and when each + * 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) => { + 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 }] : []; + }); +} + +/** + * 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, 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, 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. */ +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; +} + +/** 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; +} + +/** + * 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 = roomRank(a, model, now) - roomRank(b, model, now); + if (room !== 0) return room; + 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 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; + 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, model: string, now: number): boolean { + const peak = peakUsedPercent(provider, model, now); + return peak !== undefined && peak < STICKY_MAX_USED_PERCENT; +} + +/** 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; +} + +/** + * 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 /^auto\b/i.test(provider.displayName ?? ""); +} + +function usable(provider: ServerProvider, model: string, now: number): boolean { + return ( + provider.enabled && + 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 + ); +} + +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, + level: AutoLevel, +): ModelSelection { + return { + instanceId: provider.instanceId, + model: candidate.model, + options: [...(effortOptions(provider, candidate) ?? []), { id: AUTO_OPTION_ID, value: level }], + }; +} + +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, 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; + 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)) { + const provider = input.providers.find((entry) => entry.instanceId === current.instanceId); + 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, better.model, input.now), + ), + ); + if ( + provider && + candidate && + open(provider, candidate.model) && + (hasRoom(provider, candidate.model, input.now) || + peakUsedPercent(provider, candidate.model, input.now) === undefined) && + !betterHasRoom + ) { + return { selection: toSelection(provider, candidate, level), level, sticky: true }; + } + } + + for (const candidate of candidates) { + const instances = input.providers + .filter( + (provider) => + provider.driver === (candidate.driver as ProviderDriverKind) && + open(provider, candidate.model), + ) + // A copy: `filter` already returned a new array, and Hermes has no `toSorted`. + .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 }; + } + } + return null; +} 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 }; +} diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index 2aab03105b5d..cab6d7e2acc6 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -26,7 +26,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"); @@ -127,6 +127,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], @@ -2037,3 +2039,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 77710a8d5852..5e117346077f 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -24,56 +24,75 @@ 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. */ +export 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": + // 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_") || + 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: { @@ -788,7 +807,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 ec9ad5f9f606..2f920ea56d67 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, unshownFailedHubAccounts, } from "./usageLimits.ts"; @@ -232,3 +235,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.`, + }; +} 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; +}