diff --git a/apps/mobile/src/features/threads/LimitedSeatNoticeCard.tsx b/apps/mobile/src/features/threads/LimitedSeatNoticeCard.tsx new file mode 100644 index 0000000000000..b1fed522831b2 --- /dev/null +++ b/apps/mobile/src/features/threads/LimitedSeatNoticeCard.tsx @@ -0,0 +1,210 @@ +import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; +import { + type LimitedSeatNoticeView, + limitedSeatNoticeViews, +} from "@t3tools/client-runtime/limited-seat-notices"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import type { EnvironmentId, ThreadId } from "@t3tools/contracts"; +import { limitedLeadHandoffThreadId } from "@t3tools/shared/limitedSeat"; +import { useAtomValue } from "@effect/atom-react"; +import { StackActions, useNavigation } from "@react-navigation/native"; +import { AsyncResult } from "effect/reactivity"; +import { useGT, useMessages } from "gt-react-native"; +import { useState } from "react"; +import { Pressable, View } from "react-native"; + +import { AppText as Text } from "../../components/ui/AppText"; +import { m } from "../../i18n/messages"; +import { deliveryEnvironment } from "../../state/delivery"; +import { useEnvironmentQuery } from "../../state/query"; +import { useAtomCommand } from "../../state/use-atom-command"; + +/** + * A team conversation's limited lead or seats, following the thread's own setting: the free + * favorite to swap to in one press, the wait when none is free, and where a lead was handed on. + * The setting itself is chosen on the desktop or the web. + */ +export function LimitedSeatNoticeCard(props: { + readonly thread: EnvironmentThreadShell; + readonly environmentId: EnvironmentId; + readonly canOperateThread: boolean; +}) { + const { thread, environmentId } = props; + const gt = useGT(); + const messages = useMessages(); + const navigation = useNavigation(); + const query = useEnvironmentQuery( + deliveryEnvironment.limitedSeats({ environmentId, input: { threadId: thread.id } }), + ); + const { refresh } = query; + const views = limitedSeatNoticeViews( + query.data, + { + modelName: (model) => model.model, + formatReset: (resetAt) => + gt("Resets {date}.", { + date: new Date(resetAt).toLocaleString(undefined, { + month: "short", + day: "numeric", + hour: "numeric", + minute: "2-digit", + }), + }), + }, + messages, + ); + const openThread = (threadId: ThreadId) => + navigation.dispatch( + StackActions.push("Thread", { + environmentId: String(environmentId), + threadId: String(threadId), + }), + ); + return views.map((view) => ( + { + refresh(); + if (next !== null) openThread(next); + }} + onOpenThread={openThread} + /> + )); +} + +function LimitedSeatNotice(props: { + readonly view: LimitedSeatNoticeView; + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly canOperateThread: boolean; + readonly onSwapped: (continuedIn: ThreadId | null) => void; + readonly onOpenThread: (threadId: ThreadId) => void; +}) { + const gt = useGT(); + const { view } = props; + const swap = useAtomCommand(deliveryEnvironment.swapLimitedSeat); + const [swapping, setSwapping] = useState(false); + const [error, setError] = useState(null); + const { action } = view; + const { continuedIn } = view.notice; + + async function run() { + if (action?.type !== "swap") return; + setSwapping(true); + setError(null); + const result = await swap({ + environmentId: props.environmentId, + input: { + threadId: props.threadId, + seat: view.notice.seat, + modelSelection: action.substitute, + }, + }); + setSwapping(false); + if (AsyncResult.isFailure(result)) { + setError( + errorDisplayMessage(squashAtomCommandFailure(result), m) ?? + gt("Could not swap the model. Try again."), + ); + return; + } + props.onSwapped(result.value.continuedIn); + } + + return ( + + {view.title} + {view.description} + {action?.type === "swap" && props.canOperateThread ? ( + void run()} /> + ) : action?.type === "open" && continuedIn !== undefined ? ( + props.onOpenThread(continuedIn)} + /> + ) : null} + {error ? ( + + {error} + + ) : null} + + ); +} + +/** + * Above the composer of a thread whose limited run continues in a linked thread. The server + * refuses every message to it, so the composer sends nothing and this card leads to the thread + * that carries the work on. + */ +export function HandedOnThreadCard(props: { + readonly thread: EnvironmentThreadShell; + readonly environmentId: EnvironmentId; +}) { + const gt = useGT(); + const navigation = useNavigation(); + const runId = props.thread.latestRun?.runId; + const handedOn = useAtomValue( + deliveryEnvironment.limitedLeadHandedOn(scopeThreadRef(props.environmentId, props.thread.id)), + ); + if (!handedOn || runId === undefined) return null; + return ( + + + {gt("This conversation continues in a linked thread")} + + + navigation.dispatch( + StackActions.push("Thread", { + environmentId: String(props.environmentId), + threadId: String(limitedLeadHandoffThreadId(runId)), + }), + ) + } + /> + + ); +} + +function NoticeAction(props: { + readonly label: string; + readonly disabled: boolean; + readonly onPress: () => void; +}) { + return ( + // The margins cancel the 44pt touch height so the action sits 8pt under the text. + + + + {props.label} + + + + ); +} diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 2a627454b77cd..831dab188c6a9 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -16,6 +16,9 @@ import { parseThreadKey, threadKey } from "@t3tools/client-runtime/state/entitie import { createThreadVisitTracker } from "@t3tools/client-runtime/state/thread-visits"; import { useChildThreadInputs, useThreadReportedModelSelection } from "../../state/entities"; import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard"; +import { HandedOnThreadCard, LimitedSeatNoticeCard } from "./LimitedSeatNoticeCard"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; +import { deliveryEnvironment } from "../../state/delivery"; import { useFocusEffect, useNavigation } from "@react-navigation/native"; import { effectiveSnoozed, @@ -511,6 +514,12 @@ function ThreadDetailBody( threadId: props.selectedThread.id, }); const composerError = useAtomValue(threadComposerErrorsAtom)[selectedThreadKey]?.message ?? null; + // The server refuses every message to a thread whose limited run continues in a linked thread. + const threadHandedOn = useAtomValue( + deliveryEnvironment.limitedLeadHandedOn( + scopeThreadRef(props.environmentId, props.selectedThread.id), + ), + ); const preferences = useAtomValue(mobilePreferencesAtom); const toolCallVisibility = AsyncResult.isSuccess(preferences) ? (preferences.value.toolCallVisibility ?? "showAll") @@ -1728,6 +1737,19 @@ function ThreadDetailBody( thread={props.selectedThread} environmentId={props.environmentId} /> + {props.draftMode ? null : ( + <> + + + + )} ({ ), })); vi.mock("../../state/threads", () => ({ threadEnvironment: { updateMetadata: {} } })); +const testState = vi.hoisted(() => ({ handedOn: false })); +vi.mock("../../state/delivery", () => ({ + deliveryEnvironment: { limitedLeadHandedOn: () => ({}) }, +})); +vi.mock("@effect/atom-react", () => ({ useAtomValue: () => testState.handedOn })); vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => vi.fn() })); import { UsageLimitRecoveryCard } from "./UsageLimitRecoveryCard"; @@ -88,6 +93,26 @@ describe("UsageLimitRecoveryCard", () => { ); }); + it("offers no resume or snooze once the run continues in a linked thread", () => { + using _timers = { [Symbol.dispose]: () => vi.useRealTimers() }; + vi.useFakeTimers({ now: 0 }); + testState.handedOn = true; + using _handedOn = { [Symbol.dispose]: () => void (testState.handedOn = false) }; + const container = document.createElement("div"); + const root = createRoot(container); + using _root = { [Symbol.dispose]: () => act(() => root.unmount()) }; + act(() => + root.render( + , + ), + ); + expect(container.textContent).toContain("Usage limit reached"); + expect(container.querySelectorAll("button")).toHaveLength(0); + }); + it("drops a failed copy's error once a retry copies the request", async () => { vi.mocked(Clipboard.setStringAsync) .mockRejectedValueOnce(new Error("denied")) diff --git a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx index a70d28dad8527..27e08a542ed76 100644 --- a/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx +++ b/apps/mobile/src/features/threads/UsageLimitRecoveryCard.tsx @@ -1,3 +1,5 @@ +import { useAtomValue } from "@effect/atom-react"; +import { scopeThreadRef } from "@t3tools/client-runtime/environment"; import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; import { errorDisplayMessage } from "@t3tools/client-runtime/errors"; import { AsyncResult } from "effect/reactivity"; @@ -19,6 +21,7 @@ import { tryOpenExternalUrl } from "../../lib/openExternalUrl"; import { ProviderIcon } from "../../components/ProviderIcon"; import { AppText as Text } from "../../components/ui/AppText"; import { useDeadlinePassed } from "../../lib/clock"; +import { deliveryEnvironment } from "../../state/delivery"; import { threadEnvironment } from "../../state/threads"; import { useAtomCommand } from "../../state/use-atom-command"; @@ -34,7 +37,12 @@ export function UsageLimitRecoveryCard({ const [pending, setPending] = useState(false); const [error, setError] = useState(null); const resetAt = thread.runtime?.usageLimitResetAt ?? null; + // A run handed on to a linked thread must not resume here as well. + const handedOn = useAtomValue( + deliveryEnvironment.limitedLeadHandedOn(scopeThreadRef(environmentId, thread.id)), + ); const canSchedule = + !handedOn && thread.settledOverride !== "settled" && resetAt !== null && Date.parse(resetAt) > Date.parse(thread.latestRun?.completedAt ?? thread.updatedAt); diff --git a/apps/mobile/src/i18n/translations/de.json b/apps/mobile/src/i18n/translations/de.json index db34830fff7cd..fe57da6393645 100644 --- a/apps/mobile/src/i18n/translations/de.json +++ b/apps/mobile/src/i18n/translations/de.json @@ -74,6 +74,18 @@ "1861f909464425a6": "hat den Status geändert", "bd672d0adf5e6d9a": "Zum Schreiben in diesen Tracker ist die Schreibberechtigung für die Versionskontrolle nötig.", "bfe81d615f5f8f75": "Dieses Issue liegt außerhalb des Bereichs aller Projekte und ist hier daher schreibgeschützt.", + "167e546b3c02a17f": "{model} hat sein Nutzungslimit erreicht", + "7037860c8460904b": "{seat}: {model} hat sein Nutzungslimit erreicht", + "d4ad47339d670283": "Fortgesetzt mit {substitute}", + "0b95a334090835d6": "{model} hat sein Nutzungslimit erreicht, daher läuft diese Unterhaltung in einem verknüpften Thread weiter. Dieser bleibt lesbar.", + "c6196d99000642b4": "Thread öffnen", + "552649eea02acd9e": "{seat} läuft mit {substitute}", + "9723cacb91446778": "{model} hat sein Nutzungslimit erreicht. {seat} kehrt dorthin zurück, sobald das Limit zurückgesetzt ist.", + "4daef274c8249495": "{substitute} ist frei. Beim Wechsel läuft diese Unterhaltung in einem neuen verknüpften Thread mit einer Zusammenfassung weiter.", + "c8128bb2bd97de3c": "{substitute} ist frei. {seat} nutzt es ab deiner nächsten Nachricht.", + "05985243eafadf37": "Zu {substitute} wechseln", + "540418662b70d3d6": "Kein Lieblingsmodell ist frei, daher wartet diese Unterhaltung.", + "9da06299c78dfeeb": "Kein Lieblingsmodell ist frei, daher wartet {seat}.", "8b876f2953338661": "Noch nicht bekannt, ob er verknüpft ist", "b8c2bbba2243b429": "Bereits verknüpft", "4f1ab8a69f4a85e5": "Diese App ist nicht damit verbunden", @@ -118,9 +130,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} an", "77cc5f738cb7d459": "{label} aus", - "2159a4897d4a4d73": "{runtime, select, codex {Aktualisiere die Codex CLI auf {version} oder neuer, um {names} zu verwenden.} other {Aktualisiere {providerName} auf {version} oder neuer, um {names} zu verwenden.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} erfordert die Codex CLI {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere die Codex CLI auf anderem Weg oder warte auf ein neueres Release.} other {{names} erfordert {providerName} {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere {providerName} auf anderem Weg oder warte auf ein neueres Release.}}", "aba3bb73ce212f0c": "{names} erfordert {providerName} {version} oder neuer, aber der Homebrew-Cask claude-code hat nur {latestVersion}. Wechsle zum Cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} erfordert die Codex CLI {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere die Codex CLI auf anderem Weg oder warte auf ein neueres Release.} other {{names} erfordert {providerName} {version} oder neuer, aber diese Installation kann höchstens auf {latestVersion} aktualisieren. Installiere {providerName} auf anderem Weg oder warte auf ein neueres Release.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Aktualisiere die Codex CLI auf {version} oder neuer, um {names} zu verwenden.} other {Aktualisiere {providerName} auf {version} oder neuer, um {names} zu verwenden.}}", "d887bea446534de5": "Kein Projekt in dieser Umgebung kann {host}/{repository} lesen.", "4e466d60e2f7736b": "Füge die vollständige Pull-Request-URL ein. Dieser Thread hat kein Repository, in dem die Nummer aufgelöst werden kann.", "302625058bacbe38": "Füge eine vollständige URL ein. Für den Host dieses Projekts ist kein {changeRequest}-URL-Format bekannt.", @@ -1363,7 +1375,6 @@ "d6d5517e0d6ba4e7": "Datei", "96a022a5031b7e97": "Pfad", "e05357a50398306a": "Thread", - "c6196d99000642b4": "Thread öffnen", "c3f083943d8c530e": "Rechner", "5d0f9cf6550667af": "Skill", "c0d3dd0975eb2f22": "Beschreibung", @@ -1947,9 +1958,9 @@ "a5e3ff0d1a60b766": "Relay-Zugriff der Umgebung konnte nicht konfiguriert werden: {detail}", "7d508fe978cb0f3b": "Aus", "3ae222ec888dd171": "Trace-ID:", - "be00d572b18076d8": "Lange drücken, um von diesem Gerät zu entfernen", "46e2a0e828785d97": "{environment} verwalten", "5392155ec0c8b0be": "{environment} von diesem Gerät entfernen", + "be00d572b18076d8": "Lange drücken, um von diesem Gerät zu entfernen", "782a518513f0777a": "{environment} aktivieren", "a35685d9ad9de747": "Verknüpfte Cloud-Umgebungen werden geladen.", "91ca3ba7b2f9d6b6": "Keine weiteren verknüpften Cloud-Umgebungen.", @@ -4144,6 +4155,9 @@ "ce591b4de647ecda": "{title} öffnen", "4a9a6f6111329b54": "{title} neu laden", "12f0890f800baa7a": "Seite nicht verfügbar", + "1ff565598548c159": "Wird am {date} zurückgesetzt.", + "6760e4db3db15d81": "Modell konnte nicht gewechselt werden. Versuche es erneut.", + "d8bc550497c8992f": "Diese Unterhaltung wird in einem verknüpften Thread fortgesetzt", "9c5a2e144cefdf2f": "Nur lesen", "12d03e02951725b0": "Projekte und Threads lesen. Kann nichts starten, keine Nachrichten senden und nichts ändern.", "63fd02d55f0e4417": "Einen Rechner mit dieser Umgebung verknüpfen", @@ -4737,7 +4751,6 @@ "2a61b633ec5035a5": "Noch keine Agenten", "fe32057bfc66015e": "Wird am {date} fortgesetzt.", "7792e72ddecb6733": "Wurde am {date} zurückgesetzt.", - "1ff565598548c159": "Wird am {date} zurückgesetzt.", "babea77bd5527a74": "Der Zeitpunkt der Zurücksetzung ist vorbei. Versuche den Thread manuell erneut.", "21159303dd4c3a69": "Wiederherstellung nach Limit konnte nicht geändert werden.", "6d9729a715072bfa": "Anfrage für Admin kopieren", diff --git a/apps/mobile/src/i18n/translations/en.json b/apps/mobile/src/i18n/translations/en.json index 04ba1477f4016..87bcb9af07d92 100644 --- a/apps/mobile/src/i18n/translations/en.json +++ b/apps/mobile/src/i18n/translations/en.json @@ -74,6 +74,18 @@ "1861f909464425a6": "changed the state", "bd672d0adf5e6d9a": "Writing to this tracker needs the source-control write scope.", "bfe81d615f5f8f75": "This issue is outside every project's own scope, so it is read-only here.", + "167e546b3c02a17f": "{model} has reached its usage limit", + "7037860c8460904b": "{seat}: {model} has reached its usage limit", + "d4ad47339d670283": "Continued on {substitute}", + "0b95a334090835d6": "{model} reached its usage limit, so this conversation continues in a linked thread. This one stays readable.", + "c6196d99000642b4": "Open thread", + "552649eea02acd9e": "{seat} runs on {substitute}", + "9723cacb91446778": "{model} has reached its usage limit. {seat} returns to it once the limit resets.", + "4daef274c8249495": "{substitute} is free. Swapping continues this conversation in a new linked thread with a summary.", + "c8128bb2bd97de3c": "{substitute} is free. {seat} uses it from your next message.", + "05985243eafadf37": "Swap to {substitute}", + "540418662b70d3d6": "No favorite model is free, so this conversation waits.", + "9da06299c78dfeeb": "No favorite model is free, so {seat} waits.", "8b876f2953338661": "Not known yet whether it is linked", "b8c2bbba2243b429": "Already linked", "4f1ab8a69f4a85e5": "This app is not connected to it", @@ -118,9 +130,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} On", "77cc5f738cb7d459": "{label} Off", - "2159a4897d4a4d73": "{runtime, select, codex {Update the Codex CLI to {version} or newer to use {names}.} other {Update {providerName} to {version} or newer to use {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Using {names} requires the Codex CLI {version} or newer, but the newest this install can update to is {latestVersion}. Install the Codex CLI another way or wait for a newer release.} other {Using {names} requires {providerName} {version} or newer, but the newest this install can update to is {latestVersion}. Install {providerName} another way or wait for a newer release.}}", "aba3bb73ce212f0c": "Using {names} requires {providerName} {version} or newer, but the claude-code Homebrew cask only has {latestVersion}. Switch to the claude-code@latest cask: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Using {names} requires the Codex CLI {version} or newer, but the newest this install can update to is {latestVersion}. Install the Codex CLI another way or wait for a newer release.} other {Using {names} requires {providerName} {version} or newer, but the newest this install can update to is {latestVersion}. Install {providerName} another way or wait for a newer release.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Update the Codex CLI to {version} or newer to use {names}.} other {Update {providerName} to {version} or newer to use {names}.}}", "d887bea446534de5": "No project in this environment can read {host}/{repository}.", "4e466d60e2f7736b": "Paste the full pull request URL; this thread has no repository to resolve the number against.", "302625058bacbe38": "Paste a full URL; this project's host has no known {changeRequest} URL.", @@ -1363,7 +1375,6 @@ "d6d5517e0d6ba4e7": "File", "96a022a5031b7e97": "Path", "e05357a50398306a": "Thread", - "c6196d99000642b4": "Open thread", "c3f083943d8c530e": "Machine", "5d0f9cf6550667af": "Skill", "c0d3dd0975eb2f22": "Description", @@ -1947,9 +1958,9 @@ "a5e3ff0d1a60b766": "Could not configure environment relay access: {detail}", "7d508fe978cb0f3b": "Off", "3ae222ec888dd171": "Trace ID:", - "be00d572b18076d8": "Long press to remove from this device", "46e2a0e828785d97": "Manage {environment}", "5392155ec0c8b0be": "Remove {environment} from this device", + "be00d572b18076d8": "Long press to remove from this device", "782a518513f0777a": "Enable {environment}", "a35685d9ad9de747": "Loading linked cloud environments.", "91ca3ba7b2f9d6b6": "No additional linked cloud environments.", @@ -4146,6 +4157,9 @@ "ce591b4de647ecda": "Open {title}", "4a9a6f6111329b54": "Reload {title}", "12f0890f800baa7a": "Page unavailable", + "1ff565598548c159": "Resets {date}.", + "6760e4db3db15d81": "Could not swap the model. Try again.", + "d8bc550497c8992f": "This conversation continues in a linked thread", "9c5a2e144cefdf2f": "Read only", "12d03e02951725b0": "Read projects and threads. Cannot start, message or change anything.", "63fd02d55f0e4417": "Link a machine to this environment", @@ -4739,7 +4753,6 @@ "2a61b633ec5035a5": "No agents yet", "fe32057bfc66015e": "Resumes {date}.", "7792e72ddecb6733": "Reset {date}.", - "1ff565598548c159": "Resets {date}.", "babea77bd5527a74": "The reset time has passed. Retry the thread manually.", "21159303dd4c3a69": "Could not change limit recovery.", "6d9729a715072bfa": "Copy request for admin", diff --git a/apps/mobile/src/i18n/translations/es.json b/apps/mobile/src/i18n/translations/es.json index 2e3e2af7aa351..a458e2afd10b9 100644 --- a/apps/mobile/src/i18n/translations/es.json +++ b/apps/mobile/src/i18n/translations/es.json @@ -74,6 +74,18 @@ "1861f909464425a6": "cambió el estado", "bd672d0adf5e6d9a": "Para escribir en este gestor de issues se necesita el permiso de escritura de control de versiones.", "bfe81d615f5f8f75": "Esta issue está fuera del ámbito de todos los proyectos, así que aquí es de solo lectura.", + "167e546b3c02a17f": "{model} alcanzó su límite de uso", + "7037860c8460904b": "{seat}: {model} alcanzó su límite de uso", + "d4ad47339d670283": "Continúa con {substitute}", + "0b95a334090835d6": "{model} alcanzó su límite de uso, así que esta conversación continúa en un hilo vinculado. Este sigue siendo legible.", + "c6196d99000642b4": "Abrir hilo", + "552649eea02acd9e": "{seat} funciona con {substitute}", + "9723cacb91446778": "{model} alcanzó su límite de uso. {seat} vuelve a él cuando el límite se restablezca.", + "4daef274c8249495": "{substitute} está libre. Al cambiar, esta conversación continúa en un nuevo hilo vinculado con un resumen.", + "c8128bb2bd97de3c": "{substitute} está libre. {seat} lo usa desde tu próximo mensaje.", + "05985243eafadf37": "Cambiar a {substitute}", + "540418662b70d3d6": "Ningún modelo favorito está libre, así que esta conversación espera.", + "9da06299c78dfeeb": "Ningún modelo favorito está libre, así que {seat} espera.", "8b876f2953338661": "Aún no se sabe si está vinculada", "b8c2bbba2243b429": "Ya vinculada", "4f1ab8a69f4a85e5": "Esta app no está conectada a ella", @@ -118,9 +130,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} activado", "77cc5f738cb7d459": "{label} desactivado", - "2159a4897d4a4d73": "{runtime, select, codex {Actualiza la CLI de Codex a {version} o posterior para usar {names}.} other {Actualiza {providerName} a {version} o posterior para usar {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Para usar {names} se necesita la CLI de Codex {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala la CLI de Codex de otra forma o espera a una versión más reciente.} other {Para usar {names} se necesita {providerName} {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala {providerName} de otra forma o espera a una versión más reciente.}}", "aba3bb73ce212f0c": "Usar {names} requiere {providerName} {version} o posterior, pero el cask de Homebrew claude-code solo tiene {latestVersion}. Cambia al cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Para usar {names} se necesita la CLI de Codex {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala la CLI de Codex de otra forma o espera a una versión más reciente.} other {Para usar {names} se necesita {providerName} {version} o posterior, pero esta instalación solo puede actualizarse hasta {latestVersion}. Instala {providerName} de otra forma o espera a una versión más reciente.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Actualiza la CLI de Codex a {version} o posterior para usar {names}.} other {Actualiza {providerName} a {version} o posterior para usar {names}.}}", "d887bea446534de5": "Ningún proyecto de este entorno puede leer {host}/{repository}.", "4e466d60e2f7736b": "Pega la URL completa de la pull request; este hilo no tiene ningún repositorio con el que resolver el número.", "302625058bacbe38": "Pega una URL completa; el host de este proyecto no tiene una URL de {changeRequest} conocida.", @@ -1363,7 +1375,6 @@ "d6d5517e0d6ba4e7": "Archivo", "96a022a5031b7e97": "Ruta", "e05357a50398306a": "Hilo", - "c6196d99000642b4": "Abrir hilo", "c3f083943d8c530e": "Máquina", "5d0f9cf6550667af": "Skill", "c0d3dd0975eb2f22": "Descripción", @@ -1947,9 +1958,9 @@ "a5e3ff0d1a60b766": "No se pudo configurar el acceso del entorno al relay: {detail}", "7d508fe978cb0f3b": "Apagado", "3ae222ec888dd171": "ID de traza:", - "be00d572b18076d8": "Mantén pulsado para quitarlo de este dispositivo", "46e2a0e828785d97": "Gestionar {environment}", "5392155ec0c8b0be": "Quitar {environment} de este dispositivo", + "be00d572b18076d8": "Mantén pulsado para quitarlo de este dispositivo", "782a518513f0777a": "Activar {environment}", "a35685d9ad9de747": "Cargando entornos en la nube vinculados.", "91ca3ba7b2f9d6b6": "No hay más entornos en la nube vinculados.", @@ -4139,6 +4150,9 @@ "ce591b4de647ecda": "Abrir {title}", "4a9a6f6111329b54": "Recargar {title}", "12f0890f800baa7a": "Página no disponible", + "1ff565598548c159": "Se restablece {date}.", + "6760e4db3db15d81": "No se pudo cambiar el modelo. Inténtalo de nuevo.", + "d8bc550497c8992f": "Esta conversación continúa en un hilo vinculado", "9c5a2e144cefdf2f": "Solo lectura", "12d03e02951725b0": "Leer proyectos e hilos. No puede iniciar, enviar mensajes ni cambiar nada.", "63fd02d55f0e4417": "Vincular una máquina a este entorno", @@ -4730,7 +4744,6 @@ "2a61b633ec5035a5": "Aún no hay agentes", "fe32057bfc66015e": "Se reanuda {date}.", "7792e72ddecb6733": "Se restableció {date}.", - "1ff565598548c159": "Se restablece {date}.", "babea77bd5527a74": "La hora de restablecimiento ya pasó. Vuelve a intentar el hilo manualmente.", "21159303dd4c3a69": "No se pudo cambiar la recuperación tras el límite.", "6d9729a715072bfa": "Copiar solicitud para el administrador", diff --git a/apps/mobile/src/i18n/translations/fr.json b/apps/mobile/src/i18n/translations/fr.json index 3c32856a6cdc9..492c78ba875d1 100644 --- a/apps/mobile/src/i18n/translations/fr.json +++ b/apps/mobile/src/i18n/translations/fr.json @@ -74,6 +74,18 @@ "1861f909464425a6": "a modifié l’état", "bd672d0adf5e6d9a": "L’écriture dans ce gestionnaire de tickets nécessite l’autorisation d’écriture sur la gestion de versions.", "bfe81d615f5f8f75": "Ce ticket est hors du périmètre de chaque projet ; il est donc en lecture seule ici.", + "167e546b3c02a17f": "{model} a atteint sa limite d'utilisation", + "7037860c8460904b": "{seat} : {model} a atteint sa limite d'utilisation", + "d4ad47339d670283": "Poursuivi sur {substitute}", + "0b95a334090835d6": "{model} a atteint sa limite d'utilisation ; cette conversation se poursuit donc dans un fil lié. Celui-ci reste lisible.", + "c6196d99000642b4": "Ouvrir le fil", + "552649eea02acd9e": "{seat} fonctionne sur {substitute}", + "9723cacb91446778": "{model} a atteint sa limite d'utilisation. {seat} y revient dès que la limite est réinitialisée.", + "4daef274c8249495": "{substitute} est libre. Le remplacement poursuit cette conversation dans un nouveau fil lié, avec un résumé.", + "c8128bb2bd97de3c": "{substitute} est libre. {seat} l'utilise à partir de votre prochain message.", + "05985243eafadf37": "Passer à {substitute}", + "540418662b70d3d6": "Aucun modèle favori n'est libre ; cette conversation attend donc.", + "9da06299c78dfeeb": "Aucun modèle favori n'est libre ; {seat} attend donc.", "8b876f2953338661": "On ne sait pas encore si elle est associée", "b8c2bbba2243b429": "Déjà associée", "4f1ab8a69f4a85e5": "Cette app n’y est pas connectée", @@ -118,9 +130,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} activé", "77cc5f738cb7d459": "{label} désactivé", - "2159a4897d4a4d73": "{runtime, select, codex {Mettez à jour la CLI Codex vers la version {version} ou ultérieure pour utiliser {names}.} other {Mettez à jour {providerName} vers la version {version} ou ultérieure pour utiliser {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} nécessite la CLI Codex {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez la CLI Codex autrement ou attendez une nouvelle version.} other {{names} nécessite {providerName} {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez {providerName} autrement ou attendez une nouvelle version.}}", "aba3bb73ce212f0c": "{names} nécessite {providerName} {version} ou une version plus récente, mais le cask Homebrew claude-code ne propose que {latestVersion}. Passe au cask claude-code@latest : {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} nécessite la CLI Codex {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez la CLI Codex autrement ou attendez une nouvelle version.} other {{names} nécessite {providerName} {version} ou une version ultérieure, mais cette installation ne peut pas dépasser {latestVersion}. Installez {providerName} autrement ou attendez une nouvelle version.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Mettez à jour la CLI Codex vers la version {version} ou ultérieure pour utiliser {names}.} other {Mettez à jour {providerName} vers la version {version} ou ultérieure pour utiliser {names}.}}", "d887bea446534de5": "Aucun projet de cet environnement ne peut lire {host}/{repository}.", "4e466d60e2f7736b": "Collez l’URL complète de la pull request ; ce fil n’a pas de dépôt auquel rattacher le numéro.", "302625058bacbe38": "Collez une URL complète ; l’hôte de ce projet n’a pas de format d’URL connu pour {changeRequest}.", @@ -1363,7 +1375,6 @@ "d6d5517e0d6ba4e7": "Fichier", "96a022a5031b7e97": "Chemin", "e05357a50398306a": "Fil", - "c6196d99000642b4": "Ouvrir le fil", "c3f083943d8c530e": "Machine", "5d0f9cf6550667af": "Skill", "c0d3dd0975eb2f22": "Description", @@ -1947,9 +1958,9 @@ "a5e3ff0d1a60b766": "Impossible de configurer l’accès au relais de l’environnement : {detail}", "7d508fe978cb0f3b": "Éteint", "3ae222ec888dd171": "ID de trace :", - "be00d572b18076d8": "Appuyez longuement pour retirer de cet appareil", "46e2a0e828785d97": "Gérer {environment}", "5392155ec0c8b0be": "Retirer {environment} de cet appareil", + "be00d572b18076d8": "Appuyez longuement pour retirer de cet appareil", "782a518513f0777a": "Activer {environment}", "a35685d9ad9de747": "Chargement des environnements cloud associés.", "91ca3ba7b2f9d6b6": "Aucun autre environnement cloud associé.", @@ -4139,6 +4150,9 @@ "ce591b4de647ecda": "Ouvrir {title}", "4a9a6f6111329b54": "Recharger {title}", "12f0890f800baa7a": "Page indisponible", + "1ff565598548c159": "Réinitialisation le {date}.", + "6760e4db3db15d81": "Impossible de remplacer le modèle. Réessayez.", + "d8bc550497c8992f": "Cette conversation se poursuit dans un fil lié", "9c5a2e144cefdf2f": "Lecture seule", "12d03e02951725b0": "Lire les projets et les fils. Ne peut rien démarrer, envoyer ni modifier.", "63fd02d55f0e4417": "Associer une machine à cet environnement", @@ -4731,7 +4745,6 @@ "2a61b633ec5035a5": "Pas encore d’agent", "fe32057bfc66015e": "Reprise le {date}.", "7792e72ddecb6733": "Réinitialisé le {date}.", - "1ff565598548c159": "Réinitialisation le {date}.", "babea77bd5527a74": "L’heure de réinitialisation est passée. Relancez le fil manuellement.", "21159303dd4c3a69": "Impossible de modifier la récupération après limite.", "6d9729a715072bfa": "Copier la demande pour l’administrateur", diff --git a/apps/mobile/src/i18n/translations/ja.json b/apps/mobile/src/i18n/translations/ja.json index aa3af10b65dfc..44bcde3dd4a86 100644 --- a/apps/mobile/src/i18n/translations/ja.json +++ b/apps/mobile/src/i18n/translations/ja.json @@ -74,6 +74,18 @@ "1861f909464425a6": "状態を変更しました", "bd672d0adf5e6d9a": "このトラッカーに書き込むには、ソース管理の書き込みスコープが必要です。", "bfe81d615f5f8f75": "この Issue はどのプロジェクトのスコープにも含まれないため、ここでは読み取り専用です。", + "167e546b3c02a17f": "{model} は使用制限に達しました", + "7037860c8460904b": "{seat}: {model} は使用制限に達しました", + "d4ad47339d670283": "{substitute} で継続中", + "0b95a334090835d6": "{model} が使用制限に達したため、この会話はリンクされたスレッドで続きます。このスレッドは引き続き閲覧できます。", + "c6196d99000642b4": "スレッドを開く", + "552649eea02acd9e": "{seat} は {substitute} で動作します", + "9723cacb91446778": "{model} は使用制限に達しました。制限がリセットされると {seat} は元のモデルに戻ります。", + "4daef274c8249495": "{substitute} は空いています。切り替えると、この会話は要約付きの新しいリンクされたスレッドで続きます。", + "c8128bb2bd97de3c": "{substitute} は空いています。{seat} は次のメッセージからこれを使用します。", + "05985243eafadf37": "{substitute} に切り替える", + "540418662b70d3d6": "空いているお気に入りのモデルがないため、この会話は待機します。", + "9da06299c78dfeeb": "空いているお気に入りのモデルがないため、{seat} は待機します。", "8b876f2953338661": "リンク済みかどうかはまだ不明です", "b8c2bbba2243b429": "リンク済み", "4f1ab8a69f4a85e5": "このアプリはこのマシンに接続していません", @@ -118,9 +130,9 @@ "c4eb2b21c8c58a54": "標準", "f42c2a36b3507308": "{label} オン", "77cc5f738cb7d459": "{label} オフ", - "2159a4897d4a4d73": "{runtime, select, codex {{names} を使用するには、Codex CLI を {version} 以降に更新してください。} other {{names} を使用するには、{providerName} を {version} 以降に更新してください。}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} を使用するには Codex CLI {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で Codex CLI をインストールするか、新しいリリースをお待ちください。} other {{names} を使用するには {providerName} {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で {providerName} をインストールするか、新しいリリースをお待ちください。}}", "aba3bb73ce212f0c": "{names} を使うには {providerName} {version} 以降が必要ですが、Homebrew の claude-code cask には {latestVersion} までしかありません。claude-code@latest cask に切り替えてください: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} を使用するには Codex CLI {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で Codex CLI をインストールするか、新しいリリースをお待ちください。} other {{names} を使用するには {providerName} {version} 以降が必要ですが、このインストールで更新できる最新バージョンは {latestVersion} です。別の方法で {providerName} をインストールするか、新しいリリースをお待ちください。}}", + "2159a4897d4a4d73": "{runtime, select, codex {{names} を使用するには、Codex CLI を {version} 以降に更新してください。} other {{names} を使用するには、{providerName} を {version} 以降に更新してください。}}", "d887bea446534de5": "この環境には {host}/{repository} を読み取れるプロジェクトがありません。", "4e466d60e2f7736b": "プルリクエストの完全な URL を貼り付けてください。このスレッドには番号を解決するためのリポジトリがありません。", "302625058bacbe38": "完全な URL を貼り付けてください。このプロジェクトのホストには既知の {changeRequest} URL がありません。", @@ -1363,7 +1375,6 @@ "d6d5517e0d6ba4e7": "ファイル", "96a022a5031b7e97": "パス", "e05357a50398306a": "スレッド", - "c6196d99000642b4": "スレッドを開く", "c3f083943d8c530e": "マシン", "5d0f9cf6550667af": "スキル", "c0d3dd0975eb2f22": "説明", @@ -1947,9 +1958,9 @@ "a5e3ff0d1a60b766": "環境のリレーアクセスを構成できませんでした: {detail}", "7d508fe978cb0f3b": "オフ", "3ae222ec888dd171": "トレース ID:", - "be00d572b18076d8": "長押しでこのデバイスから削除", "46e2a0e828785d97": "{environment} を管理", "5392155ec0c8b0be": "このデバイスから {environment} を削除", + "be00d572b18076d8": "長押しでこのデバイスから削除", "782a518513f0777a": "{environment} を有効にする", "a35685d9ad9de747": "リンクされたクラウド環境を読み込んでいます。", "91ca3ba7b2f9d6b6": "他にリンクされたクラウド環境はありません。", @@ -4135,6 +4146,9 @@ "ce591b4de647ecda": "{title} を開く", "4a9a6f6111329b54": "{title} を再読み込み", "12f0890f800baa7a": "ページを利用できません", + "1ff565598548c159": "{date} にリセットされます。", + "6760e4db3db15d81": "モデルを切り替えられませんでした。もう一度お試しください。", + "d8bc550497c8992f": "この会話はリンクされたスレッドで続いています", "9c5a2e144cefdf2f": "読み取り専用", "12d03e02951725b0": "プロジェクトとスレッドを読み取ります。開始、メッセージ送信、変更はできません。", "63fd02d55f0e4417": "この環境にマシンをリンク", @@ -4711,7 +4725,6 @@ "2a61b633ec5035a5": "エージェントはまだいません", "fe32057bfc66015e": "{date} に再開します。", "7792e72ddecb6733": "{date} にリセットされました。", - "1ff565598548c159": "{date} にリセットされます。", "babea77bd5527a74": "リセット時刻を過ぎました。スレッドを手動で再試行してください。", "21159303dd4c3a69": "上限からの回復方法を変更できませんでした。", "6d9729a715072bfa": "管理者向けのリクエストをコピー", diff --git a/apps/mobile/src/i18n/translations/ko.json b/apps/mobile/src/i18n/translations/ko.json index ffdf2e31dedcf..e46ad9546c6ba 100644 --- a/apps/mobile/src/i18n/translations/ko.json +++ b/apps/mobile/src/i18n/translations/ko.json @@ -74,6 +74,18 @@ "1861f909464425a6": "상태 변경함", "bd672d0adf5e6d9a": "이 트래커에 쓰려면 소스 제어 쓰기 범위가 필요합니다.", "bfe81d615f5f8f75": "이 이슈는 어떤 프로젝트의 범위에도 속하지 않으므로 여기서는 읽기 전용입니다.", + "167e546b3c02a17f": "{model}이(가) 사용 한도에 도달했습니다", + "7037860c8460904b": "{seat}: {model}이(가) 사용 한도에 도달했습니다", + "d4ad47339d670283": "{substitute}(으)로 계속됨", + "0b95a334090835d6": "{model}이(가) 사용 한도에 도달하여 이 대화는 연결된 스레드에서 계속됩니다. 이 스레드는 계속 읽을 수 있습니다.", + "c6196d99000642b4": "스레드 열기", + "552649eea02acd9e": "{seat}은(는) {substitute}(으)로 실행됩니다", + "9723cacb91446778": "{model}이(가) 사용 한도에 도달했습니다. 한도가 재설정되면 {seat}은(는) 원래 모델로 돌아갑니다.", + "4daef274c8249495": "{substitute}을(를) 사용할 수 있습니다. 교체하면 이 대화는 요약과 함께 새 연결 스레드에서 계속됩니다.", + "c8128bb2bd97de3c": "{substitute}을(를) 사용할 수 있습니다. {seat}은(는) 다음 메시지부터 이를 사용합니다.", + "05985243eafadf37": "{substitute}(으)로 교체", + "540418662b70d3d6": "사용 가능한 즐겨찾는 모델이 없어 이 대화는 대기합니다.", + "9da06299c78dfeeb": "사용 가능한 즐겨찾는 모델이 없어 {seat}은(는) 대기합니다.", "8b876f2953338661": "연결되어 있는지 아직 알 수 없습니다", "b8c2bbba2243b429": "이미 연결됨", "4f1ab8a69f4a85e5": "이 앱이 해당 머신에 연결되어 있지 않습니다", @@ -118,9 +130,9 @@ "c4eb2b21c8c58a54": "보통", "f42c2a36b3507308": "{label} 켜짐", "77cc5f738cb7d459": "{label} 꺼짐", - "2159a4897d4a4d73": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI를 {version} 이상으로 업데이트하세요.} other {{names}을(를) 사용하려면 {providerName}을(를) {version} 이상으로 업데이트하세요.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 Codex CLI를 설치하거나 새 릴리스를 기다리세요.} other {{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 {providerName}을(를) 설치하거나 새 릴리스를 기다리세요.}}", "aba3bb73ce212f0c": "{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만 Homebrew claude-code cask에는 {latestVersion}까지만 있습니다. claude-code@latest cask로 전환하세요: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 Codex CLI를 설치하거나 새 릴리스를 기다리세요.} other {{names}을(를) 사용하려면 {providerName} {version} 이상이 필요하지만, 이 설치에서 업데이트할 수 있는 최신 버전은 {latestVersion}입니다. 다른 방법으로 {providerName}을(를) 설치하거나 새 릴리스를 기다리세요.}}", + "2159a4897d4a4d73": "{runtime, select, codex {{names}을(를) 사용하려면 Codex CLI를 {version} 이상으로 업데이트하세요.} other {{names}을(를) 사용하려면 {providerName}을(를) {version} 이상으로 업데이트하세요.}}", "d887bea446534de5": "이 환경에는 {host}/{repository}을(를) 읽을 수 있는 프로젝트가 없습니다.", "4e466d60e2f7736b": "전체 풀 리퀘스트 URL을 붙여 넣으세요. 이 스레드에는 번호를 확인할 저장소가 없습니다.", "302625058bacbe38": "전체 URL을 붙여 넣으세요. 이 프로젝트의 호스트에는 알려진 {changeRequest} URL이 없습니다.", @@ -1363,7 +1375,6 @@ "d6d5517e0d6ba4e7": "파일", "96a022a5031b7e97": "경로", "e05357a50398306a": "스레드", - "c6196d99000642b4": "스레드 열기", "c3f083943d8c530e": "머신", "5d0f9cf6550667af": "스킬", "c0d3dd0975eb2f22": "설명", @@ -1948,9 +1959,9 @@ "a5e3ff0d1a60b766": "환경 릴레이 액세스를 구성할 수 없습니다: {detail}", "7d508fe978cb0f3b": "꺼짐", "3ae222ec888dd171": "추적 ID:", - "be00d572b18076d8": "길게 눌러 이 기기에서 제거", "46e2a0e828785d97": "{environment} 관리", "5392155ec0c8b0be": "이 기기에서 {environment} 제거", + "be00d572b18076d8": "길게 눌러 이 기기에서 제거", "782a518513f0777a": "{environment} 사용", "a35685d9ad9de747": "연결된 클라우드 환경 불러오는 중입니다.", "91ca3ba7b2f9d6b6": "추가로 연결된 클라우드 환경이 없습니다.", @@ -4139,6 +4150,9 @@ "ce591b4de647ecda": "{title} 열기", "4a9a6f6111329b54": "{title} 다시 불러오기", "12f0890f800baa7a": "페이지를 사용할 수 없음", + "1ff565598548c159": "{date}에 초기화됩니다.", + "6760e4db3db15d81": "모델을 교체하지 못했습니다. 다시 시도하세요.", + "d8bc550497c8992f": "이 대화는 연결된 스레드에서 계속됩니다", "9c5a2e144cefdf2f": "읽기 전용", "12d03e02951725b0": "프로젝트와 스레드를 읽습니다. 시작, 메시지 전송, 변경은 할 수 없습니다.", "63fd02d55f0e4417": "이 환경에 머신 연결", @@ -4716,7 +4730,6 @@ "2a61b633ec5035a5": "아직 에이전트 없음", "fe32057bfc66015e": "{date}에 재개됩니다.", "7792e72ddecb6733": "{date}에 초기화되었습니다.", - "1ff565598548c159": "{date}에 초기화됩니다.", "babea77bd5527a74": "초기화 시간이 지났습니다. 스레드를 직접 다시 시도하세요.", "21159303dd4c3a69": "한도 복구 설정을 변경할 수 없습니다.", "6d9729a715072bfa": "관리자용 요청 복사", diff --git a/apps/mobile/src/i18n/translations/pt-BR.json b/apps/mobile/src/i18n/translations/pt-BR.json index 497666749800d..9b2e961923ce9 100644 --- a/apps/mobile/src/i18n/translations/pt-BR.json +++ b/apps/mobile/src/i18n/translations/pt-BR.json @@ -74,6 +74,18 @@ "1861f909464425a6": "alterou o estado", "bd672d0adf5e6d9a": "Escrever neste rastreador exige a permissão de escrita no controle de versão.", "bfe81d615f5f8f75": "Esta issue está fora do escopo de todos os projetos, então aqui ela é somente leitura.", + "167e546b3c02a17f": "{model} atingiu o limite de uso", + "7037860c8460904b": "{seat}: {model} atingiu o limite de uso", + "d4ad47339d670283": "Continuou em {substitute}", + "0b95a334090835d6": "{model} atingiu o limite de uso, então esta conversa continua em uma thread vinculada. Esta continua legível.", + "c6196d99000642b4": "Abrir thread", + "552649eea02acd9e": "{seat} roda em {substitute}", + "9723cacb91446778": "{model} atingiu o limite de uso. {seat} volta a ele quando o limite for redefinido.", + "4daef274c8249495": "{substitute} está livre. Ao trocar, esta conversa continua em uma nova thread vinculada com um resumo.", + "c8128bb2bd97de3c": "{substitute} está livre. {seat} passa a usá-lo a partir da sua próxima mensagem.", + "05985243eafadf37": "Trocar para {substitute}", + "540418662b70d3d6": "Nenhum modelo favorito está livre, então esta conversa aguarda.", + "9da06299c78dfeeb": "Nenhum modelo favorito está livre, então {seat} aguarda.", "8b876f2953338661": "Ainda não se sabe se está vinculada", "b8c2bbba2243b429": "Já vinculada", "4f1ab8a69f4a85e5": "Este app não está conectado a ela", @@ -118,9 +130,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} ativado", "77cc5f738cb7d459": "{label} desativado", - "2159a4897d4a4d73": "{runtime, select, codex {Atualize a CLI do Codex para {version} ou mais recente para usar {names}.} other {Atualize o {providerName} para {version} ou mais recente para usar {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Usar {names} requer a CLI do Codex {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale a CLI do Codex de outra forma ou aguarde uma versão mais recente.} other {Usar {names} requer {providerName} {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale {providerName} de outra forma ou aguarde uma versão mais recente.}}", "aba3bb73ce212f0c": "Usar {names} requer {providerName} {version} ou mais recente, mas o cask claude-code do Homebrew só tem {latestVersion}. Mude para o cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Usar {names} requer a CLI do Codex {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale a CLI do Codex de outra forma ou aguarde uma versão mais recente.} other {Usar {names} requer {providerName} {version} ou mais recente, mas esta instalação só pode ser atualizada até {latestVersion}. Instale {providerName} de outra forma ou aguarde uma versão mais recente.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Atualize a CLI do Codex para {version} ou mais recente para usar {names}.} other {Atualize o {providerName} para {version} ou mais recente para usar {names}.}}", "d887bea446534de5": "Nenhum projeto neste ambiente consegue ler {host}/{repository}.", "4e466d60e2f7736b": "Cole a URL completa do pull request; esta thread não tem repositório para resolver o número.", "302625058bacbe38": "Cole uma URL completa; o host deste projeto não tem uma URL de {changeRequest} conhecida.", @@ -1363,7 +1375,6 @@ "d6d5517e0d6ba4e7": "Arquivo", "96a022a5031b7e97": "Caminho", "e05357a50398306a": "Thread", - "c6196d99000642b4": "Abrir thread", "c3f083943d8c530e": "Máquina", "5d0f9cf6550667af": "Skill", "c0d3dd0975eb2f22": "Descrição", @@ -1947,9 +1958,9 @@ "a5e3ff0d1a60b766": "Não foi possível configurar o acesso do ambiente ao relay: {detail}", "7d508fe978cb0f3b": "Desligado", "3ae222ec888dd171": "ID do trace:", - "be00d572b18076d8": "Mantenha pressionado para remover deste dispositivo", "46e2a0e828785d97": "Gerenciar {environment}", "5392155ec0c8b0be": "Remover {environment} deste dispositivo", + "be00d572b18076d8": "Mantenha pressionado para remover deste dispositivo", "782a518513f0777a": "Ativar {environment}", "a35685d9ad9de747": "Carregando ambientes na nuvem vinculados.", "91ca3ba7b2f9d6b6": "Nenhum outro ambiente na nuvem vinculado.", @@ -4139,6 +4150,9 @@ "ce591b4de647ecda": "Abrir {title}", "4a9a6f6111329b54": "Recarregar {title}", "12f0890f800baa7a": "Página indisponível", + "1ff565598548c159": "Redefine {date}.", + "6760e4db3db15d81": "Não foi possível trocar o modelo. Tente novamente.", + "d8bc550497c8992f": "Esta conversa continua em uma thread vinculada", "9c5a2e144cefdf2f": "Somente leitura", "12d03e02951725b0": "Lê projetos e threads. Não pode iniciar, enviar mensagens nem alterar nada.", "63fd02d55f0e4417": "Vincular uma máquina a este ambiente", @@ -4731,7 +4745,6 @@ "2a61b633ec5035a5": "Nenhum agente ainda", "fe32057bfc66015e": "Retoma {date}.", "7792e72ddecb6733": "Redefinido em {date}.", - "1ff565598548c159": "Redefine {date}.", "babea77bd5527a74": "O horário de renovação já passou. Tente a thread novamente manualmente.", "21159303dd4c3a69": "Não foi possível alterar a recuperação de limite.", "6d9729a715072bfa": "Copiar pedido para o administrador", diff --git a/apps/mobile/src/i18n/translations/ru.json b/apps/mobile/src/i18n/translations/ru.json index 24fb4ac8d2b19..e2616eab19dd1 100644 --- a/apps/mobile/src/i18n/translations/ru.json +++ b/apps/mobile/src/i18n/translations/ru.json @@ -74,6 +74,18 @@ "1861f909464425a6": "изменил(а) состояние", "bd672d0adf5e6d9a": "Для записи в этот трекер нужна область записи в контроль версий.", "bfe81d615f5f8f75": "Этот issue вне области всех проектов, поэтому здесь он доступен только для чтения.", + "167e546b3c02a17f": "{model} достигла лимита использования", + "7037860c8460904b": "{seat}: {model} достигла лимита использования", + "d4ad47339d670283": "Продолжено на {substitute}", + "0b95a334090835d6": "{model} достигла лимита использования, поэтому разговор продолжается в связанном треде. Этот тред остаётся доступным для чтения.", + "c6196d99000642b4": "Открыть тред", + "552649eea02acd9e": "{seat} работает на {substitute}", + "9723cacb91446778": "{model} достигла лимита использования. {seat} вернётся к ней, когда лимит сбросится.", + "4daef274c8249495": "{substitute} свободна. При замене разговор продолжится в новом связанном треде с кратким изложением.", + "c8128bb2bd97de3c": "{substitute} свободна. {seat} будет использовать её со следующего сообщения.", + "05985243eafadf37": "Заменить на {substitute}", + "540418662b70d3d6": "Нет свободной избранной модели, поэтому разговор ждёт.", + "9da06299c78dfeeb": "Нет свободной избранной модели, поэтому {seat} ждёт.", "8b876f2953338661": "Пока неизвестно, привязана ли она", "b8c2bbba2243b429": "Уже привязана", "4f1ab8a69f4a85e5": "Это приложение к ней не подключено", @@ -118,9 +130,9 @@ "c4eb2b21c8c58a54": "Обычная", "f42c2a36b3507308": "{label}: вкл.", "77cc5f738cb7d459": "{label}: выкл.", - "2159a4897d4a4d73": "{runtime, select, codex {Обновите Codex CLI до {version} или новее, чтобы использовать {names}.} other {Обновите {providerName} до {version} или новее, чтобы использовать {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {Для {names} нужна Codex CLI {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите Codex CLI другим способом или дождитесь нового релиза.} other {Для {names} нужен {providerName} {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите {providerName} другим способом или дождитесь нового релиза.}}", "aba3bb73ce212f0c": "Для {names} нужен {providerName} {version} или новее, но в Homebrew cask claude-code есть только {latestVersion}. Перейдите на cask claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {Для {names} нужна Codex CLI {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите Codex CLI другим способом или дождитесь нового релиза.} other {Для {names} нужен {providerName} {version} или новее, но эта установка может обновиться максимум до {latestVersion}. Установите {providerName} другим способом или дождитесь нового релиза.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Обновите Codex CLI до {version} или новее, чтобы использовать {names}.} other {Обновите {providerName} до {version} или новее, чтобы использовать {names}.}}", "d887bea446534de5": "Ни один проект в этом окружении не может прочитать {host}/{repository}.", "4e466d60e2f7736b": "Вставьте полный URL пул-реквеста: у этого треда нет репозитория, по которому можно найти номер.", "302625058bacbe38": "Вставьте полный URL: для хоста этого проекта неизвестен формат URL {changeRequest}.", @@ -1363,7 +1375,6 @@ "d6d5517e0d6ba4e7": "Файл", "96a022a5031b7e97": "Путь", "e05357a50398306a": "Тред", - "c6196d99000642b4": "Открыть тред", "c3f083943d8c530e": "Машина", "5d0f9cf6550667af": "Навык", "c0d3dd0975eb2f22": "Описание", @@ -1971,9 +1982,9 @@ "a5e3ff0d1a60b766": "Не удалось настроить доступ окружения к relay: {detail}", "7d508fe978cb0f3b": "Выкл.", "3ae222ec888dd171": "ID трассировки:", - "be00d572b18076d8": "Нажмите и удерживайте, чтобы удалить с этого устройства", "46e2a0e828785d97": "Управление {environment}", "5392155ec0c8b0be": "Удалить {environment} с этого устройства", + "be00d572b18076d8": "Нажмите и удерживайте, чтобы удалить с этого устройства", "782a518513f0777a": "Включить {environment}", "a35685d9ad9de747": "Загрузка привязанных облачных окружений.", "91ca3ba7b2f9d6b6": "Других привязанных облачных окружений нет.", @@ -4193,6 +4204,9 @@ "ce591b4de647ecda": "Открыть {title}", "4a9a6f6111329b54": "Перезагрузить {title}", "12f0890f800baa7a": "Страница недоступна", + "1ff565598548c159": "Сброс {date}.", + "6760e4db3db15d81": "Не удалось заменить модель. Повторите попытку.", + "d8bc550497c8992f": "Этот разговор продолжается в связанном треде", "9c5a2e144cefdf2f": "Только чтение", "12d03e02951725b0": "Чтение проектов и тредов. Нельзя ничего запускать, отправлять или менять.", "63fd02d55f0e4417": "Привязать машину к этому окружению", @@ -4809,7 +4823,6 @@ "2a61b633ec5035a5": "Агентов пока нет", "fe32057bfc66015e": "Возобновится {date}.", "7792e72ddecb6733": "Сброшен {date}.", - "1ff565598548c159": "Сброс {date}.", "babea77bd5527a74": "Время сброса прошло. Повторите тред вручную.", "21159303dd4c3a69": "Не удалось изменить восстановление после лимита.", "6d9729a715072bfa": "Копировать запрос для администратора", diff --git a/apps/mobile/src/i18n/translations/sv.json b/apps/mobile/src/i18n/translations/sv.json index b80843748c3ba..1edd912eee7ef 100644 --- a/apps/mobile/src/i18n/translations/sv.json +++ b/apps/mobile/src/i18n/translations/sv.json @@ -74,6 +74,18 @@ "1861f909464425a6": "ändrade status", "bd672d0adf5e6d9a": "Att skriva till den här ärendehanteraren kräver skrivomfånget för versionshantering.", "bfe81d615f5f8f75": "Det här ärendet ligger utanför alla projekts eget omfång, så det är skrivskyddat här.", + "167e546b3c02a17f": "{model} har nått sin användningsgräns", + "7037860c8460904b": "{seat}: {model} har nått sin användningsgräns", + "d4ad47339d670283": "Fortsätter på {substitute}", + "0b95a334090835d6": "{model} har nått sin användningsgräns, så konversationen fortsätter i en länkad tråd. Den här förblir läsbar.", + "c6196d99000642b4": "Öppna tråd", + "552649eea02acd9e": "{seat} körs på {substitute}", + "9723cacb91446778": "{model} har nått sin användningsgräns. {seat} återgår till den när gränsen återställs.", + "4daef274c8249495": "{substitute} är ledig. Vid byte fortsätter konversationen i en ny länkad tråd med en sammanfattning.", + "c8128bb2bd97de3c": "{substitute} är ledig. {seat} använder den från ditt nästa meddelande.", + "05985243eafadf37": "Byt till {substitute}", + "540418662b70d3d6": "Ingen favoritmodell är ledig, så konversationen väntar.", + "9da06299c78dfeeb": "Ingen favoritmodell är ledig, så {seat} väntar.", "8b876f2953338661": "Det är ännu inte känt om den är länkad", "b8c2bbba2243b429": "Redan länkad", "4f1ab8a69f4a85e5": "Den här appen är inte ansluten till den", @@ -118,9 +130,9 @@ "c4eb2b21c8c58a54": "Normal", "f42c2a36b3507308": "{label} på", "77cc5f738cb7d459": "{label} av", - "2159a4897d4a4d73": "{runtime, select, codex {Uppdatera Codex CLI till {version} eller senare för att använda {names}.} other {Uppdatera {providerName} till {version} eller senare för att använda {names}.}}", - "a0854b0f9604fc7b": "{runtime, select, codex {{names} kräver Codex CLI {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera Codex CLI på ett annat sätt eller vänta på en nyare version.} other {{names} kräver {providerName} {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera {providerName} på ett annat sätt eller vänta på en nyare version.}}", "aba3bb73ce212f0c": "{names} kräver {providerName} {version} eller senare, men Homebrew-casken claude-code har bara {latestVersion}. Byt till casken claude-code@latest: {command}", + "a0854b0f9604fc7b": "{runtime, select, codex {{names} kräver Codex CLI {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera Codex CLI på ett annat sätt eller vänta på en nyare version.} other {{names} kräver {providerName} {version} eller senare, men den här installationen kan bara uppdateras till {latestVersion}. Installera {providerName} på ett annat sätt eller vänta på en nyare version.}}", + "2159a4897d4a4d73": "{runtime, select, codex {Uppdatera Codex CLI till {version} eller senare för att använda {names}.} other {Uppdatera {providerName} till {version} eller senare för att använda {names}.}}", "d887bea446534de5": "Inget projekt i den här miljön kan läsa {host}/{repository}.", "4e466d60e2f7736b": "Klistra in hela pull request-URL:en; den här tråden har inget repo att slå upp numret i.", "302625058bacbe38": "Klistra in en fullständig URL; det här projektets värd har ingen känd URL för {changeRequest}.", @@ -1363,7 +1375,6 @@ "d6d5517e0d6ba4e7": "Fil", "96a022a5031b7e97": "Sökväg", "e05357a50398306a": "Tråd", - "c6196d99000642b4": "Öppna tråd", "c3f083943d8c530e": "Dator", "5d0f9cf6550667af": "Färdighet", "c0d3dd0975eb2f22": "Beskrivning", @@ -1947,9 +1958,9 @@ "a5e3ff0d1a60b766": "Kunde inte konfigurera miljöns reläåtkomst: {detail}", "7d508fe978cb0f3b": "Av", "3ae222ec888dd171": "Spårnings-id:", - "be00d572b18076d8": "Tryck länge för att ta bort från den här enheten", "46e2a0e828785d97": "Hantera {environment}", "5392155ec0c8b0be": "Ta bort {environment} från den här enheten", + "be00d572b18076d8": "Tryck länge för att ta bort från den här enheten", "782a518513f0777a": "Aktivera {environment}", "a35685d9ad9de747": "Läser in länkade molnmiljöer.", "91ca3ba7b2f9d6b6": "Inga ytterligare länkade molnmiljöer.", @@ -4145,6 +4156,9 @@ "ce591b4de647ecda": "Öppna {title}", "4a9a6f6111329b54": "Läs in {title} igen", "12f0890f800baa7a": "Sidan är inte tillgänglig", + "1ff565598548c159": "Återställs {date}.", + "6760e4db3db15d81": "Det gick inte att byta modell. Försök igen.", + "d8bc550497c8992f": "Den här konversationen fortsätter i en länkad tråd", "9c5a2e144cefdf2f": "Endast läsning", "12d03e02951725b0": "Läs projekt och trådar. Kan inte starta, skicka meddelanden eller ändra något.", "63fd02d55f0e4417": "Länka en dator till den här miljön", @@ -4737,7 +4751,6 @@ "2a61b633ec5035a5": "Inga agenter än", "fe32057bfc66015e": "Återupptas {date}.", "7792e72ddecb6733": "Återställdes {date}.", - "1ff565598548c159": "Återställs {date}.", "babea77bd5527a74": "Återställningstiden har passerat. Försök med tråden igen manuellt.", "21159303dd4c3a69": "Kunde inte ändra återhämtning efter gräns.", "6d9729a715072bfa": "Kopiera begäran till administratören", diff --git a/apps/mobile/src/i18n/translations/zh.json b/apps/mobile/src/i18n/translations/zh.json index 4b9be3ca97195..e85dfe7d6e22e 100644 --- a/apps/mobile/src/i18n/translations/zh.json +++ b/apps/mobile/src/i18n/translations/zh.json @@ -74,6 +74,18 @@ "1861f909464425a6": "更改了状态", "bd672d0adf5e6d9a": "写入此跟踪器需要版本控制写入权限范围。", "bfe81d615f5f8f75": "此 issue 不在任何项目自身的范围内,因此在这里为只读。", + "167e546b3c02a17f": "{model} 已达使用限额", + "7037860c8460904b": "{seat}:{model} 已达使用限额", + "d4ad47339d670283": "已改用 {substitute} 继续", + "0b95a334090835d6": "{model} 已达使用限额,因此此对话在关联的线程中继续。当前线程仍可阅读。", + "c6196d99000642b4": "打开会话", + "552649eea02acd9e": "{seat} 使用 {substitute} 运行", + "9723cacb91446778": "{model} 已达使用限额。限额重置后,{seat} 会改回该模型。", + "4daef274c8249495": "{substitute} 空闲。切换后,此对话将在带有摘要的新关联线程中继续。", + "c8128bb2bd97de3c": "{substitute} 空闲。{seat} 将从你的下一条消息起使用它。", + "05985243eafadf37": "切换到 {substitute}", + "540418662b70d3d6": "没有空闲的收藏模型,因此此对话将等待。", + "9da06299c78dfeeb": "没有空闲的收藏模型,因此 {seat} 将等待。", "8b876f2953338661": "尚不清楚是否已关联", "b8c2bbba2243b429": "已关联", "4f1ab8a69f4a85e5": "此应用未连接到该机器", @@ -118,9 +130,9 @@ "c4eb2b21c8c58a54": "普通", "f42c2a36b3507308": "{label} 开启", "77cc5f738cb7d459": "{label} 关闭", - "2159a4897d4a4d73": "{runtime, select, codex {请将 Codex CLI 更新到 {version} 或更高版本以使用 {names}。} other {请将 {providerName} 更新到 {version} 或更高版本以使用 {names}。}}", - "a0854b0f9604fc7b": "{runtime, select, codex {使用 {names} 需要 Codex CLI {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 Codex CLI,或等待更新的版本发布。} other {使用 {names} 需要 {providerName} {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 {providerName},或等待更新的版本发布。}}", "aba3bb73ce212f0c": "使用 {names} 需要 {providerName} {version} 或更高版本,但 Homebrew 的 claude-code cask 只有 {latestVersion}。请切换到 claude-code@latest cask:{command}", + "a0854b0f9604fc7b": "{runtime, select, codex {使用 {names} 需要 Codex CLI {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 Codex CLI,或等待更新的版本发布。} other {使用 {names} 需要 {providerName} {version} 或更高版本,但此安装最多只能更新到 {latestVersion}。请通过其他方式安装 {providerName},或等待更新的版本发布。}}", + "2159a4897d4a4d73": "{runtime, select, codex {请将 Codex CLI 更新到 {version} 或更高版本以使用 {names}。} other {请将 {providerName} 更新到 {version} 或更高版本以使用 {names}。}}", "d887bea446534de5": "此环境中没有项目能读取 {host}/{repository}。", "4e466d60e2f7736b": "请粘贴完整的 pull request URL;此会话没有可用于解析编号的仓库。", "302625058bacbe38": "请粘贴完整 URL;此项目的托管平台没有已知的 {changeRequest} URL。", @@ -1363,7 +1375,6 @@ "d6d5517e0d6ba4e7": "文件", "96a022a5031b7e97": "路径", "e05357a50398306a": "会话", - "c6196d99000642b4": "打开会话", "c3f083943d8c530e": "机器", "5d0f9cf6550667af": "技能", "c0d3dd0975eb2f22": "描述", @@ -1949,9 +1960,9 @@ "a5e3ff0d1a60b766": "无法配置环境的中继访问:{detail}", "7d508fe978cb0f3b": "关闭", "3ae222ec888dd171": "追踪 ID:", - "be00d572b18076d8": "长按以从此设备移除", "46e2a0e828785d97": "管理 {environment}", "5392155ec0c8b0be": "从此设备移除 {environment}", + "be00d572b18076d8": "长按以从此设备移除", "782a518513f0777a": "启用 {environment}", "a35685d9ad9de747": "正在加载关联的云环境。", "91ca3ba7b2f9d6b6": "没有其他关联的云环境。", @@ -4142,6 +4153,9 @@ "ce591b4de647ecda": "打开 {title}", "4a9a6f6111329b54": "重新加载 {title}", "12f0890f800baa7a": "页面不可用", + "1ff565598548c159": "{date} 重置。", + "6760e4db3db15d81": "无法切换模型。请重试。", + "d8bc550497c8992f": "此对话在关联的线程中继续", "9c5a2e144cefdf2f": "只读", "12d03e02951725b0": "读取项目和会话,不能启动会话、发送消息或进行任何更改。", "63fd02d55f0e4417": "将一台机器关联到此环境", @@ -4720,7 +4734,6 @@ "2a61b633ec5035a5": "还没有智能体", "fe32057bfc66015e": "{date} 继续。", "7792e72ddecb6733": "已于 {date} 重置。", - "1ff565598548c159": "{date} 重置。", "babea77bd5527a74": "重置时间已过,请手动重试这个会话。", "21159303dd4c3a69": "无法更改限制恢复设置。", "6d9729a715072bfa": "复制给管理员的申请", diff --git a/apps/mobile/src/state/delivery.ts b/apps/mobile/src/state/delivery.ts index 6e9049d08b0be..885bcc52df66a 100644 --- a/apps/mobile/src/state/delivery.ts +++ b/apps/mobile/src/state/delivery.ts @@ -2,6 +2,12 @@ import { createDeliveryEnvironmentAtoms } from "@t3tools/client-runtime/state/de import { Atom } from "effect/reactivity"; import type { DeliveryThreadBinding } from "@t3tools/contracts"; import { connectionAtomRuntime } from "../connection/runtime"; +import { serverEnvironment } from "./server"; +import { environmentThreadShells } from "./threads"; -export const deliveryEnvironment = createDeliveryEnvironmentAtoms(connectionAtomRuntime); +export const deliveryEnvironment = createDeliveryEnvironmentAtoms(connectionAtomRuntime, { + threadShellAtom: environmentThreadShells.threadShellAtom, + settingsAtom: serverEnvironment.settingsValueAtom, + providersAtom: serverEnvironment.providersValueAtom, +}); export const emptyDeliveryBindingAtom = Atom.make(null); diff --git a/apps/server/src/auth/RpcAuthorization.ts b/apps/server/src/auth/RpcAuthorization.ts index c3de6f335b2dc..48f8751a528b6 100644 --- a/apps/server/src/auth/RpcAuthorization.ts +++ b/apps/server/src/auth/RpcAuthorization.ts @@ -137,6 +137,8 @@ export const RPC_REQUIRED_SCOPES = { [WS_METHODS.deliveryArchivedBoardThreads]: AuthOrchestrationReadScope, [WS_METHODS.deliveryReleaseThread]: AuthOrchestrationOperateScope, [WS_METHODS.deliverySetThreadLineup]: AuthOrchestrationOperateScope, + [WS_METHODS.deliveryLimitedSeats]: AuthOrchestrationReadScope, + [WS_METHODS.deliverySwapLimitedSeat]: AuthOrchestrationOperateScope, [WS_METHODS.serverReportClientActivity]: AuthOrchestrationReadScope, [WS_METHODS.scheduledTasksSubscribe]: AuthOrchestrationReadScope, [WS_METHODS.secretsAnswerRequest]: AuthOrchestrationOperateScope, diff --git a/apps/server/src/delivery/LimitedSeatSwap.test.ts b/apps/server/src/delivery/LimitedSeatSwap.test.ts new file mode 100644 index 0000000000000..68ca10bbdac8d --- /dev/null +++ b/apps/server/src/delivery/LimitedSeatSwap.test.ts @@ -0,0 +1,388 @@ +import { + DEFAULT_SERVER_SETTINGS, + type DeliveryOrchestrationConfig, + type OrchestrationV2ServerCommand, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + RunId, + type ServerProvider, + ThreadId, +} from "@t3tools/contracts"; +import { expect, it } from "@effect/vitest"; +import type { LimitedSeatFacts } from "@t3tools/shared/limitedSeat"; +import { createModelSelection } from "@t3tools/shared/model"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import { limitRecoveryCommand } from "../orchestration-v2/UsageLimitRecoveryWorker.ts"; +import * as DeliveryService from "./DeliveryService.ts"; +import * as LimitedSeats from "./LimitedSeats.ts"; +import * as LimitedSeatSwap from "./LimitedSeatSwap.ts"; + +const threadId = ThreadId.make("lead-thread"); +const runId = RunId.make("lead-run"); +const target = LimitedSeatSwap.leadHandoffThreadId(runId); +const NOW = "2026-11-22T12:00:00.000Z"; +const RESET = "2026-11-22T17:00:00.000Z"; +const id = ProviderInstanceId.make; +const model = (instanceId: string, slug: string) => createModelSelection(id(instanceId), slug); + +const provider = (instanceId: string, driver: string): ServerProvider => ({ + instanceId: id(instanceId), + driver: ProviderDriverKind.make(driver), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: NOW, + models: [], + slashCommands: [], + skills: [], +}); + +function setup({ + policy = undefined as DeliveryOrchestrationConfig["limitedSeat"], + favorites = [ + ["kimi", "kimi-k3"], + ["deepseek", "deepseek-v4"], + ] as ReadonlyArray, + bound = true, + lineage = {} as Record, + ordinary = false, + limitedSeat = false, + limitedScout = false, + /** The hand-off's fork lands but its first turn has not: the window a status read can fall in. */ + startsNoTurn = false, +} = {}) { + const providers = [ + provider("claude", "claudeAgent"), + provider("codex", "codex"), + provider("kimi", "kimi"), + provider("deepseek", "deepseek"), + ]; + const lineups = new Map(); + if (!ordinary) + lineups.set(threadId, { + participants: [ + { seat: "critic", role: "reviewer", modelSelection: model("codex", "gpt-astra") }, + { seat: "scout", role: "researcher", modelSelection: model("deepseek", "deepseek-v4") }, + ], + ...(policy ? { limitedSeat: policy } : {}), + }); + const binding = { team: "research", role: "lead", workspace: "/repo" }; + const bindings = new Map(bound ? [[threadId, binding]] : []); + const shell = { + id: threadId, + title: "Migration plan", + projectId: ProjectId.make("project"), + modelSelection: model("claude", "claude-fable"), + lineage, + status: "failed", + lastErrorClass: "usage_limit", + usageLimitResetAt: RESET, + latestRunId: runId, + latestRunCompletedAt: DateTime.makeUnsafe("2026-11-22T11:59:00.000Z"), + updatedAt: DateTime.makeUnsafe("2026-11-22T11:59:00.000Z"), + archivedAt: null, + settledOverride: null, + pendingRuntimeRequest: null, + snoozedUntil: null, + limitRecovery: null as null | { + runId: RunId; + resetAt: string; + autoResume: boolean; + snooze?: boolean; + }, + }; + // A fork keeps its source's model until its first turn lands, so the fake never updates it. + const created = new Map< + string, + { id: ThreadId; modelSelection: unknown; deletedAt: null; runs: Array } + >(); + const commands: Array = []; + const calls: Array = []; + const facts = (): LimitedSeatFacts => ({ + now: Date.parse(NOW), + projectId: shell.projectId, + providers, + threadLimits: [ + { instanceId: id("claude"), model: "claude-fable", resetAt: RESET }, + ...(limitedSeat ? [{ instanceId: id("codex"), model: "gpt-astra", resetAt: RESET }] : []), + ...(limitedScout + ? [{ instanceId: id("deepseek"), model: "deepseek-v4", resetAt: RESET }] + : []), + ], + settings: { + ...DEFAULT_SERVER_SETTINGS, + providerInstances: Object.fromEntries( + providers.map((entry) => [entry.instanceId, { driver: entry.driver, enabled: true }]), + ), + favorites: favorites.map(([instanceId, slug]) => ({ provider: id(instanceId), model: slug })), + }, + }); + const delivery = { + threadState: (thread: ThreadId) => + Effect.succeed({ + binding: bindings.get(thread) ?? null, + pending: null, + ...(lineups.has(thread) ? { lineup: lineups.get(thread) } : {}), + }), + bindThread: (input: { threadId: ThreadId; driver: string; orchestration?: unknown }) => + Effect.sync(() => { + calls.push(`bind:${input.threadId}:${input.driver}`); + bindings.set(input.threadId, binding); + lineups.set(input.threadId, input.orchestration as DeliveryOrchestrationConfig); + return binding; + }), + setThreadLineup: (input: { threadId: ThreadId; orchestration: DeliveryOrchestrationConfig }) => + Effect.sync(() => { + calls.push(`lineup:${input.threadId}`); + lineups.set(input.threadId, input.orchestration); + return {}; + }), + } as unknown as DeliveryService.DeliveryService["Service"]; + const projections = { + getThreadShell: (thread: ThreadId) => Effect.succeed(thread === threadId ? shell : null), + findThread: (thread: ThreadId) => Effect.sync(() => created.get(thread) ?? null), + getThreadRecords: (thread: ThreadId) => + Effect.sync(() => ({ runs: created.get(thread)?.runs ?? [] })), + } as unknown as ProjectionStore.ProjectionStoreV2["Service"]; + const threads = { + dispatch: (command: OrchestrationV2ServerCommand) => + Effect.sync(() => { + commands.push(command); + calls.push(command.type); + if (command.type === "thread.fork" && !created.has(command.targetThreadId)) + created.set(command.targetThreadId, { + id: command.targetThreadId, + modelSelection: shell.modelSelection, + deletedAt: null, + runs: [], + }); + if (command.type === "message.dispatch" && command.modelSelection && !startsNoTurn) { + const runs = created.get(command.threadId)!.runs; + if (runs.length === 0) runs.push({ modelSelection: command.modelSelection }); + } + if (command.type === "thread.metadata.update" && command.limitRecovery) + shell.limitRecovery = { + runId: command.limitRecovery.runId, + resetAt: command.limitRecovery.resetAt, + autoResume: command.limitRecovery.autoResume ?? false, + }; + return { sequence: commands.length, storedEvents: [] }; + }), + } as unknown as ThreadManagementService.ThreadManagementService["Service"]; + const layer = LimitedSeatSwap.layer.pipe( + Layer.provide( + Layer.mergeAll( + Layer.succeed(DeliveryService.DeliveryService, delivery), + Layer.succeed(LimitedSeats.LimitedSeats, { facts: () => Effect.sync(facts) }), + Layer.succeed(ProjectionStore.ProjectionStoreV2, projections), + Layer.succeed(ThreadManagementService.ThreadManagementService, threads), + Layer.succeed(ProviderAdapterRegistry.ProviderAdapterRegistryV2, { + get: (instanceId: ProviderInstanceId) => Effect.succeed({ driver: instanceId }), + } as unknown as ProviderAdapterRegistry.ProviderAdapterRegistryV2["Service"]), + ), + ), + ); + return { layer, shell, commands, calls, lineups }; +} + +it.effect("hands a limited lead on to a linked thread on the first free favorite", () => { + const fixture = setup(); + return Effect.gen(function* () { + const swaps = yield* LimitedSeatSwap.LimitedSeatSwap; + expect(yield* swaps.handOffLimitedLead(threadId)).toBe(target); + // Bound to the team first, disarmed, forked from the failed run, and only then started. + expect(fixture.calls).toEqual([ + `bind:${target}:kimi`, + "thread.metadata.update", + "thread.fork", + "message.dispatch", + ]); + expect(fixture.commands[1]).toMatchObject({ + sourceThreadId: threadId, + targetThreadId: target, + sourcePoint: { type: "run", runId }, + }); + expect(fixture.commands[2]).toMatchObject({ + threadId: target, + text: LimitedSeatSwap.LEAD_HANDOFF_MESSAGE, + // Deepseek is a favorite too, but a seat of the conversation already runs it. + modelSelection: { instanceId: "kimi", model: "kimi-k3" }, + }); + expect(fixture.lineups.get(target)).toEqual(fixture.lineups.get(threadId)); + expect((yield* swaps.status(threadId)).notices).toEqual([ + expect.objectContaining({ seat: null, state: "swapped", continuedIn: target }), + ]); + }).pipe(Effect.provide(fixture.layer)); +}); + +it.effect("names the model the hand-off started, not the one the fork inherited", () => { + const fixture = setup({ limitedSeat: true }); + return Effect.gen(function* () { + const swaps = yield* LimitedSeatSwap.LimitedSeatSwap; + yield* swaps.handOffLimitedLead(threadId); + // The old thread runs no more turns: its limited seat is offered no swap there. + expect((yield* swaps.status(threadId)).notices).toEqual([ + { + seat: null, + state: "swapped", + continuedIn: target, + limited: expect.objectContaining({ model: "claude-fable" }), + substitute: { instanceId: "kimi", model: "kimi-k3" }, + }, + ]); + }).pipe(Effect.provide(fixture.layer)); +}); + +it.effect("names the substitute about to start while the fork has no turn yet", () => { + const fixture = setup({ startsNoTurn: true }); + return Effect.gen(function* () { + const swaps = yield* LimitedSeatSwap.LimitedSeatSwap; + yield* swaps.handOffLimitedLead(threadId); + expect((yield* swaps.status(threadId)).notices).toEqual([ + expect.objectContaining({ + state: "swapped", + substitute: { instanceId: "kimi", model: "kimi-k3" }, + }), + ]); + // Asked again, the turn that never landed is sent on the substitute, not the limited model. + yield* swaps.handOffLimitedLead(threadId); + expect(fixture.commands.at(-1)).toMatchObject({ + type: "message.dispatch", + modelSelection: { instanceId: "kimi", model: "kimi-k3" }, + }); + }).pipe(Effect.provide(fixture.layer)); +}); + +it.effect( + "disarms the old thread's limit recovery, so the same work is never resumed there", + () => { + const fixture = setup(); + return Effect.gen(function* () { + const resumes = () => + limitRecoveryCommand(fixture.shell as never, true, Date.parse("2026-11-22T18:00:00.000Z")); + // Left alone, the recovery worker arms the thread and later sends its resume. + expect(resumes()).toMatchObject({ type: "thread.metadata.update" }); + yield* (yield* LimitedSeatSwap.LimitedSeatSwap).handOffLimitedLead(threadId); + expect(fixture.commands[0]).toMatchObject({ + type: "thread.metadata.update", + threadId, + limitRecovery: { runId, resetAt: RESET, autoResume: false, snooze: false }, + }); + expect(resumes()).toBeNull(); + }).pipe(Effect.provide(fixture.layer)); + }, +); + +it.effect("makes one thread however often the swap is asked for", () => { + const fixture = setup({ policy: "ask" }); + return Effect.gen(function* () { + const swaps = yield* LimitedSeatSwap.LimitedSeatSwap; + const [offer] = (yield* swaps.status(threadId)).notices; + expect(offer).toMatchObject({ seat: null, state: "offered", substitute: { model: "kimi-k3" } }); + // Ask me never hands on by itself. + expect(yield* swaps.handOffLimitedLead(threadId)).toBeNull(); + expect(fixture.commands).toHaveLength(0); + const input = { threadId, seat: null, modelSelection: offer!.substitute! }; + expect(yield* swaps.swap(input)).toEqual({ continuedIn: target }); + expect(yield* swaps.swap(input)).toEqual({ continuedIn: target }); + const ids = fixture.commands.map((command) => command.commandId); + // The second click repeats the same commands, which the orchestrator answers from receipts. + expect(ids.slice(3)).toEqual([ids[1], ids[2]]); + expect(new Set(ids).size).toBe(3); + expect(fixture.calls.filter((call) => call.startsWith("bind:"))).toHaveLength(1); + }).pipe(Effect.provide(fixture.layer)); +}); + +it.effect("leaves the lead as it failed, with a notice, when no favorite is free", () => { + const fixture = setup({ favorites: [["deepseek", "deepseek-v4"]] }); + return Effect.gen(function* () { + const swaps = yield* LimitedSeatSwap.LimitedSeatSwap; + expect(yield* swaps.handOffLimitedLead(threadId)).toBeNull(); + expect(fixture.calls).toEqual([]); + expect((yield* swaps.status(threadId)).notices).toEqual([ + { seat: null, state: "none-free", substitute: null, limited: expect.anything() }, + ]); + }).pipe(Effect.provide(fixture.layer)); +}); + +it.effect("refuses a model that is not a free favorite", () => { + const fixture = setup({ policy: "ask" }); + return Effect.gen(function* () { + const swaps = yield* LimitedSeatSwap.LimitedSeatSwap; + const refusal = yield* Effect.flip( + swaps.swap({ threadId, seat: null, modelSelection: model("codex", "gpt-sol") }), + ); + expect(refusal.detail).toContain("no longer free"); + expect(fixture.calls).toEqual([]); + }).pipe(Effect.provide(fixture.layer)); +}); + +it.effect("carries the lineup to a conversation bound to no team", () => { + const fixture = setup({ bound: false }); + return Effect.gen(function* () { + yield* (yield* LimitedSeatSwap.LimitedSeatSwap).handOffLimitedLead(threadId); + expect(fixture.calls[0]).toBe(`lineup:${target}`); + }).pipe(Effect.provide(fixture.layer)); +}); + +it.effect("records the substitute a person agreed to for a seat, once", () => { + const fixture = setup({ policy: "ask", limitedSeat: true }); + return Effect.gen(function* () { + const swaps = yield* LimitedSeatSwap.LimitedSeatSwap; + const offer = (yield* swaps.status(threadId)).notices.find( + (notice) => notice.seat === "critic", + ); + expect(offer).toMatchObject({ state: "offered", substitute: { model: "kimi-k3" } }); + const input = { threadId, seat: "critic", modelSelection: offer!.substitute! }; + expect(yield* swaps.swap(input)).toEqual({ continuedIn: null }); + expect(yield* swaps.swap(input)).toEqual({ continuedIn: null }); + expect(fixture.calls).toEqual([`lineup:${threadId}`]); + expect(fixture.lineups.get(threadId)?.participants[0]?.substitute).toEqual(offer!.substitute); + expect( + (yield* swaps.status(threadId)).notices.find((notice) => notice.seat === "critic"), + ).toMatchObject({ state: "swapped", substitute: { model: "kimi-k3" } }); + }).pipe(Effect.provide(fixture.layer)); +}); + +it.effect("never offers a seat the model another seat stands in on", () => { + const fixture = setup({ policy: "ask", limitedSeat: true, limitedScout: true }); + return Effect.gen(function* () { + const swaps = yield* LimitedSeatSwap.LimitedSeatSwap; + const kimi = model("kimi", "kimi-k3"); + const noticeFor = (seat: string) => + Effect.map(swaps.status(threadId), (status) => + status.notices.find((notice) => notice.seat === seat), + ); + expect(yield* noticeFor("scout")).toMatchObject({ state: "offered", substitute: kimi }); + yield* swaps.swap({ threadId, seat: "critic", modelSelection: kimi }); + expect(yield* noticeFor("critic")).toMatchObject({ state: "swapped", substitute: kimi }); + expect(yield* noticeFor("scout")).toMatchObject({ state: "none-free", substitute: null }); + const refused = yield* Effect.flip( + swaps.swap({ threadId, seat: "scout", modelSelection: kimi }), + ); + expect(refused.detail).toBe("kimi-k3 is no longer free. Choose again from the notice."); + expect(fixture.lineups.get(threadId)?.participants[1]?.substitute).toBeUndefined(); + }).pipe(Effect.provide(fixture.layer)); +}); + +it.effect.each([ + { name: "an ordinary chat", options: { ordinary: true } }, + { name: "a board task's conversation", options: { lineage: { engineIntake: "task-1" } } }, +])("does not govern $name", ({ options }) => { + const fixture = setup(options); + return Effect.gen(function* () { + const swaps = yield* LimitedSeatSwap.LimitedSeatSwap; + expect(yield* swaps.status(threadId)).toEqual({ policy: null, notices: [] }); + expect(yield* swaps.handOffLimitedLead(threadId)).toBeNull(); + expect(fixture.calls).toEqual([]); + }).pipe(Effect.provide(fixture.layer)); +}); diff --git a/apps/server/src/delivery/LimitedSeatSwap.ts b/apps/server/src/delivery/LimitedSeatSwap.ts new file mode 100644 index 0000000000000..1d939ced6677e --- /dev/null +++ b/apps/server/src/delivery/LimitedSeatSwap.ts @@ -0,0 +1,432 @@ +import { + CommandId, + DeliveryError, + type DeliveryLimitedSeatNotice, + deliveryLimitedSeatPolicy, + type DeliveryLimitedSeatStatus, + type DeliveryLimitedSeatSwapInput, + type DeliveryLimitedSeatSwapResult, + type DeliveryOrchestrationConfig, + isServerOwnedThreadLineage, + MessageId, + type ModelSelection, + type OrchestrationV2ServerCommand, + type OrchestrationV2ThreadShell, + type RunId, + ThreadId, +} from "@t3tools/contracts"; +import { + agreedStandIn, + firstFreeFavorite, + isFreeCandidate, + limitedLeadHandoffThreadId, + limitedLeadPool, + limitedSeatPool, + seatLimit, + seatModelOf, + type SeatModel, +} from "@t3tools/shared/limitedSeat"; +import { createModelSelection } from "@t3tools/shared/model"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; + +import * as Orchestrator from "../orchestration-v2/Orchestrator.ts"; +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ProviderAdapterRegistry from "../orchestration-v2/ProviderAdapterRegistry.ts"; +import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; +import { forkParked } from "../serverActivation.ts"; +import * as DeliveryService from "./DeliveryService.ts"; +import * as LimitedSeats from "./LimitedSeats.ts"; + +/** What a lead handed on to a new thread is told, as limit recovery tells a thread it resumes. */ +export const LEAD_HANDOFF_MESSAGE = "Continue where you left off."; + +export const leadHandoffThreadId = limitedLeadHandoffThreadId; + +/** + * What hands a limited lead on, in order. The old thread's resume is disarmed first, so the same + * work is never run twice and a refusal creates nothing; then the fork, then its first turn on + * the substitute, which carries the handoff summary. Every id follows from the failed run. + */ +export function leadHandoffCommands(input: { + readonly threadId: ThreadId; + readonly title: string; + readonly runId: RunId; + /** The reset the old thread would resume at; null when there is none to disarm. */ + readonly resetAt: string | null; + readonly substitute: ModelSelection; +}): ReadonlyArray { + const identity = `limited-lead:${input.threadId}:${input.runId}`; + const target = leadHandoffThreadId(input.runId); + return [ + ...(input.resetAt === null + ? [] + : [ + { + type: "thread.metadata.update" as const, + commandId: CommandId.make(`${identity}:disarm`), + threadId: input.threadId, + limitRecovery: { + runId: input.runId, + resetAt: input.resetAt, + autoResume: false, + snooze: false, + }, + }, + ]), + { + type: "thread.fork", + commandId: CommandId.make(`${identity}:fork`), + sourceThreadId: input.threadId, + targetThreadId: target, + sourcePoint: { type: "run", runId: input.runId }, + title: input.title, + createdBy: "system", + creationSource: "server", + }, + { + type: "message.dispatch", + commandId: CommandId.make(`${identity}:continue`), + messageId: MessageId.make(`${identity}:continue`), + threadId: target, + text: LEAD_HANDOFF_MESSAGE, + attachments: [], + modelSelection: input.substitute, + dispatchMode: { type: "start_immediately" }, + createdBy: "agent", + creationSource: "server", + }, + ]; +} + +export class LimitedSeatSwap extends Context.Service< + LimitedSeatSwap, + { + readonly status: ( + threadId: ThreadId, + ) => Effect.Effect; + /** One click of the notice. Repeating it changes nothing and starts nothing twice. */ + readonly swap: ( + input: DeliveryLimitedSeatSwapInput, + ) => Effect.Effect; + /** + * Hands a limited lead on when its conversation swaps automatically. Null where there is + * nothing to hand on: no limit, another setting, or no free favorite. + */ + readonly handOffLimitedLead: (threadId: ThreadId) => Effect.Effect; + } +>()("t3/delivery/LimitedSeatSwap") {} + +const refused = (detail: string) => new DeliveryError({ reason: "invalid", detail }); +const storage = (cause: unknown) => + new DeliveryError({ + reason: "storage", + detail: + cause instanceof Error + ? cause.message || "Thread state could not be read." + : "Thread state could not be read.", + }); + +/** The usage limit a thread's latest run failed on, while it has not reset. */ +function leadLimit(shell: OrchestrationV2ThreadShell, now: number) { + if ( + shell.status !== "failed" || + shell.lastErrorClass !== "usage_limit" || + shell.latestRunId === null || + shell.archivedAt !== null || + (shell.usageLimitResetAt != null && Date.parse(shell.usageLimitResetAt) <= now) + ) + return null; + return { + runId: shell.latestRunId, + limited: { ...seatModelOf(shell.modelSelection), resetAt: shell.usageLimitResetAt ?? null }, + }; +} + +const selectionOf = (model: SeatModel): ModelSelection => + createModelSelection(model.instanceId, model.model); + +const make = Effect.gen(function* () { + const deliveryOption = yield* Effect.serviceOption(DeliveryService.DeliveryService); + const limitedSeats = yield* LimitedSeats.LimitedSeats; + const projections = yield* ProjectionStore.ProjectionStoreV2; + const threads = yield* ThreadManagementService.ThreadManagementService; + const adapters = yield* ProviderAdapterRegistry.ProviderAdapterRegistryV2; + + /** The conversation as this setting governs it, or null where it does not. */ + const governed = Effect.fn("LimitedSeatSwap.governed")(function* (threadId: ThreadId) { + if (Option.isNone(deliveryOption)) return null; + const shell = yield* projections.getThreadShell(threadId).pipe(Effect.mapError(storage)); + if ( + shell === null || + isServerOwnedThreadLineage(shell.lineage) || + shell.lineage.relationshipToParent === "subagent" || + shell.lineage.sideChat === true + ) + return null; + const state = yield* deliveryOption.value.threadState(threadId); + if (state.lineup === undefined) return null; + return { + delivery: deliveryOption.value, + shell, + state, + lineup: state.lineup, + facts: yield* limitedSeats.facts(threadId), + }; + }); + + /** + * The thread a limited run was handed on to, with the model the hand-off started it on. The + * fork carries its source's model until that first turn lands, so the thread's own model is + * not the substitute. Null where the run was not handed on, or the thread was deleted since. + */ + const handedOn = Effect.fn("LimitedSeatSwap.handedOn")(function* (runId: RunId) { + const target = leadHandoffThreadId(runId); + const continued = yield* projections.findThread(target); + if (continued === null) return null; + const { runs } = yield* projections.getThreadRecords(target, ["runs"]); + return { + id: continued.id, + deleted: continued.deletedAt !== null, + dispatched: runs[0]?.modelSelection ?? null, + }; + }, Effect.mapError(storage)); + + const status: LimitedSeatSwap["Service"]["status"] = Effect.fn("LimitedSeatSwap.status")( + function* (threadId) { + const conversation = yield* governed(threadId); + if (conversation === null) return { policy: null, notices: [] }; + const { shell, lineup, facts } = conversation; + const policy = deliveryLimitedSeatPolicy(lineup); + const notices: Array = []; + const lead = leadLimit(shell, facts.now); + if (lead !== null) { + const continued = yield* handedOn(lead.runId); + const free = firstFreeFavorite( + limitedLeadPool({ facts, roster: lineup.participants, lead: shell.modelSelection }), + ); + if (continued !== null && !continued.deleted) { + // Between the fork and its first turn, the substitute is the one about to be started. + const substitute = continued.dispatched ?? (free === null ? null : selectionOf(free)); + if (substitute !== null) + notices.push({ + seat: null, + limited: lead.limited, + state: "swapped", + substitute, + continuedIn: continued.id, + }); + // This thread runs no more turns, so its seats have nothing left to swap for. + return { policy, notices }; + } + // A deleted continuation cannot be made again; the recovery banner's resume is the way on. + if (continued === null && policy !== "skip") { + notices.push({ + seat: null, + limited: lead.limited, + state: free === null ? "none-free" : "offered", + substitute: free === null ? null : selectionOf(free), + }); + } + } + if (policy !== "skip") { + for (const seat of lineup.participants) { + const limit = seatLimit(facts, seatModelOf(seat.modelSelection)); + if (limit === null) continue; + const pool = limitedSeatPool({ + facts, + roster: lineup.participants, + lead: shell.modelSelection, + seat, + runsOn: (other) => + agreedStandIn({ facts, policy, seat: other }) ?? other.modelSelection, + }); + const limited = { + instanceId: limit.instanceId, + model: limit.model, + resetAt: limit.resetAt, + }; + const free = firstFreeFavorite(pool); + const asks = policy === "ask" || seat.picked === true; + if (asks && seat.substitute && isFreeCandidate(pool, seatModelOf(seat.substitute))) { + notices.push({ + seat: seat.seat, + limited, + state: "swapped", + substitute: seat.substitute, + }); + } else if (free === null) { + notices.push({ seat: seat.seat, limited, state: "none-free", substitute: null }); + } else if (asks) { + notices.push({ + seat: seat.seat, + limited, + state: "offered", + substitute: selectionOf(free), + }); + } + } + } + return { policy, notices }; + }, + ); + + const handOffLead = Effect.fn("LimitedSeatSwap.handOffLead")(function* ( + conversation: NonNullable>>, + /** The model a person clicked; absent, the first free favorite. */ + chosen: ModelSelection | undefined, + ) { + const { delivery, shell, state, lineup, facts } = conversation; + const lead = leadLimit(shell, facts.now); + if (lead === null) return yield* refused("This conversation's lead is not limited now."); + const target = leadHandoffThreadId(lead.runId); + const existing = yield* handedOn(lead.runId); + if (existing?.deleted === true) + return yield* refused( + "The thread this conversation continued in was deleted. Resume this one at its reset.", + ); + const pool = limitedLeadPool({ + facts, + roster: lineup.participants, + lead: shell.modelSelection, + }); + const free = firstFreeFavorite(pool); + // A hand-off already started keeps its model: a second click or sweep only finishes it. + const substitute = + existing !== null && existing.dispatched !== null + ? existing.dispatched + : chosen !== undefined + ? isFreeCandidate(pool, seatModelOf(chosen)) + ? chosen + : yield* refused(`${chosen.model} is no longer free. Choose again from the notice.`) + : free === null + ? yield* refused("No favorite model is free.") + : selectionOf(free); + const dispatch = (command: Parameters[0]) => + threads + .dispatch(command) + .pipe( + Effect.mapError( + (cause) => + new DeliveryError({ reason: "refused", detail: cause.message || "Refused." }), + ), + ); + // The team's roles and tools are bound to the thread before it exists, as a seat's are. + const targetState = yield* delivery.threadState(target); + if (state.binding !== null && targetState.binding === null) { + const adapter = yield* adapters + .get(substitute.instanceId) + .pipe(Effect.mapError(() => refused(`${substitute.model}'s provider is unavailable.`))); + yield* delivery.bindThread({ + threadId: target, + team: state.binding.team, + role: state.binding.role, + driver: adapter.driver, + cwd: state.binding.workspace, + orchestration: lineup, + }); + } else if (state.binding === null && targetState.lineup === undefined) { + yield* delivery.setThreadLineup({ threadId: target, orchestration: lineup }); + } + for (const command of leadHandoffCommands({ + threadId: shell.id, + title: shell.title, + runId: lead.runId, + // Nothing to disarm when no reset is known, or a person already turned the resume off. + resetAt: + shell.limitRecovery?.runId === lead.runId && shell.limitRecovery.autoResume === false + ? null + : lead.limited.resetAt, + substitute, + })) + yield* dispatch(command); + return target; + }); + + const swap: LimitedSeatSwap["Service"]["swap"] = Effect.fn("LimitedSeatSwap.swap")( + function* (input) { + const conversation = yield* governed(input.threadId); + if (conversation === null) + return yield* refused("This conversation has no setting for a limited seat."); + if (input.seat === null) + return { continuedIn: yield* handOffLead(conversation, input.modelSelection) }; + const { delivery, shell, lineup, facts } = conversation; + const seat = lineup.participants.find((candidate) => candidate.seat === input.seat); + if (seat === undefined) return yield* refused(`${input.seat} is not in this conversation.`); + const chosen = seatModelOf(input.modelSelection); + const agreed = seat.substitute; + if (agreed?.instanceId === chosen.instanceId && agreed.model === chosen.model) + return { continuedIn: null }; + if (seatLimit(facts, seatModelOf(seat.modelSelection)) === null) + return yield* refused(`${input.seat} is not limited now.`); + const policy = deliveryLimitedSeatPolicy(lineup); + const pool = limitedSeatPool({ + facts, + roster: lineup.participants, + lead: shell.modelSelection, + seat, + runsOn: (other) => agreedStandIn({ facts, policy, seat: other }) ?? other.modelSelection, + }); + if (!isFreeCandidate(pool, chosen)) + return yield* refused(`${chosen.model} is no longer free. Choose again from the notice.`); + const orchestration: DeliveryOrchestrationConfig = { + ...lineup, + participants: lineup.participants.map((candidate) => + candidate.seat === seat.seat + ? { ...candidate, substitute: input.modelSelection } + : candidate, + ), + }; + yield* delivery.setThreadLineup({ threadId: input.threadId, orchestration }); + return { continuedIn: null }; + }, + ); + + const handOffLimitedLead: LimitedSeatSwap["Service"]["handOffLimitedLead"] = Effect.fn( + "LimitedSeatSwap.handOffLimitedLead", + )( + function* (threadId) { + const conversation = yield* governed(threadId); + if ( + conversation === null || + deliveryLimitedSeatPolicy(conversation.lineup) !== "swap" || + leadLimit(conversation.shell, conversation.facts.now) === null + ) + return null; + return yield* handOffLead(conversation, undefined); + }, + // No free favorite, or a refusal: the thread stays as it failed, with its notice. + (effect, threadId) => + effect.pipe( + Effect.catchCause((cause) => + Effect.logInfo("limited-seats.lead-not-handed-on", { threadId, cause }).pipe( + Effect.as(null), + ), + ), + ), + ); + + return LimitedSeatSwap.of({ status, swap, handOffLimitedLead }); +}); + +export const layer = Layer.effect(LimitedSeatSwap, make); + +/** Hands a limited lead on as soon as its turn fails, where the conversation swaps automatically. */ +export const layerWorker = Layer.effectDiscard( + Effect.gen(function* () { + const swaps = yield* LimitedSeatSwap; + const orchestrator = yield* Orchestrator.OrchestratorV2; + yield* forkParked( + Stream.runForEach(orchestrator.streamDomainEvents, (event) => + // The failure and its usage-limit error are separate events, in either order. + (event.type === "run.updated" && event.payload.status === "failed") || + (event.type === "turn-item.updated" && event.payload.type === "error") + ? swaps.handOffLimitedLead(event.threadId) + : Effect.void, + ), + ); + }), +); diff --git a/apps/server/src/delivery/LimitedSeats.ts b/apps/server/src/delivery/LimitedSeats.ts new file mode 100644 index 0000000000000..90d839ac1c398 --- /dev/null +++ b/apps/server/src/delivery/LimitedSeats.ts @@ -0,0 +1,103 @@ +import { type ThreadId } from "@t3tools/contracts"; +import type { LimitedSeatFacts, SeatLimit } from "@t3tools/shared/limitedSeat"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; + +import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; +import * as ProviderInstanceRegistry from "../provider/ProviderInstanceRegistry.ts"; +import * as ServerSettings from "../serverSettings.ts"; + +/** How far back a conversation's failed seats and fork parents are read for a limit. */ +const MAX_FAILED_SEATS = 24; +const MAX_FORK_PARENTS = 8; + +export class LimitedSeats extends Context.Service< + LimitedSeats, + { + /** + * What decides whether a seat of this conversation is limited and what may stand in: + * Favorites, provider status, and the usage limits its own turns and seats failed on. + */ + readonly facts: (threadId: ThreadId) => Effect.Effect; + } +>()("t3/delivery/LimitedSeats") {} + +const make = Effect.gen(function* () { + const projections = yield* ProjectionStore.ProjectionStoreV2; + const instances = yield* ProviderInstanceRegistry.ProviderInstanceRegistry; + const settings = yield* ServerSettings.ServerSettingsService; + + const facts: LimitedSeats["Service"]["facts"] = Effect.fn("LimitedSeats.facts")( + function* (threadId) { + const now = DateTime.toEpochMillis(yield* DateTime.now); + const { subagents } = yield* projections.getThreadRecords(threadId, ["subagents"]); + const failedSeats = subagents + .filter((task) => task.teamChat !== undefined && task.status === "failed") + .toSorted( + (left, right) => + DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt), + ) + .slice(0, MAX_FAILED_SEATS) + .flatMap((task) => (task.childThreadId === null ? [] : [task.childThreadId])); + const threadLimits: Array = []; + const read = Effect.fn("LimitedSeats.readLimit")(function* (id: ThreadId) { + const shell = yield* projections.getThreadShell(id); + if ( + shell?.lastErrorClass === "usage_limit" && + shell.status === "failed" && + (shell.usageLimitResetAt == null || Date.parse(shell.usageLimitResetAt) > now) + ) { + threadLimits.push({ + instanceId: shell.modelSelection.instanceId, + model: shell.modelSelection.model, + resetAt: shell.usageLimitResetAt ?? null, + }); + } + return shell; + }); + // A conversation handed on from a limited lead must not be handed straight back. + let current: ThreadId | null = threadId; + for (let depth = 0; current !== null && depth <= MAX_FORK_PARENTS; depth += 1) { + const shell: Effect.Success> = yield* read(current); + current = + shell?.lineage.relationshipToParent === "fork" ? shell.lineage.parentThreadId : null; + } + yield* Effect.forEach(failedSeats, read, { discard: true }); + const root = yield* projections.getThreadShell(threadId); + return { + now, + providers: yield* Effect.forEach( + yield* instances.listInstances, + (instance) => instance.snapshot.getSnapshot, + ), + settings: yield* settings.getSettings, + projectId: root?.projectId ?? null, + threadLimits, + }; + }, + // A limit that cannot be read is no limit: the seat starts as it always did. + (effect) => + effect.pipe( + Effect.catchCause((cause) => + Effect.logWarning("limited-seats.facts-failed", cause).pipe( + Effect.andThen( + Effect.gen(function* () { + return { + now: DateTime.toEpochMillis(yield* DateTime.now), + providers: [], + settings: { favorites: [], providerInstances: {}, projectSettingsOverrides: {} }, + projectId: null, + threadLimits: [], + } satisfies LimitedSeatFacts; + }), + ), + ), + ), + ), + ); + return LimitedSeats.of({ facts }); +}); + +export const layer = Layer.effect(LimitedSeats, make); diff --git a/apps/server/src/delivery/NativeTeamChat.test.ts b/apps/server/src/delivery/NativeTeamChat.test.ts index bc98621cb9c85..235fca847d0e1 100644 --- a/apps/server/src/delivery/NativeTeamChat.test.ts +++ b/apps/server/src/delivery/NativeTeamChat.test.ts @@ -11,6 +11,9 @@ import { type OrchestrationV2TurnItem, type ChatAttachment, type OrchestrationV2ServerCommand, + DEFAULT_SERVER_SETTINGS, + ProviderDriverKind, + type ServerProvider, } from "@t3tools/contracts"; import { expect, it } from "@effect/vitest"; import * as Effect from "effect/Effect"; @@ -19,10 +22,12 @@ import { threadContextRecord, formatComposerContextReference, } from "@t3tools/shared/composerContextReferences"; +import type { LimitedSeatFacts } from "@t3tools/shared/limitedSeat"; import { createModelSelection } from "@t3tools/shared/model"; import { ServerConfig } from "../config.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as DeliveryService from "./DeliveryService.ts"; +import * as LimitedSeats from "./LimitedSeats.ts"; import * as EventSink from "../orchestration-v2/EventSink.ts"; import * as NativeTeamChat from "./NativeTeamChat.ts"; import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; @@ -60,6 +65,9 @@ function setup({ unbound = false, callsTeam = undefined as string | undefined, participantConfiguration = "research@3#abc", + /** What T3 knows about limits and Favorites; absent, no seat is ever treated as limited. */ + limitFacts = undefined as (() => LimitedSeatFacts) | undefined, + boardOwned = false, } = {}) { const participants = [ { @@ -183,6 +191,8 @@ function setup({ worktreePath: null, projectId: ProjectId.make("project"), runtimeMode: threadAccess, + modelSelection: createModelSelection(ProviderInstanceId.make("lead-work"), "lead-model"), + lineage: boardOwned ? { engineIntake: "task-1" } : {}, }, runs: missingRun ? [] : [run], messages: [message], @@ -272,6 +282,11 @@ function setup({ Effect.provideService(ThreadManagementService.ThreadManagementService, threads), Effect.provideService(ProviderAdapterRegistry.ProviderAdapterRegistryV2, adapters), Effect.provideService(ProviderInstanceRegistry.ProviderInstanceRegistry, instances), + limitFacts === undefined + ? (effect) => effect + : Effect.provideService(LimitedSeats.LimitedSeats, { + facts: () => Effect.sync(limitFacts), + }), Effect.provide(IdAllocator.layer), ), }; @@ -849,3 +864,273 @@ it.effect( } }), ); + +const LIMIT_RESET = "2026-11-22T17:00:00.000Z"; +const RESET_SHOWN = NativeTeamChat.formatLimitReset(LIMIT_RESET); +const MODEL_NAMES = { "claude-model": "Claude Model", "kimi-k3": "Kimi K3" }; +const limitedProvider = (instanceId: string, driver: string, limited = false): ServerProvider => ({ + instanceId: ProviderInstanceId.make(instanceId), + driver: ProviderDriverKind.make(driver), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-11-22T11:00:00.000Z", + // Named as the model picker names them; the notes use these names, not the ids. + models: Object.entries(MODEL_NAMES).map(([slug, name]) => ({ + slug, + name, + isCustom: false, + capabilities: null, + })), + slashCommands: [], + skills: [], + ...(limited + ? { + usageLimits: { + checkedAt: "2026-11-22T11:00:00.000Z", + windows: [ + { + id: "primary", + kind: "session", + label: "5 hours", + usedPercent: 100, + resetsAt: LIMIT_RESET, + }, + ], + }, + } + : {}), +}); + +/** The researcher's Claude is limited; Favorites are Kimi, then DeepSeek. */ +function limitedResearcher( + options: Omit[0]>, "limitFacts"> & { + readonly favorites?: ReadonlyArray; + } = {}, +) { + const limitedInstances = new Set(["claude-work"]); + const providers = [ + ["claude-work", "claudeAgent"], + ["codex-work", "codex"], + ["builder-work", "codex"], + ["kimi-work", "kimi"], + ["deepseek-work", "deepseek"], + ] as const; + const { favorites, ...rest } = options; + const fixture = setup({ + third: true, + ...rest, + limitFacts: () => ({ + now: Date.parse("2026-11-22T12:00:00.000Z"), + projectId: ProjectId.make("project"), + threadLimits: [], + providers: providers.map(([instanceId, driver]) => + limitedProvider(instanceId, driver, limitedInstances.has(instanceId)), + ), + settings: { + ...DEFAULT_SERVER_SETTINGS, + providerInstances: Object.fromEntries( + providers.map(([instanceId, driver]) => [ + ProviderInstanceId.make(instanceId), + { driver: ProviderDriverKind.make(driver), enabled: true }, + ]), + ), + favorites: ( + favorites ?? [ + ["kimi-work", "kimi-k3"], + ["deepseek-work", "deepseek-v4"], + ] + ).map(([provider, model]) => ({ provider: ProviderInstanceId.make(provider), model })), + }, + }), + }); + const seatsOn = () => + Object.fromEntries( + [...fixture.admissions.values()].map((command) => [ + `${command.teamChat.stage}:${command.teamChat.seat}`, + command.modelSelection.model, + ]), + ); + return { ...fixture, limitedInstances, seatsOn }; +} + +it.effect("starts a limited seat on the first free favorite and notes why", () => + Effect.gen(function* () { + const fixture = limitedResearcher(); + const service = yield* fixture.service; + yield* service.prepareTurn({ threadId, runId }); + // Swap automatically is the default: the lineup states no setting. + expect(fixture.lineup.current).not.toHaveProperty("limitedSeat"); + expect(fixture.seatsOn()).toEqual({ + "contribution:researcher": "kimi-k3", + "contribution:critic": "codex-model", + "contribution:builder": "builder-model", + }); + const researcher = [...fixture.admissions.values()].find( + (command) => command.teamChat.seat === "researcher", + )!; + expect(researcher.modelSelection.instanceId).toBe("kimi-work"); + expect(researcher.teamChat.substituteFor).toEqual({ + instanceId: "claude-work", + model: "claude-model", + resetAt: LIMIT_RESET, + }); + expect(fixture.notices).toHaveLength(1); + expect(fixture.notices[0]).toMatchObject({ + status: "completed", + title: "researcher · substitute", + message: `researcher runs on Kimi K3 this turn: Claude Model has reached its usage limit until ${RESET_SHOWN}.`, + }); + // Whoever reads the researcher's contribution is told which model stood in for it. + for (const task of fixture.tasks) + Object.assign(task, { status: "completed", result: "Noted." }); + yield* service.prepareTurn({ threadId, runId }); + const critique = [...fixture.admissions.values()].find( + (command) => command.teamChat.stage === "critique", + )!; + expect(critique.task).toContain( + "kimi-work/kimi-k3, standing in for claude-model, which reached its usage limit, completed", + ); + }), +); + +it.effect( + "swaps a seat once a turn: the critique keeps the stand-in or sits out, never a third model", + () => + Effect.gen(function* () { + const fixture = limitedResearcher({ critique: "always" }); + const service = yield* fixture.service; + yield* service.prepareTurn({ threadId, runId }); + for (const task of fixture.tasks) task.status = "completed"; + // The stand-in reaches its own limit before the critique round. + fixture.limitedInstances.add("kimi-work"); + yield* service.prepareTurn({ threadId, runId }); + expect(fixture.seatsOn()).toEqual({ + "contribution:researcher": "kimi-k3", + "contribution:critic": "codex-model", + "contribution:builder": "builder-model", + "critique:critic": "codex-model", + "critique:builder": "builder-model", + }); + expect(fixture.notices.at(-1)).toMatchObject({ + status: "failed", + message: expect.stringContaining("a seat is swapped once a turn"), + }); + }), +); + +it.effect("keeps the same stand-in for the critique round while it stays free", () => + Effect.gen(function* () { + const fixture = limitedResearcher({ critique: "always" }); + const service = yield* fixture.service; + yield* service.prepareTurn({ threadId, runId }); + for (const task of fixture.tasks) task.status = "completed"; + yield* service.prepareTurn({ threadId, runId }); + expect(fixture.seatsOn()["critique:researcher"]).toBe("kimi-k3"); + }), +); + +it.effect("leaves a limited seat waiting with a notice when no favorite is free", () => + Effect.gen(function* () { + // The only favorites are the limited account's own model and a provider that is not there. + const fixture = limitedResearcher({ + favorites: [ + ["claude-work", "claude-other"], + ["lead-work", "lead-model"], + ], + }); + const service = yield* fixture.service; + yield* service.prepareTurn({ threadId, runId }); + expect(Object.keys(fixture.seatsOn())).toEqual(["contribution:critic", "contribution:builder"]); + expect(fixture.notices).toHaveLength(1); + expect(fixture.notices[0]).toMatchObject({ + status: "failed", + title: "researcher · skipped", + message: expect.stringContaining("No favorite model is free, so researcher waits."), + }); + }), +); + +it.effect("does not swap a model a person chose by hand; the notice still names the free one", () => + Effect.gen(function* () { + const fixture = limitedResearcher(); + Object.assign(fixture.participants[0]!, { picked: true }); + const service = yield* fixture.service; + yield* service.prepareTurn({ threadId, runId }); + expect(fixture.seatsOn()).not.toHaveProperty("contribution:researcher"); + expect(fixture.notices[0]?.type === "system_notice" && fixture.notices[0].message).toBe( + `researcher: Claude Model has reached its usage limit until ${RESET_SHOWN}. Its model was chosen by hand, so it is not swapped without asking. Kimi K3 is free: swap to it from the notice to use it from the next message.`, + ); + }), +); + +it.effect("asks before a swap, and uses the model the person agreed to", () => + Effect.gen(function* () { + const fixture = limitedResearcher(); + fixture.lineup.current = { ...fixture.lineup.current!, limitedSeat: "ask" } as never; + const service = yield* fixture.service; + yield* service.prepareTurn({ threadId, runId }); + expect(fixture.seatsOn()).not.toHaveProperty("contribution:researcher"); + expect(fixture.notices[0]).toMatchObject({ + message: expect.stringContaining("Kimi K3 is free: swap to it from the notice"), + }); + + const agreed = limitedResearcher(); + Object.assign(agreed.participants[0]!, { + substitute: createModelSelection(ProviderInstanceId.make("deepseek-work"), "deepseek-v4"), + }); + agreed.lineup.current = { ...agreed.lineup.current!, limitedSeat: "ask" } as never; + yield* (yield* agreed.service).prepareTurn({ threadId, runId }); + expect(agreed.seatsOn()["contribution:researcher"]).toBe("deepseek-v4"); + }), +); + +it.effect("leaves another seat's agreed substitute to that seat", () => + Effect.gen(function* () { + const fixture = limitedResearcher(); + fixture.limitedInstances.add("codex-work"); + // The critic comes after the researcher in the roster, and already agreed to Kimi. + Object.assign(fixture.participants[1]!, { + substitute: createModelSelection(ProviderInstanceId.make("kimi-work"), "kimi-k3"), + }); + fixture.lineup.current = { ...fixture.lineup.current!, limitedSeat: "ask" } as never; + yield* (yield* fixture.service).prepareTurn({ threadId, runId }); + expect(fixture.seatsOn()["contribution:critic"]).toBe("kimi-k3"); + expect(fixture.seatsOn()).not.toHaveProperty("contribution:researcher"); + expect(fixture.notices[0]).toMatchObject({ + message: expect.stringContaining("deepseek-v4 is free: swap to it from the notice"), + }); + }), +); + +it.effect( + "reads the setting at the start of each turn, so a change applies from the next message", + () => + Effect.gen(function* () { + const fixture = limitedResearcher(); + const service = yield* fixture.service; + yield* service.prepareTurn({ threadId, runId }); + expect(fixture.seatsOn()["contribution:researcher"]).toBe("kimi-k3"); + // The person chooses Leave it out; the next message is a new turn with nothing recorded. + fixture.lineup.current = { ...fixture.lineup.current!, limitedSeat: "skip" } as never; + fixture.tasks.length = 0; + fixture.notices.length = 0; + fixture.admissions.clear(); + yield* service.prepareTurn({ threadId, runId }); + expect(fixture.seatsOn()).not.toHaveProperty("contribution:researcher"); + expect(fixture.notices[0]).toMatchObject({ + message: `researcher: Claude Model has reached its usage limit until ${RESET_SHOWN}. Left out of this message.`, + }); + }), +); + +it.effect("leaves a board task's conversation to its team's own setting", () => + Effect.gen(function* () { + const fixture = limitedResearcher({ boardOwned: true }); + yield* (yield* fixture.service).prepareTurn({ threadId, runId }); + expect(fixture.seatsOn()["contribution:researcher"]).toBe("claude-model"); + expect(fixture.notices).toHaveLength(0); + }), +); diff --git a/apps/server/src/delivery/NativeTeamChat.ts b/apps/server/src/delivery/NativeTeamChat.ts index a2e72fef870bd..883d657f096a1 100644 --- a/apps/server/src/delivery/NativeTeamChat.ts +++ b/apps/server/src/delivery/NativeTeamChat.ts @@ -1,13 +1,27 @@ import { CommandId, + deliveryLimitedSeatPolicy, deliveryParticipantAccess, isCompactionCommandMessage, + isServerOwnedThreadLineage, + type ModelSelection, parseGoalCommand, type OrchestrationV2Subagent, RunId, ThreadId, } from "@t3tools/contracts"; import { projectComposerContextForProvider } from "@t3tools/shared/composerContextReferences"; +import { + agreedStandIn, + firstFreeFavorite, + isFreeCandidate, + type LimitedSeatFacts, + limitedSeatPool, + seatLimit, + type SeatModel, + seatModelOf, +} from "@t3tools/shared/limitedSeat"; +import { createModelSelection } from "@t3tools/shared/model"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as EventSink from "../orchestration-v2/EventSink.ts"; @@ -21,6 +35,7 @@ import { resolveAttachmentPath } from "../attachmentStore.ts"; import { ServerConfig } from "../config.ts"; import * as ProjectStore from "../orchestration-v2/ProjectStore.ts"; import * as DeliveryService from "./DeliveryService.ts"; +import * as LimitedSeats from "./LimitedSeats.ts"; import { teamDiscussionContext } from "./teamDiscussionContext.ts"; import * as ProjectionStore from "../orchestration-v2/ProjectionStore.ts"; import * as ThreadManagementService from "../orchestration-v2/ThreadManagementService.ts"; @@ -59,11 +74,39 @@ export const isNativeTeamChatError = Schema.is(NativeTeamChatError); const terminal = (task: OrchestrationV2Subagent) => ["completed", "failed", "cancelled", "interrupted"].includes(task.status); +/** + * A usage limit's reset as a turn note writes it. The server cannot know each reader's clock, so + * the time is the server's own and names its zone. + */ +export const formatLimitReset = (resetAt: string) => + Option.match(DateTime.make(resetAt), { + onNone: () => resetAt, + onSome: (time) => + DateTime.toDate(time).toLocaleString(undefined, { + month: "short", + day: "numeric", + hour: "numeric", + minute: "2-digit", + timeZoneName: "short", + }), + }); + +/** The name the model picker shows for a model; its id where the provider lists no name. */ +const modelName = (facts: LimitedSeatFacts, model: SeatModel) => + facts.providers + .find((provider) => provider.instanceId === model.instanceId) + ?.models.find((candidate) => candidate.slug === model.model)?.name ?? model.model; + const contributions = (tasks: ReadonlyArray) => tasks .map( (task) => - `${task.teamChat?.seat ?? task.title} (${task.providerInstanceId}/${task.model}, ${task.status}; native child ${task.childThreadId}):\n${ + `${task.teamChat?.seat ?? task.title} (${task.providerInstanceId}/${task.model}${ + // The lead attributes insights to a seat's model, so it is told when another stood in. + task.teamChat?.substituteFor === undefined + ? "" + : `, standing in for ${task.teamChat.substituteFor.model}, which reached its usage limit` + }, ${task.status}; native child ${task.childThreadId}):\n${ task.result === null ? "No contribution was returned." : task.result.length > 6000 @@ -75,6 +118,7 @@ const contributions = (tasks: ReadonlyArray) => export const make = Effect.gen(function* () { const deliveryOption = yield* Effect.serviceOption(DeliveryService.DeliveryService); + const limitedSeatsOption = yield* Effect.serviceOption(LimitedSeats.LimitedSeats); const projections = yield* ProjectionStore.ProjectionStoreV2; const eventSink = yield* EventSink.EventSinkV2; const threads = yield* ThreadManagementService.ThreadManagementService; @@ -159,10 +203,13 @@ export const make = Effect.gen(function* () { if (notice?.type === "system_notice") skipped.set(seat.seat, notice.message); } // Notices preserve admission failures even when a provider or team changes on a later wake. + let noticesWritten = 0; const recordSkip = Effect.fn("NativeTeamChat.recordSkip")(function* ( seat: string, reason: string, noticeId = skipId(seat), + // A substitute is a note on a seat that joins, not a seat that is left out. + substitute = false, ) { const now = yield* DateTime.now; const written = yield* eventSink.writeIfRunCurrent({ @@ -189,9 +236,11 @@ export const make = Effect.gen(function* () { nativeItemRef: null, parentItemId: null, ordinal: - Math.max(0, ...parent.turnItems.map((item) => item.ordinal)) + skipped.size + 1, - status: "failed", - title: `${seat} · skipped`, + Math.max(0, ...parent.turnItems.map((item) => item.ordinal)) + + skipped.size + + (noticesWritten += 1), + status: substitute ? "completed" : "failed", + title: substitute ? `${seat} · substitute` : `${seat} · skipped`, message: reason, startedAt: now, completedAt: now, @@ -202,7 +251,7 @@ export const make = Effect.gen(function* () { }); if (!written.committed) return yield* new NativeTeamChatError({ runId: input.runId, reason: "state" }); - skipped.set(seat, reason); + if (!substitute) skipped.set(seat, reason); }); const fallback = Effect.fn("NativeTeamChat.fallback")(function* (reason: string) { if (!tasks.every(terminal)) return { ready: false, context: "" }; @@ -247,6 +296,97 @@ export const make = Effect.gen(function* () { ? { readOnly: true, access: "approval-required" as const } : { readOnly: false, access }; }; + const policy = deliveryLimitedSeatPolicy(lineup); + type StandIn = { + readonly selection: ModelSelection; + readonly substituteFor?: NonNullable< + NonNullable["substituteFor"] + >; + }; + /** Seats this call starts on a substitute, by seat. */ + const standIns = new Map(); + const turnStandIn = (seat: string): ModelSelection | undefined => { + const task = tasks.find( + (candidate) => + candidate.teamChat?.seat === seat && candidate.teamChat.substituteFor !== undefined, + ); + if (task === undefined) return undefined; + return ( + task.modelSelection ?? + (task.model === null + ? undefined + : createModelSelection(task.providerInstanceId, task.model)) + ); + }; + const runsOn = (seat: (typeof roster)[number]) => + standIns.get(seat.seat)?.selection ?? turnStandIn(seat.seat) ?? seat.modelSelection; + /** + * What a seat starts on: its own model, or a substitute when that one is limited. Undefined + * once the seat has been left out, with its notice written. + */ + const standIn = Effect.fn("NativeTeamChat.standIn")(function* ( + seat: (typeof roster)[number], + facts: LimitedSeatFacts, + ) { + const own = seatModelOf(seat.modelSelection); + const limit = seatLimit(facts, own); + if (limit === null) return { selection: seat.modelSelection } satisfies StandIn; + const limited = `${seat.seat}: ${modelName(facts, own)} has reached its usage limit${limit.resetAt ? ` until ${formatLimitReset(limit.resetAt)}` : ""}.`; + const substituteFor = { ...own, resetAt: limit.resetAt }; + const earlier = turnStandIn(seat.seat); + if (earlier !== undefined) { + // One swap a turn: the stand-in chosen for this turn is kept, or the seat sits out. + if (seatLimit(facts, seatModelOf(earlier)) === null) + return { selection: earlier, substituteFor } satisfies StandIn; + yield* recordSkip( + seat.seat, + `${limited} Its substitute ${modelName(facts, seatModelOf(earlier))} is limited too, and a seat is swapped once a turn.`, + ); + return undefined; + } + if (policy === "skip") { + yield* recordSkip(seat.seat, `${limited} Left out of this message.`); + return undefined; + } + const pool = limitedSeatPool({ + facts, + roster, + lead: parent.thread.modelSelection, + seat, + // A seat not started yet still holds the substitute a person agreed to for it. + runsOn: (other) => + standIns.get(other.seat)?.selection ?? + turnStandIn(other.seat) ?? + agreedStandIn({ facts, policy, seat: other }) ?? + other.modelSelection, + }); + const free = firstFreeFavorite(pool); + const none = `${limited} No favorite model is free, so ${seat.seat} waits.`; + if (policy === "ask" || seat.picked === true) { + const agreed = seat.substitute; + if (agreed !== undefined && isFreeCandidate(pool, seatModelOf(agreed))) + return { selection: agreed, substituteFor } satisfies StandIn; + yield* recordSkip( + seat.seat, + free === null + ? none + : `${limited} ${ + policy === "ask" + ? "" + : "Its model was chosen by hand, so it is not swapped without asking. " + }${modelName(facts, free)} is free: swap to it from the notice to use it from the next message.`, + ); + return undefined; + } + if (free === null) { + yield* recordSkip(seat.seat, none); + return undefined; + } + return { + selection: createModelSelection(free.instanceId, free.model), + substituteFor, + } satisfies StandIn; + }); const mode = lineup.critique ?? "first"; const critiqueWanted = mode === "always" || (mode === "first" && !followUp); const stage = done(initial) ? "critique" : "contribution"; @@ -261,13 +401,20 @@ export const make = Effect.gen(function* () { roster.length - skipped.size >= 2 && !(done(initial) && (done(critiques) || !critiqueWanted)) ) { + const facts = + Option.isSome(limitedSeatsOption) && !isServerOwnedThreadLineage(parent.thread.lineage) + ? yield* limitedSeatsOption.value.facts(input.threadId) + : undefined; const available = yield* Effect.forEach( candidates, Effect.fn("NativeTeamChat.preflight")(function* (seat) { - const instance = yield* instances.getInstance(seat.modelSelection.instanceId); + const runsOn = facts === undefined ? undefined : yield* standIn(seat, facts); + if (facts !== undefined && runsOn === undefined) return undefined; + const selection = runsOn?.selection ?? seat.modelSelection; + const instance = yield* instances.getInstance(selection.instanceId); const enabled = yield* threads.isProviderInstanceEnabledForProject({ projectId: parent.thread.projectId, - instanceId: seat.modelSelection.instanceId, + instanceId: selection.instanceId, }); let reason: string | undefined; if (instance === undefined) reason = "provider is unavailable"; @@ -297,13 +444,28 @@ export const make = Effect.gen(function* () { ); return undefined; } - const adapter = yield* adapters.get(seat.modelSelection.instanceId).pipe( + const adapter = yield* adapters.get(selection.instanceId).pipe( Effect.catchTags({ ProviderAdapterRegistryLookupError: () => Effect.undefined, }), ); - if (adapter === undefined) + if (adapter === undefined) { yield* recordSkip(seat.seat, `${seat.seat}: provider is unavailable.`); + return undefined; + } + if (facts !== undefined && runsOn?.substituteFor !== undefined) { + const { resetAt } = runsOn.substituteFor; + yield* recordSkip( + seat.seat, + `${seat.seat} runs on ${modelName(facts, seatModelOf(selection))} this turn: ${modelName(facts, runsOn.substituteFor)} has reached its usage limit${resetAt ? ` until ${formatLimitReset(resetAt)}` : ""}.`, + ids.derive.runSignalTurnItem({ + runId: input.runId, + signal: `team-seat-substitute:${stage}:${seat.seat}`, + }), + true, + ); + standIns.set(seat.seat, runsOn); + } return adapter; }), ); @@ -378,8 +540,8 @@ export const make = Effect.gen(function* () { members: eligible.map((seat) => ({ seat: seat.seat, role: seat.role, - providerInstanceId: seat.modelSelection.instanceId, - model: seat.modelSelection.model, + providerInstanceId: runsOn(seat).instanceId, + model: runsOn(seat).model, access: deliveryParticipantAccess(lineup, seat.seat), })), skipped: roster.flatMap((seat) => { @@ -416,7 +578,14 @@ export const make = Effect.gen(function* () { parentThreadId: input.threadId, parentRunId: input.runId, parentNodeId: run.rootNodeId, - teamChat: { sourceRunId: input.runId, stage, seat: seat.seat }, + teamChat: { + sourceRunId: input.runId, + stage, + seat: seat.seat, + ...(standIns.get(seat.seat)?.substituteFor === undefined + ? {} + : { substituteFor: standIns.get(seat.seat)!.substituteFor! }), + }, title: `${seat.seat} · ${stage}`, task: `Participate as ${seat.role}, seat ${seat.seat}, in ${group}. ${ readOnly @@ -427,7 +596,7 @@ export const make = Effect.gen(function* () { ? "Give your independent assessment of the latest user message, with evidence, assumptions, and objections." : "Critique the independent contributions below. Identify errors, disagreements, overlooked alternatives, and evidence that changes your conclusion. Do not merely repeat the other participants." }\n\nConversation:\n${conversation}${attached}${stage === "critique" ? `\n\nIndependent contributions:\n${contributions(initial)}` : ""}`, - modelSelection: seat.modelSelection, + modelSelection: standIns.get(seat.seat)?.selection ?? seat.modelSelection, runtimeMode: access, // No seat gets plan mode: a harness in it writes a plan and asks for its approval, // which a read-only seat is refused, and then asks the person what to revise. A diff --git a/apps/server/src/observability/RpcInstrumentation.ts b/apps/server/src/observability/RpcInstrumentation.ts index 113a06cd20e82..11afab149951c 100644 --- a/apps/server/src/observability/RpcInstrumentation.ts +++ b/apps/server/src/observability/RpcInstrumentation.ts @@ -19,6 +19,8 @@ const RPC_AGGREGATES = { [WS_METHODS.deliveryArchivedBoardThreads]: "delivery", [WS_METHODS.deliveryReleaseThread]: "delivery", [WS_METHODS.deliverySetThreadLineup]: "delivery", + [WS_METHODS.deliveryLimitedSeats]: "delivery", + [WS_METHODS.deliverySwapLimitedSeat]: "delivery", [WS_METHODS.serverSubscribeCheckoutUpdate]: "server", [WS_METHODS.serverCheckCheckoutUpdate]: "server", [WS_METHODS.serverStartCheckoutUpdate]: "server", diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 9ca90a5d8f18b..b5fd9a455898f 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -84,6 +84,7 @@ import { managedRuntimeModeCeilingMessage, } from "@t3tools/contracts"; import * as KeyedLock from "@t3tools/shared/KeyedLock"; +import { limitedLeadHandoffThreadId } from "@t3tools/shared/limitedSeat"; import { modelSelectionsEqual } from "@t3tools/shared/model"; import { expandAssistantCitationsForProvider } from "@t3tools/shared/assistantCitations"; import { modelSwitchSince } from "./modelSwitch.ts"; @@ -314,6 +315,20 @@ export class OrchestratorThreadArchivedError extends Schema.TaggedError()( + "OrchestratorThreadHandedOnError", + { commandId: CommandId, threadId: ThreadId, continuedIn: ThreadId }, +) { + override get message(): string { + return handedOnThreadRefusal; + } +} + export class OrchestratorThreadAboveModeLimitError extends Schema.TaggedError()( "OrchestratorThreadAboveModeLimitError", { @@ -402,6 +417,7 @@ export const OrchestratorV2Error = Schema.Union([ OrchestratorCommandIdConflictError, OrchestratorSubagentThreadReadOnlyError, OrchestratorThreadArchivedError, + OrchestratorThreadHandedOnError, OrchestratorThreadAboveModeLimitError, OrchestratorProviderSelectionBusyError, OrchestratorRuntimeModeAboveCeilingError, @@ -848,6 +864,19 @@ function metadataUpdateContinuation( }; } +/** The server's own follow-up to a run, as against what a person, the CLI or a tool sends. */ +function isServerFollowUp( + command: Extract, +): boolean { + return ( + command.steerFollowUpOfRunId !== undefined || + command.usageLimitContinuationOfRunId !== undefined || + command.restartContinuationOfRunId !== undefined || + command.notification !== undefined || + command.idleCompaction !== undefined + ); +} + // A later command for the first message would leave the new thread committed with no run, // and every client would show it idle until that command landed. function threadCreateInitialMessage( @@ -1908,6 +1937,33 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio .findThread(threadId) .pipe(Effect.mapError((cause) => new OrchestratorProjectionError({ threadId, cause }))); + /** + * Whether a limited lead's run was handed on to a linked thread. Resuming it here as well would + * run the same work twice, so nothing arms or resumes it while that thread exists. + */ + const runHandedOn = (runId: RunId) => + findThread(limitedLeadHandoffThreadId(runId)).pipe( + Effect.map((continued) => continued !== null && continued.deletedAt === null), + ); + + /** + * The linked thread these runs' work continues in, when the latest executed one is a limited run + * that was handed on. Such a thread is read-only while that thread exists: a second run here + * would redo the work, so it takes no message and starts nothing from its queue. + */ + const handedOnTo = Effect.fnUntraced(function* (runs: ReadonlyArray) { + const latest = latestExecutedRun(runs); + if (latest?.status !== "failed" || !(yield* runHandedOn(latest.id))) return null; + return limitedLeadHandoffThreadId(latest.id); + }); + + /** + * `handedOnTo` for a delegated task's result, read from the run that spawned the task alone so a + * long parent costs nothing more. A task of an earlier run is caught where its wake would start. + */ + const spawningRunHandedOn = (run: OrchestrationV2Run) => + run.status === "failed" ? runHandedOn(run.id) : Effect.succeed(false); + /** Side chats live inside their parent, so deleting or archiving the parent takes them too. */ const liveSideChatIds = Effect.fn("Orchestrator.liveSideChatIds")( function* (threadId: ThreadId) { @@ -2099,6 +2155,8 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio controls.thread.deletedAt !== null ) return; + // A handed-on parent takes no result, as an archived one takes none. + if (yield* spawningRunHandedOn(parentRun)) return; const messages = yield* projectionStore.getThreadRecords(threadId, ["messages"], { messageIds: [delivery.messageId], }); @@ -2518,6 +2576,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ) { return; } + // Every start of a queued run passes here: a resume, a mode change, recovery, a wake, a run's + // end. None starts one on a thread whose work continues in a linked thread. + if ((yield* handedOnTo(projection.runs)) !== null) return; if (yield* cancelStaleQuestionWakes(projection)) { projection = yield* readCommandProjection(threadId); @@ -4842,6 +4903,19 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: "The provider limit changed before recovery could be configured.", }); } + const previous = thread.limitRecovery; + const resumes = + command.limitRecovery.autoResume ?? + (previous?.runId === command.limitRecovery.runId && + previous.resetAt === command.limitRecovery.resetAt && + previous.autoResume); + if (resumes && (yield* runHandedOn(command.limitRecovery.runId))) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: handedOnThreadRefusal, + }); + } } let restoredUnsettledAt: DateTime.Utc | null | undefined; if (command.type === "thread.unsettle" && command.restoreUnsettledAt !== undefined) { @@ -7138,14 +7212,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio command: Extract, thread: Pick, ) { - if ( - thread.archivedAt !== null && - command.steerFollowUpOfRunId === undefined && - command.usageLimitContinuationOfRunId === undefined && - command.restartContinuationOfRunId === undefined && - command.notification === undefined && - command.idleCompaction === undefined - ) { + if (thread.archivedAt !== null && !isServerFollowUp(command)) { return yield* new OrchestratorThreadArchivedError({ commandId: command.commandId, threadId: command.threadId, @@ -7153,6 +7220,39 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } }); + /** + * A thread whose latest limited run continues in a linked thread is read-only while that thread + * exists: a second run here would redo the work. What a person, the CLI or a tool sends is + * refused; the server's own follow-ups and a delegated task's result settle quietly, starting + * nothing. + */ + const settleHandedOnThreadMessage = Effect.fnUntraced(function* ( + command: Extract, + projection: Pick, + events: Ref.Ref>, + ) { + const continuedIn = yield* handedOnTo(projection.runs); + if (continuedIn === null) return false; + if (!isServerFollowUp(command) && command.delegatedCompletion === undefined) { + return yield* new OrchestratorThreadHandedOnError({ + commandId: command.commandId, + threadId: command.threadId, + continuedIn, + }); + } + // The unchanged row gives the automatic delivery an accepted receipt, so it is not retried. + yield* emit( + events, + command, + )({ + type: "thread.metadata-updated", + threadId: command.threadId, + occurredAt: yield* DateTime.now, + payload: projection.thread, + }); + return true; + }); + const dispatchMessage = Effect.fn("Orchestrator.dispatchMessage")(function* ( command: Extract, events: Ref.Ref>, @@ -7180,6 +7280,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio } : undefined, ); + if (yield* settleHandedOnThreadMessage(command, projection, events)) return; if (command.steerFollowUpOfRunId !== undefined) { const source = projection.runs.find((run) => run.id === command.steerFollowUpOfRunId); if ( @@ -14783,7 +14884,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio input.parentRun === undefined || input.parentProjection.thread.archivedAt !== null || input.parentProjection.thread.deletedAt !== null || - (cohort !== undefined && cohort.disposition !== "open") + (cohort !== undefined && cohort.disposition !== "open") || + // A handed-on parent takes no result, as an archived one takes none. + (yield* spawningRunHandedOn(input.parentRun)) ) { return { task: { @@ -15974,6 +16077,14 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio cause: `Thread ${command.threadId} is not active.`, }); } + const continuedIn = yield* handedOnTo(projection.runs); + if (continuedIn !== null) { + return yield* new OrchestratorThreadHandedOnError({ + commandId: command.commandId, + threadId: command.threadId, + continuedIn, + }); + } const selectedRunId = command.type === "queued-run.start" ? command.runId : undefined; const selectedRun = selectedRunId === undefined @@ -17059,7 +17170,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio // A Stop that reached the run before its limit failure landed had nothing to disarm. const stopped = yield* stopReachedRun(command, input.threadId, input.limitRecovery.runId); yield* dispatchWithReceiptEffect( - stopped + stopped || (yield* runHandedOn(input.limitRecovery.runId)) ? { ...command, limitRecovery: { ...input.limitRecovery, autoResume: false, snooze: false }, diff --git a/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts b/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts index 292882d0f894b..79daa99ff9d87 100644 --- a/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts +++ b/apps/server/src/orchestration-v2/RemoteDelegatedTask.test.ts @@ -12,6 +12,7 @@ import { RunId, ThreadId, } from "@t3tools/contracts"; +import { limitedLeadHandoffThreadId } from "@t3tools/shared/limitedSeat"; import * as Context from "effect/Context"; import * as DateTime from "effect/DateTime"; import * as Effect from "effect/Effect"; @@ -420,4 +421,77 @@ it.layer(layerTest)("a delegated task in a linked environment", (it) => { assert.equal(offered[0]?.threadId, parent.threadId); }), ); + + it.effect("settles its result quietly on a parent whose work continues in a linked thread", () => + Effect.gen(function* () { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const sink = yield* EventSink.EventSinkV2; + const parent = yield* seedLiveParent("handed-on"); + yield* orchestrator.dispatch({ + type: "delegated_task.remote.request", + commandId: CommandId.make("command:remote-delegate:handed-on"), + parentThreadId: parent.threadId, + parentRunId: parent.runId, + parentNodeId: parent.rootNodeId, + task: "Run the suite there.", + driver: ProviderDriverKind.make("remote"), + modelSelection, + remoteChild, + completionWake: "always", + }); + // The parent's run fails on its limit and the work is handed on to a linked thread. + const now = yield* DateTime.now; + const before = yield* orchestrator.getThreadProjection(parent.threadId); + yield* sink.write({ + events: [ + { + id: EventId.make("event:handed-on:failed"), + type: "run.updated", + threadId: parent.threadId, + runId: parent.runId, + occurredAt: now, + payload: { ...before.runs[0]!, status: "failed", completedAt: now }, + }, + ], + }); + const continuedIn = limitedLeadHandoffThreadId(parent.runId); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "agent", + creationSource: "server", + commandId: CommandId.make("command:create:handed-on-continued"), + threadId: continuedIn, + projectId: ProjectId.make("project:remote-delegated-task"), + title: "Parent, continued", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + const offers = yield* Offers; + yield* Ref.set(offers, []); + const taskId = before.subagents[0]!.id; + // The result is recorded and disposed, as on an archived parent: no error, no wake, no run. + yield* orchestrator.dispatch({ + type: "delegated_task.remote.complete", + commandId: CommandId.make("command:remote-complete:handed-on"), + parentThreadId: parent.threadId, + taskId, + status: "completed", + result: "All 412 tests pass on the box.", + stoppedThere: "ran-out", + }); + const after = yield* orchestrator.getThreadProjection(parent.threadId); + const task = after.subagents.find((candidate) => candidate.id === taskId); + assert.equal(task?.result, "All 412 tests pass on the box."); + assert.equal(task?.completionDelivery?.state, "disposed"); + assert.deepEqual( + after.runs.map((run) => [run.id, run.status]), + [[parent.runId, "failed"]], + ); + assert.lengthOf(after.messages, before.messages.length); + assert.deepEqual(yield* Ref.get(offers), []); + }), + ); }); diff --git a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts index ae47dac361327..0df0ffdf89031 100644 --- a/apps/server/src/orchestration-v2/ThreadMessageIntake.ts +++ b/apps/server/src/orchestration-v2/ThreadMessageIntake.ts @@ -31,6 +31,7 @@ function dispatchWasNotAccepted( case "OrchestratorCommandIdConflictError": case "OrchestratorSubagentThreadReadOnlyError": case "OrchestratorThreadArchivedError": + case "OrchestratorThreadHandedOnError": case "OrchestratorThreadAboveModeLimitError": case "OrchestratorProviderSelectionBusyError": case "OrchestratorRuntimeModeAboveCeilingError": diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index 8e38f5204c970..fba6eac258d64 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -1,6 +1,7 @@ import { PullRequestProviderError } from "@t3tools/source-control-core/server/PullRequestProvider"; import { PullRequestUnavailableError, SourceControlProviderKind } from "@t3tools/contracts"; import { limitRecoveryCommand } from "./UsageLimitRecoveryWorker.ts"; +import { leadHandoffCommands, leadHandoffThreadId } from "../delivery/LimitedSeatSwap.ts"; import { createOrchestrationV2TurnItemVisibility } from "@t3tools/shared/orchestrationV2Timeline"; import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions"; import * as SourceControlProviderRegistry from "../sourceControl/SourceControlProviderRegistry.ts"; @@ -13352,7 +13353,254 @@ it.layer(layerSharedApplicationDataPlaneTest)("shared application data plane", ( ); }); +/** + * A thread whose first run failed on a usage limit that resets in a minute. `queueBehind` leaves a + * message queued behind that run, which the limit holds without writing a hold on it. + */ +const failLimitedLead = Effect.fn("failLimitedLead")(function* ( + name: string, + options?: { readonly queueBehind?: boolean }, +) { + const orchestrator = yield* Orchestrator.OrchestratorV2; + const events = yield* EventSink.EventSinkV2; + const threadId = ThreadId.make(name); + const projectId = ProjectId.make(`${name}:project`); + const now = yield* DateTime.now; + yield* seedProject({ + projectId, + title: "Hand-off project", + workspaceRoot: process.cwd(), + defaultModelSelection: modelSelection, + createdAt: DateTime.formatIso(now), + }); + yield* orchestrator.dispatch({ + type: "thread.create", + commandId: CommandId.make(`${name}:create`), + threadId, + projectId, + title: "Limited lead", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdBy: "user", + creationSource: "web", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${name}:start`), + threadId, + messageId: MessageId.make(`${name}:start`), + text: "Start work.", + attachments: [], + dispatchMode: { type: "defer_start" }, + createdBy: "user", + creationSource: "web", + }); + if (options?.queueBehind === true) { + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`${name}:queue`), + threadId, + messageId: MessageId.make(`${name}:queue`), + text: "Follow up.", + attachments: [], + dispatchMode: { type: "queue_after_active" }, + createdBy: "user", + creationSource: "web", + }); + } + const [source] = (yield* orchestrator.getThreadProjection(threadId)).runs as [ + OrchestrationV2Run, + ...Array, + ]; + const resetAt = DateTime.formatIso(DateTime.add(now, { minutes: 1 })); + yield* events.write({ + events: [ + { + id: EventId.make(`${name}:failed`), + type: "run.updated", + threadId, + occurredAt: now, + payload: { ...source, status: "failed", completedAt: now }, + }, + { + id: EventId.make(`${name}:error`), + type: "turn-item.updated", + threadId, + occurredAt: now, + payload: { + id: TurnItemId.make(`${name}:error`), + type: "error", + threadId, + runId: source.id, + nodeId: source.rootNodeId, + providerThreadId: null, + providerTurnId: null, + nativeItemRef: null, + parentItemId: null, + ordinal: 2, + status: "failed", + title: "Usage limit reached", + startedAt: now, + completedAt: now, + updatedAt: now, + failure: { + class: "usage_limit", + message: "Plan limit reached.", + code: "usageLimitExceeded", + retryable: null, + resetAt, + }, + }, + }, + ], + }); + const shellOf = Effect.map(orchestrator.getShellSnapshot(), (snapshot) => + snapshot.threads.find((thread) => thread.id === threadId)!, + ); + return { orchestrator, threadId, source, resetAt, now, shellOf }; +}); + it.layer(layerTest)("usage-limit recovery", (it) => { + it.effect("hands a limited lead on to a linked thread once, and stops its own resume", () => + Effect.gen(function* () { + const { orchestrator, threadId, source, resetAt, now, shellOf } = + yield* failLimitedLead("limited-lead"); + // Left alone, the recovery worker would arm this thread and resume it at the reset. + assert.isNotNull(limitRecoveryCommand(yield* shellOf, true, DateTime.toEpochMillis(now))); + + const substitute = { instanceId: alternateInstanceId, model: "gpt-5.4" }; + const handOff = leadHandoffCommands({ + threadId, + title: "Limited lead", + runId: source.id, + resetAt, + substitute, + }); + // The notice's button pressed twice: every command is sent again. + for (const command of [...handOff, ...handOff]) yield* orchestrator.dispatch(command); + + const target = leadHandoffThreadId(source.id); + const continued = yield* orchestrator.getThreadProjection(target); + assert.deepInclude(continued.thread.lineage, { + parentThreadId: threadId, + relationshipToParent: "fork", + }); + assert.deepEqual(continued.thread.forkedFrom, { type: "run", threadId, runId: source.id }); + assert.lengthOf(continued.runs, 1); + assert.equal(continued.runs[0]?.providerInstanceId, alternateInstanceId); + + const old = yield* shellOf; + assert.deepInclude(old.limitRecovery, { runId: source.id, autoResume: false }); + assert.isNull(limitRecoveryCommand(old, true, Date.parse(resetAt))); + assert.lengthOf((yield* orchestrator.getThreadProjection(threadId)).runs, 1); + + // "Resume at reset" pressed on the old thread: refused, and the recovery stays disarmed. + const rearm = yield* Effect.flip( + orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("limited-lead:rearm"), + threadId, + limitRecovery: { runId: source.id, resetAt, autoResume: true }, + }), + ); + assert.include(String(rearm.cause), "continues in a linked thread"); + assert.deepInclude((yield* shellOf).limitRecovery, { autoResume: false }); + // Snoozing the old thread until its reset resumes nothing, so it stays allowed. + yield* orchestrator.dispatch({ + type: "thread.metadata.update", + commandId: CommandId.make("limited-lead:snooze"), + threadId, + limitRecovery: { runId: source.id, resetAt, snooze: true }, + }); + assert.deepInclude((yield* shellOf).limitRecovery, { autoResume: false, snooze: true }); + // A resume that still reaches the old thread starts no run there. + yield* orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make("limited-lead:resume"), + messageId: MessageId.make("limited-lead:resume"), + threadId, + usageLimitContinuationOfRunId: source.id, + text: "Continue where you left off.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + createdBy: "agent", + creationSource: "server", + }); + assert.lengthOf((yield* orchestrator.getThreadProjection(threadId)).runs, 1); + + // The composer's "Resume thread", a typed message, and the send the CLI and tools make. + const send = (name: string, extra: { readonly manualContinuationOfRunId?: RunId } = {}) => + orchestrator.dispatch({ + type: "message.dispatch", + commandId: CommandId.make(`limited-lead:${name}`), + messageId: MessageId.make(`limited-lead:${name}`), + threadId, + ...extra, + text: "Continue where you left off.", + attachments: [], + dispatchMode: { type: "start_immediately" }, + ...(name === "cli" + ? { deliveryIntent: "auto" as const, createdBy: "agent", creationSource: "mcp" } + : { createdBy: "user", creationSource: "web" }), + }); + for (const refusedSend of [ + send("manual-resume", { manualContinuationOfRunId: source.id }), + send("typed"), + send("cli"), + ]) { + const refused = yield* Effect.flip(refusedSend); + assert.equal(refused._tag, "OrchestratorThreadHandedOnError"); + assert.equal( + refused.message, + "This conversation continues in a linked thread. Open that thread instead of resuming this one.", + ); + } + const kept = yield* orchestrator.getThreadProjection(threadId); + assert.deepEqual( + kept.runs.map((run) => run.id), + [source.id], + ); + assert.lengthOf(kept.messages, 1); + + // Deleting the linked thread reopens this one. + yield* orchestrator.dispatch({ + type: "thread.delete", + commandId: CommandId.make("limited-lead:delete-continued"), + threadId: target, + }); + yield* send("reopened"); + assert.lengthOf((yield* orchestrator.getThreadProjection(threadId)).runs, 2); + }), + ); + + it.effect("records the worker's arming of a handed-on run as disarmed", () => + Effect.gen(function* () { + const { orchestrator, threadId, source, resetAt, shellOf } = + yield* failLimitedLead("limited-lead-armed"); + // Handed on with nothing to disarm, as when no recovery was on record yet. + for (const command of leadHandoffCommands({ + threadId, + title: "Limited lead", + runId: source.id, + resetAt: null, + substitute: { instanceId: alternateInstanceId, model: "gpt-5.4" }, + })) + yield* orchestrator.dispatch(command); + assert.isUndefined((yield* shellOf).limitRecovery?.autoResume); + yield* orchestrator.autoArmLimitRecovery({ + commandId: CommandId.make("limited-lead-armed:auto-arm"), + threadId, + limitRecovery: { runId: source.id, resetAt, autoResume: true }, + }); + const old = yield* shellOf; + assert.deepInclude(old.limitRecovery, { runId: source.id, autoResume: false }); + assert.isNull(limitRecoveryCommand(old, true, Date.parse(resetAt))); + }), + ); + it.effect.each(["interrupted", "usage_limit"] as const)( "manually resumes an %s run ahead of its queued message only once", (reason) => @@ -14229,6 +14477,130 @@ it.layer(layerTest)("usage-limit recovery", (it) => { ); }); +// The orchestrator starts a thread's queue on a runtime mode change only under a managed ceiling. +const layerRuntimeModeCeilingTest = Layer.mergeAll( + RuntimeLayer.layer, + RuntimeLayer.layerEventSink, + ProjectStore.layer, + ProjectionStore.layer, + EffectOutbox.layer, + ThreadCommandExecutor.layer, +).pipe( + Layer.provide(McpSessionRegistryTestkit.layer), + Layer.provide(McpProviderSessions.layer), + Layer.provide(SqlitePersistence.layerMemory), + Layer.provide(layerCheckpointStoreTest), + Layer.provide(layerServerConfig), + Layer.provide( + ServerSettings.layerTest( + {}, + { + organization: "Example Corp", + lockedSettings: [], + limits: { maxRuntimeMode: "full-access" }, + }, + ), + ), + Layer.provide(layerTestProviderInstanceRegistry), + Layer.provide(layerGitWorkflowTest), + Layer.provide(layerProjectServiceTest), + Layer.provide(layerPlatformTest), +); + +it.layer(layerRuntimeModeCeilingTest)("the queue of a handed-on thread", (it) => { + it.effect("starts no queued run while the work continues in a linked thread", () => + Effect.gen(function* () { + const { orchestrator, threadId, source, resetAt } = yield* failLimitedLead( + "limited-lead-queue", + { queueBehind: true }, + ); + const runsOf = Effect.map(orchestrator.getThreadProjection(threadId), ({ runs }) => + runs.map((run) => [run.id, run.status]), + ); + const queued = (yield* orchestrator.getThreadProjection(threadId)).runs.find( + (run) => run.status === "queued", + )!; + assert.notEqual(queued.queueHeld, true); + for (const command of leadHandoffCommands({ + threadId, + title: "Limited lead", + runId: source.id, + resetAt, + substitute: { instanceId: alternateInstanceId, model: "gpt-5.4" }, + })) + yield* orchestrator.dispatch(command); + // The queued message is for a provider with no limit, so the limit does not hold it: only + // the hand-off stands between it and a second run here. + const events = yield* EventSink.EventSinkV2; + const substitute = { instanceId: alternateInstanceId, model: "gpt-5.4" }; + yield* events.write({ + events: [ + { + id: EventId.make("limited-lead-queue:other-provider"), + type: "run.updated", + threadId, + occurredAt: yield* DateTime.now, + payload: { + ...queued, + modelSelection: substitute, + providerInstanceId: alternateInstanceId, + }, + }, + ], + }); + + // The CLI's, a tool's or another client's resume learns why nothing starts. + for (const resume of [ + orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make("limited-lead-queue:resume"), + threadId, + }), + orchestrator.dispatch({ + type: "queued-run.start", + commandId: CommandId.make("limited-lead-queue:start-queued"), + threadId, + runId: queued.id, + }), + ]) { + const refused = yield* Effect.flip(resume); + assert.equal(refused._tag, "OrchestratorThreadHandedOnError"); + assert.equal( + refused.message, + "This conversation continues in a linked thread. Open that thread instead of resuming this one.", + ); + } + // What starts a queue with no one asking settles quietly: a mode change, and recovery. + yield* orchestrator.dispatch({ + type: "thread.runtime-mode.set", + commandId: CommandId.make("limited-lead-queue:mode"), + threadId, + runtimeMode: "approval-required", + }); + yield* orchestrator.resumeQueuedRuns; + assert.deepEqual(yield* runsOf, [ + [source.id, "failed"], + [queued.id, "queued"], + ]); + + // Deleting the linked thread gives the queue back. + yield* orchestrator.dispatch({ + type: "thread.delete", + commandId: CommandId.make("limited-lead-queue:delete-continued"), + threadId: leadHandoffThreadId(source.id), + }); + yield* orchestrator.dispatch({ + type: "queue.resume", + commandId: CommandId.make("limited-lead-queue:resume-reopened"), + threadId, + }); + const reopened = yield* runsOf; + assert.lengthOf(reopened, 2); + assert.notEqual(reopened[1]?.[1], "queued"); + }), + ); +}); + const queueResumeDisabledInstanceProjectId = ProjectId.make( "project:queue-resume-disabled-instance", ); diff --git a/apps/server/src/orchestration-v2/runtimeLayer.ts b/apps/server/src/orchestration-v2/runtimeLayer.ts index cc827f618fd4c..832b52d39016a 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.ts @@ -1,6 +1,8 @@ import * as SendFailureNotice from "./SendFailureNotice.ts"; import * as WorktreeBranchSync from "./WorktreeBranchSync.ts"; import * as GuestShareService from "../guest/GuestShareService.ts"; +import * as LimitedSeats from "../delivery/LimitedSeats.ts"; +import * as LimitedSeatSwap from "../delivery/LimitedSeatSwap.ts"; import * as NativeTeamChat from "../delivery/NativeTeamChat.ts"; import * as UsageLimitRecoveryWorker from "./UsageLimitRecoveryWorker.ts"; import * as Scheduler from "../scheduling/Scheduler.ts"; @@ -276,6 +278,17 @@ const layerThreadManagementProvided = ThreadManagementService.layerWithLegacyImp ), ), ); +const layerLimitedSeatsProvided = LimitedSeats.layer.pipe(Layer.provide(ProjectionStore.layer)); +const layerLimitedSeatSwapProvided = LimitedSeatSwap.layer.pipe( + Layer.provide( + Layer.mergeAll( + layerLimitedSeatsProvided, + layerThreadManagementProvided, + ProjectionStore.layer, + ProviderAdapterRegistry.layerFromProviderInstanceRegistry, + ), + ), +); const layerNativeTeamChatProvided = NativeTeamChat.layer.pipe( Layer.provide( Layer.mergeAll( @@ -285,6 +298,7 @@ const layerNativeTeamChatProvided = NativeTeamChat.layer.pipe( ProjectStore.layer, IdAllocator.layer, ProviderAdapterRegistry.layerFromProviderInstanceRegistry, + layerLimitedSeatsProvided, ), ), ); @@ -448,6 +462,10 @@ export const layerProduction = Layer.mergeAll( ), ), ), + layerLimitedSeatSwapProvided, + LimitedSeatSwap.layerWorker.pipe( + Layer.provide(Layer.merge(layerLimitedSeatSwapProvided, layerOrchestratorProvided)), + ), layerProviderContinuationWorkerProvided, layerAgentSessionScannerProvided, layerAgentSessionImporterProvided, diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index b8124c081a5b7..eadf79a0d6b84 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -259,6 +259,7 @@ import { commandFeatureUsage, featureUsage } from "./telemetry/FeatureUsage.ts"; import type { TelemetryOwner } from "./telemetry/Identify.ts"; import * as UsageService from "./usage/UsageService.ts"; import * as DeliveryService from "./delivery/DeliveryService.ts"; +import * as LimitedSeatSwap from "./delivery/LimitedSeatSwap.ts"; import * as TraceDiagnostics from "./diagnostics/TraceDiagnostics.ts"; import * as TriageService from "./triage/TriageService.ts"; import * as PullRequestService from "./pullRequest/PullRequestService.ts"; @@ -3717,6 +3718,7 @@ const layerForkWsRpc = (currentSession: EnvironmentAuth.AuthenticatedSession) => Effect.gen(function* () { const checkoutUpdate = yield* CheckoutUpdate.CheckoutUpdate; const delivery = yield* DeliveryService.DeliveryService; + const limitedSeatSwap = yield* Effect.serviceOption(LimitedSeatSwap.LimitedSeatSwap); const sql = yield* SqlClient.SqlClient; const serverEnvironment = yield* ServerEnvironment.ServerEnvironment; return ForkServerWsRpcGroup.of({ @@ -3751,6 +3753,19 @@ const layerForkWsRpc = (currentSession: EnvironmentAuth.AuthenticatedSession) => ), [WS_METHODS.deliveryReleaseThread]: (input) => delivery.releaseThread(input.threadId), [WS_METHODS.deliverySetThreadLineup]: (input) => delivery.setThreadLineup(input), + [WS_METHODS.deliveryLimitedSeats]: (input) => + Option.match(limitedSeatSwap, { + onNone: () => Effect.succeed({ policy: null, notices: [] }), + onSome: (swaps) => swaps.status(input.threadId), + }), + [WS_METHODS.deliverySwapLimitedSeat]: (input) => + Option.match(limitedSeatSwap, { + onNone: () => + Effect.fail( + new DeliveryError({ reason: "disabled", detail: "Delivery is turned off." }), + ), + onSome: (swaps) => swaps.swap(input), + }), }); }), ); diff --git a/apps/web/src/components/ChatView.handedOnSend.browser.test.tsx b/apps/web/src/components/ChatView.handedOnSend.browser.test.tsx new file mode 100644 index 0000000000000..5a562ace2af30 --- /dev/null +++ b/apps/web/src/components/ChatView.handedOnSend.browser.test.tsx @@ -0,0 +1,95 @@ +import { createMemoryHistory } from "@tanstack/react-router"; +import { DEFAULT_CLIENT_SETTINGS } from "@t3tools/contracts/settings"; +import { limitedLeadHandoffThreadId } from "@t3tools/shared/limitedSeat"; +import type * as Context from "effect/Context"; +import { expect, it, vi } from "vite-plus/test"; +import { page, userEvent } from "vite-plus/test/browser"; + +import { AppRoot } from "~/AppRoot"; +// The route loads ChatView lazily; importing it here keeps its first transform out of the test. +import "~/components/ChatView"; +import { __setClientSettingsForTests } from "~/hooks/useSettings"; +import { getRouter } from "~/router"; +import { + ENVIRONMENT_ID, + dispatchedCommands, + installFakeEnvironment, + threadWithHistory, + type FakeDriver, + type FakeThread, +} from "../../test/fakeEnvironment"; +import { render } from "../../test/render"; + +// The socket is the only fake layer; see test/appScenarios.renders.tsx. +vi.mock("../../../../packages/client-runtime/src/connection/driver.ts", async (importOriginal) => { + const [actual, { fakeDriver }, Layer] = await Promise.all([ + importOriginal<{ readonly ConnectionDriver: Context.Key }>(), + import("../../test/fakeEnvironment"), + import("effect/Layer"), + ]); + return { ...actual, layer: Layer.succeed(actual.ConnectionDriver, fakeDriver) }; +}); + +vi.mock(import("~/rpc/requestLatencyState"), async (original) => ({ + ...(await original()), + trackRpcRequestSent: () => {}, +})); + +const NOTICE = "This conversation continues in a linked thread"; +const sends = () => dispatchedCommands().filter((command) => command.type === "message.dispatch"); + +/** A thread whose only run stopped short, so its composer would offer "Resume thread". */ +function stoppedThread(name: string): FakeThread { + const history = threadWithHistory(name, 1); + return { ...history, runs: [{ ...history.runs[0]!, status: "interrupted" }] }; +} + +async function open(thread: FakeThread) { + __setClientSettingsForTests({ + ...DEFAULT_CLIENT_SETTINGS, + onboardingCompletedAt: "2026-01-01T00:00:00.000Z", + }); + const router = getRouter( + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }), + ); + await router.load(); + // AppRoot brings its own router. + const app = await render(, { router: false }); + await expect.element(page.getByText(`${thread.id}: question 0`)).toBeVisible(); + return app; +} + +it("a thread handed on to a linked thread offers no resume and sends nothing", async () => { + const old = stoppedThread("handed-on"); + const continued = threadWithHistory(limitedLeadHandoffThreadId(old.runs[0]!.id), 1); + using _environment = installFakeEnvironment([old, continued], { acceptCommands: true }); + await using _app = await open(old); + + await expect.element(page.getByText(NOTICE)).toBeVisible(); + // With an empty draft the send must not turn into the resume. + expect(page.getByRole("button", { name: "Resume thread" }).query()).toBeNull(); + const editor = page.getByTestId("composer-editor"); + await userEvent.click(editor); + await userEvent.keyboard("{Enter}"); + await userEvent.keyboard("still there?"); + await vi.waitFor(() => expect(editor.element().textContent).toContain("still there?")); + await expect.element(page.getByRole("button", { name: NOTICE })).toBeDisabled(); + await userEvent.keyboard("{Enter}"); + expect(editor.element().textContent).toContain("still there?"); + expect(sends()).toEqual([]); + + await userEvent.click(page.getByRole("button", { name: "Open thread" })); + await expect.element(page.getByText(`${continued.id}: question 0`)).toBeVisible(); +}); + +it("a stopped thread that was not handed on still resumes and sends", async () => { + const thread = stoppedThread("not-handed-on"); + using _environment = installFakeEnvironment([thread], { acceptCommands: true }); + await using _app = await open(thread); + + expect(page.getByText(NOTICE).query()).toBeNull(); + await expect.element(page.getByRole("button", { name: "Resume thread" })).toBeVisible(); + await userEvent.click(page.getByTestId("composer-editor")); + await userEvent.keyboard("still there?{Enter}"); + await vi.waitFor(() => expect(sends()).toHaveLength(1)); +}); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 8b1fe2f99dbc2..30a52ba753d35 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -67,6 +67,7 @@ import { ThreadFind, ThreadFindCanvas } from "./chat/ThreadFindProvider"; import { closeThreadFind, openThreadFind, useThreadFindOpen } from "./chat/threadFindStore"; import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar"; import { useUsageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner"; +import { useLimitedSeatBannerItems } from "./chat/LimitedSeatNotices"; import { isThreadEnvironmentLocked, resolveDraftHeroState, @@ -81,6 +82,7 @@ import { RightPanelSurfaceContent } from "./chat/RightPanelSurfaceContent"; import { usePendingThreadRequests } from "./chat/usePendingThreadRequests"; import { isScratchProject } from "@t3tools/client-runtime/state/projects"; import { resolveWorktreeRepositorySelection } from "@t3tools/client-runtime/state/thread-repositories"; +import { limitedLeadHandoffThreadId } from "@t3tools/shared/limitedSeat"; import { visibleThreadPullRequests } from "@t3tools/shared/threadPullRequests"; import type { UsageLimitSourceSnapshots } from "@t3tools/contracts"; import { feedbackBannerItem } from "./chat/ComposerFeedback"; @@ -88,6 +90,10 @@ import { archivedThreadBannerItem, archivedThreadSendBlockReason, } from "./chat/ComposerArchivedThread"; +import { + handedOnThreadBannerItem, + handedOnThreadSendBlockReason, +} from "./chat/ComposerHandedOnThread"; import { freshSessionBannerItem } from "./chat/ComposerFreshSession"; import { armFreshSession, disarmFreshSession, useFreshSessionArmed } from "./chat/freshSessionArms"; import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel"; @@ -191,7 +197,7 @@ import { squashAtomCommandFailure, type AtomCommandResult, } from "@t3tools/client-runtime/state/runtime"; -import { AsyncResult } from "effect/reactivity"; +import { AsyncResult, Atom } from "effect/reactivity"; import { isElectron } from "../env"; import { useActiveThreadRef } from "../hooks/useActiveThreadRef"; import { composerRequiresModifier } from "../composer-logic"; @@ -449,6 +455,7 @@ import { } from "./ChatView.logic"; const EMPTY_PROVIDERS: ServerProvider[] = []; +const NOT_HANDED_ON_ATOM = Atom.make(false); const EMPTY_PROVIDER_MODELS: ServerProvider["models"] = []; const EMPTY_USAGE_LIMIT_SOURCES: UsageLimitSourceSnapshots = []; import type { CodexArtifactTemplate } from "@t3tools/shared/codexArtifactTemplates"; @@ -920,7 +927,16 @@ export default function ChatView(props: ChatViewProps) { !isServerThread || serverProjection === null ? null : deriveResumableRunId(serverProjection, serverRuntime); + // A thread whose limited run continues in a linked thread opens to read. The server refuses + // every message to it, so the composer offers no resume and no send. + const threadHandedOn = useAtomValue( + serverThread === null + ? NOT_HANDED_ON_ATOM + : deliveryEnvironment.limitedLeadHandedOn(scopeThreadRef(environmentId, serverThread.id)), + ); + const handedOnRunId = threadHandedOn ? (serverThread?.latestRun?.runId ?? null) : null; const canResume = + !threadHandedOn && serverProjection !== null && canResumeThread(serverProjection, resumableRunId, hasHeldQueuedRuns); const parentSubagentThreadId = @@ -2881,6 +2897,7 @@ export default function ChatView(props: ChatViewProps) { stoppedAt: limitRecoveryRun.completedAt ?? activeThreadShell.updatedAt, settled: activeThreadShell.settledOverride === "settled", requestPending: pendingApprovals.length > 0 || pendingUserInputs.length > 0, + handedOn: threadHandedOn, recovery: activeThreadShell.limitRecovery ?? null, snoozedUntil: activeThreadShell.snoozedUntil, timestampFormat, @@ -2895,11 +2912,40 @@ export default function ChatView(props: ChatViewProps) { : null, messages, ); + const limitedSeatBannerItems = useLimitedSeatBannerItems( + { + environmentId, + threadId: deliveryEnabled && activeThreadShell !== null ? activeThreadShell.id : null, + providers: providerStatuses, + timestampFormat, + onOpenThread: (next) => + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams(scopeThreadRef(environmentId, next)), + }), + }, + messages, + ); // An archived thread opens to read. The server refuses every message to it, so the composer says // so before one is written, not after a send that goes nowhere. const threadArchived = serverThread !== null && serverThread.archivedAt !== null; const composerBannerItems = (() => { - const archivedItems = threadArchived ? [archivedThreadBannerItem(messages)] : []; + const archivedItems = threadArchived + ? [archivedThreadBannerItem(messages)] + : handedOnRunId !== null + ? [ + handedOnThreadBannerItem( + () => + void navigate({ + to: "/$environmentId/$threadId", + params: buildThreadRouteParams( + scopeThreadRef(environmentId, limitedLeadHandoffThreadId(handedOnRunId)), + ), + }), + messages, + ), + ] + : []; const fallbackSelection = draftFallback?.selection; const defaultSelection = draftDefaultModelSelection ?? @@ -2948,7 +2994,10 @@ export default function ChatView(props: ChatViewProps) { ), ] : []; - const limitRecoveryItems = limitRecoveryBanner === null ? [] : [limitRecoveryBanner]; + const limitRecoveryItems = + limitRecoveryBanner === null + ? limitedSeatBannerItems + : [limitRecoveryBanner, ...limitedSeatBannerItems]; const extensionStatusBanner = extensionStatusBannerItem( deriveProviderExtensionStatuses(serverProjection), ); @@ -4099,17 +4148,19 @@ export default function ChatView(props: ChatViewProps) { ? gt("This connection cannot change threads.") : threadArchived ? archivedThreadSendBlockReason(messages) - : isEnvironmentChanging - ? gt("Preparing machine") - : isRevertingCheckpoint - ? gt("Rewinding conversation") - : feedbackUploading - ? gt("Sending feedback") - : threadDetailLoading - ? gt("Messages loading") - : worktreeSetupBlocksSend - ? gt("Preparing worktree") - : projectCloneSendBlockReason + : threadHandedOn + ? handedOnThreadSendBlockReason(messages) + : isEnvironmentChanging + ? gt("Preparing machine") + : isRevertingCheckpoint + ? gt("Rewinding conversation") + : feedbackUploading + ? gt("Sending feedback") + : threadDetailLoading + ? gt("Messages loading") + : worktreeSetupBlocksSend + ? gt("Preparing worktree") + : projectCloneSendBlockReason } isPreparingWorktree={isPreparingWorktree && !sendQueuesBehindSetup} bannerItems={ diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index be7b073fc2c50..662836edf2b9a 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -63,6 +63,7 @@ import { EnvironmentRequestInvalidError, AuthOrchestrationOperateScope, clampManagedRuntimeMode, + isServerOwnedThreadLineage, ProviderDriverKind, ProviderInstanceId, PROVIDER_SEND_TURN_MAX_ATTACHMENTS, @@ -2750,6 +2751,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) entries={providerInstanceEntries} models={modelOptionsByInstance} onFocusChat={startSingleChatForSeat} + boardOwned={ + activeThread !== undefined && isServerOwnedThreadLineage(activeThread.lineage) + } onLeaveToSingle={() => void switchStartedThreadToSingle()} /> ), diff --git a/apps/web/src/components/chat/ComposerHandedOnThread.tsx b/apps/web/src/components/chat/ComposerHandedOnThread.tsx new file mode 100644 index 0000000000000..9d6afc4f28a23 --- /dev/null +++ b/apps/web/src/components/chat/ComposerHandedOnThread.tsx @@ -0,0 +1,30 @@ +import { msg } from "gt-react"; +import { GitForkIcon } from "lucide-react"; + +import { m, type MessageResolver } from "../../i18n/messages"; +import { Button } from "../ui/button"; + +import type { ComposerBannerStackItem } from "./ComposerBannerStack"; + +/** Why a handed-on thread's composer sends nothing: the server refuses every message to it. */ +export function handedOnThreadSendBlockReason(resolve: MessageResolver = m) { + return resolve(msg("This conversation continues in a linked thread")); +} + +/** Shown above the composer of a thread whose limited run continues in a linked thread. */ +export function handedOnThreadBannerItem( + onOpenThread: () => void, + resolve: MessageResolver = m, +): ComposerBannerStackItem { + return { + id: "handed-on-thread", + variant: "info", + icon: , + title: handedOnThreadSendBlockReason(resolve), + actions: ( + + ), + }; +} diff --git a/apps/web/src/components/chat/LimitedSeatNotices.browser.test.tsx b/apps/web/src/components/chat/LimitedSeatNotices.browser.test.tsx new file mode 100644 index 0000000000000..36e661486da8b --- /dev/null +++ b/apps/web/src/components/chat/LimitedSeatNotices.browser.test.tsx @@ -0,0 +1,124 @@ +import { + type DeliveryLimitedSeatStatus, + EnvironmentId, + ProviderInstanceId, + ThreadId, +} from "@t3tools/contracts"; +import { createModelSelection } from "@t3tools/shared/model"; +import { expect, it, vi } from "vite-plus/test"; +import { page } from "vite-plus/test/browser"; + +import "~/index.css"; + +import { render } from "../../../test/render"; +import { ComposerBannerStack } from "./ComposerBannerStack"; +import { useLimitedSeatBannerItems } from "./LimitedSeatNotices"; + +const testState = vi.hoisted(() => ({ + status: null as unknown, + release: null as (() => void) | null, + swap: vi.fn(), +})); + +vi.mock("../../state/query", () => ({ + useEnvironmentQuery: () => ({ data: testState.status, error: null, refresh: () => {} }), +})); +vi.mock("../../state/use-atom-command", () => ({ useAtomCommand: () => testState.swap })); +vi.mock("../../state/session", async (importOriginal) => ({ + ...(await importOriginal()), + useEnvironmentScope: () => true, +})); + +const environmentId = EnvironmentId.make("env-a"); +const threadId = ThreadId.make("lead-thread"); +const limited = { + instanceId: ProviderInstanceId.make("claude"), + model: "claude-fable", + resetAt: null, +}; +const kimi = createModelSelection(ProviderInstanceId.make("kimi"), "kimi-k3"); + +function setup(status: DeliveryLimitedSeatStatus) { + testState.status = status; + testState.release = null; + testState.swap.mockReset(); + // The server takes a moment, as a fork does; the test decides when it answers. + testState.swap.mockImplementation( + () => + new Promise((resolve) => { + testState.release = () => + resolve({ _tag: "Success", value: { continuedIn: ThreadId.make("continued") } }); + }), + ); +} + +function Notices(props: { readonly onOpenThread: (threadId: ThreadId) => void }) { + const items = useLimitedSeatBannerItems({ + environmentId, + threadId, + providers: [], + timestampFormat: "locale", + onOpenThread: props.onOpenThread, + }); + return ; +} + +it("names the free favorite and swaps to it in one click, however often it is pressed", async () => { + setup({ + policy: "ask", + notices: [{ seat: null, limited, state: "offered", substitute: kimi }], + }); + const onOpenThread = vi.fn(); + await using _screen = await render(); + + await expect.element(page.getByText("claude-fable has reached its usage limit")).toBeVisible(); + const swap = page.getByRole("button", { name: "Swap to kimi-k3" }); + await swap.click(); + // The button is off while the swap runs, so a second press sends nothing. + await expect.element(swap).toBeDisabled(); + await swap.click({ force: true }); + expect(testState.swap).toHaveBeenCalledTimes(1); + expect(testState.swap).toHaveBeenCalledWith({ + environmentId, + input: { threadId, seat: null, modelSelection: kimi }, + }); + + testState.release?.(); + await vi.waitFor(() => expect(onOpenThread).toHaveBeenCalledWith("continued")); + expect(onOpenThread).toHaveBeenCalledTimes(1); +}); + +it("says a seat waits when no favorite is free, and offers nothing to press", async () => { + setup({ + policy: "swap", + notices: [{ seat: "critic", limited, state: "none-free", substitute: null }], + }); + await using _screen = await render( {}} />); + + await expect + .element(page.getByText("critic: claude-fable has reached its usage limit")) + .toBeVisible(); + await expect.element(page.getByText("No favorite model is free, so critic waits.")).toBeVisible(); + expect(page.getByRole("button", { name: /Swap/ }).elements()).toHaveLength(0); +}); + +it("links a lead that was handed on to the thread it continues in", async () => { + setup({ + policy: "swap", + notices: [ + { + seat: null, + limited, + state: "swapped", + substitute: kimi, + continuedIn: ThreadId.make("continued"), + }, + ], + }); + const onOpenThread = vi.fn(); + await using _screen = await render(); + + await expect.element(page.getByText("Continued on kimi-k3")).toBeVisible(); + await page.getByRole("button", { name: "Open thread" }).click(); + expect(onOpenThread).toHaveBeenCalledWith("continued"); +}); diff --git a/apps/web/src/components/chat/LimitedSeatNotices.tsx b/apps/web/src/components/chat/LimitedSeatNotices.tsx new file mode 100644 index 0000000000000..f5e79a598f3f5 --- /dev/null +++ b/apps/web/src/components/chat/LimitedSeatNotices.tsx @@ -0,0 +1,159 @@ +import { + AuthOrchestrationOperateScope, + type DeliveryLimitedSeatNotice, + type EnvironmentId, + type ModelSelection, + type ServerProvider, + type ThreadId, +} from "@t3tools/contracts"; +import type { TimestampFormat } from "@t3tools/contracts/settings"; +import { msg } from "gt-react"; +import { ArrowLeftRightIcon, GaugeIcon } from "lucide-react"; +import { useState } from "react"; + +import { m, type MessageResolver } from "~/i18n/messages"; +import { deliveryEnvironment } from "../../state/delivery"; +import { useEnvironmentQuery } from "../../state/query"; +import { useEnvironmentScope } from "../../state/session"; +import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; +import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; +import { useAtomCommand } from "../../state/use-atom-command"; +import { formatUpcomingTimestamp } from "../../timestampFormat"; +import { Button } from "../ui/button"; +import { toastManager } from "../ui/toast"; +import type { ComposerBannerStackItem } from "./ComposerBannerStack"; +import { limitedSeatNoticeViews } from "@t3tools/client-runtime/limited-seat-notices"; + +/** + * The notices for a team conversation whose lead or seats have reached a usage limit: the free + * favorite to swap to in one click, the wait when none is free, and where a lead was handed on. + */ +export function useLimitedSeatBannerItems( + input: { + readonly environmentId: EnvironmentId; + /** Null where the conversation has no participants, so nothing is asked of the server. */ + readonly threadId: ThreadId | null; + readonly providers: ReadonlyArray; + readonly timestampFormat: TimestampFormat; + readonly onOpenThread: (threadId: ThreadId) => void; + }, + resolve: MessageResolver = m, +): ReadonlyArray { + const { environmentId, threadId, providers } = input; + const query = useEnvironmentQuery( + threadId === null + ? null + : deliveryEnvironment.limitedSeats({ environmentId, input: { threadId } }), + ); + const { refresh } = query; + if (threadId === null) return []; + return limitedSeatNoticeViews( + query.data, + { + modelName: (model) => + providers + .find((provider) => provider.instanceId === model.instanceId) + ?.models.find((candidate) => candidate.slug === model.model)?.name ?? model.model, + formatReset: (resetAt) => { + const time = formatUpcomingTimestamp( + resetAt, + input.timestampFormat, + undefined, + undefined, + resolve, + ); + return time ? resolve(msg("Resets {time}", { time })) : null; + }, + }, + resolve, + ).map((view) => { + const { continuedIn } = view.notice; + return { + id: view.id, + variant: view.notice.state === "swapped" ? "default" : "warning", + group: "environment", + icon: , + title: view.title, + description: view.description, + actions: + view.action?.type === "swap" ? ( + { + refresh(); + if (next !== null) input.onOpenThread(next); + }} + /> + ) : view.action?.type === "open" && continuedIn !== undefined ? ( + + ) : null, + } satisfies ComposerBannerStackItem; + }); +} + +/** + * Swaps a limited seat, or hands a limited lead on, in one click. Built like the provider Fix + * button: disabled while it works and hidden where threads cannot be run. The command is safe + * to repeat, so a second click makes no second thread. + */ +function LimitedSeatSwapButton(props: { + readonly environmentId: EnvironmentId; + readonly threadId: ThreadId; + readonly notice: DeliveryLimitedSeatNotice; + readonly substitute: ModelSelection; + readonly label: string; + /** Called with the thread a lead continues in, or null for a seat. */ + readonly onSwapped: (continuedIn: ThreadId | null) => void; +}) { + const canOperate = useEnvironmentScope(props.environmentId, AuthOrchestrationOperateScope); + const swap = useAtomCommand(deliveryEnvironment.swapLimitedSeat, { + label: "swap a limited seat", + reportFailure: false, + }); + const [swapping, setSwapping] = useState(false); + if (!canOperate) return null; + + const run = async () => { + setSwapping(true); + const result = await swap({ + environmentId: props.environmentId, + input: { + threadId: props.threadId, + seat: props.notice.seat, + modelSelection: props.substitute, + }, + }); + setSwapping(false); + if (result._tag === "Failure") { + toastManager.add({ + type: "error", + title: m(msg("Could not swap the model")), + description: + thrownErrorMessage(squashAtomCommandFailure(result), m) ?? + m(msg("Try again from the notice.")), + }); + return; + } + if (result.value.continuedIn === null) { + toastManager.add({ + type: "success", + title: m(msg("Swapped")), + description: m(msg("It applies from your next message.")), + }); + } + props.onSwapped(result.value.continuedIn); + }; + + return ( + + ); +} diff --git a/apps/web/src/components/chat/SubagentTooltipContent.tsx b/apps/web/src/components/chat/SubagentTooltipContent.tsx index 722968fb6241a..bd7415c75b168 100644 --- a/apps/web/src/components/chat/SubagentTooltipContent.tsx +++ b/apps/web/src/components/chat/SubagentTooltipContent.tsx @@ -22,6 +22,7 @@ import { CircleDashedIcon, CircleXIcon, FolderIcon, + GaugeIcon, GitBranchIcon, TerminalIcon, } from "lucide-react"; @@ -37,6 +38,8 @@ export function SubagentTooltipContent(props: { providerInstanceId: ProviderInstanceId; origin: OrchestrationV2Subagent["origin"]; modelSelection?: OrchestrationV2Subagent["modelSelection"]; + /** The seat's own model, when a substitute ran this turn because that one was limited. */ + substituteFor?: NonNullable["substituteFor"]; provider?: ServerProvider | undefined; providers?: ReadonlyArray | undefined; driver?: ProviderDriverKind | undefined; @@ -197,6 +200,16 @@ export function SubagentTooltipContent(props: { {props.elapsed} + {props.substituteFor ? ( +
+ + + {gt("Substitute for {model}, which reached its usage limit", { + model: props.substituteFor.model, + })} + +
+ ) : null} {metadata.map(({ label, value }, index) => { const Icon = props.childThread?.branch && !(hasProjectRow && index === 0) ? GitBranchIcon : FolderIcon; diff --git a/apps/web/src/components/chat/UsageLimitRecoveryBanner.test.tsx b/apps/web/src/components/chat/UsageLimitRecoveryBanner.test.tsx index ea757f4604128..77263da1018c0 100644 --- a/apps/web/src/components/chat/UsageLimitRecoveryBanner.test.tsx +++ b/apps/web/src/components/chat/UsageLimitRecoveryBanner.test.tsx @@ -6,7 +6,7 @@ import { usageLimitRecoveryBannerItem } from "./UsageLimitRecoveryBanner"; const stoppedAt = new Date(2026, 9, 20, 12, 0); -function bannerItem(resetAt: Date, timestampFormat: TimestampFormat = "24-hour") { +function bannerItem(resetAt: Date, timestampFormat: TimestampFormat = "24-hour", handedOn = false) { return usageLimitRecoveryBannerItem({ runId: RunId.make("run-1"), errorCode: null, @@ -14,6 +14,7 @@ function bannerItem(resetAt: Date, timestampFormat: TimestampFormat = "24-hour") stoppedAt: stoppedAt.toISOString(), settled: false, requestPending: false, + handedOn, snoozedUntil: null, recovery: null, timestampFormat, @@ -30,6 +31,15 @@ describe("usageLimitRecoveryBannerItem", () => { expect(bannerItem(new Date(2026, 9, 20, 17, 30), timestampFormat).description).toBe(expected); }); + it("offers no resume or snooze once the run continues in a linked thread", () => { + using _now = vi.spyOn(Date, "now").mockReturnValue(stoppedAt.getTime()); + const resetAt = new Date(2026, 9, 20, 17, 30); + expect(bannerItem(resetAt).actions).not.toBeNull(); + const handedOn = bannerItem(resetAt, "24-hour", true); + expect(handedOn.actions).toBeNull(); + expect(handedOn.description).toBe("Resets 17:30"); + }); + it("names the day when the reset is tomorrow", () => { using _now = vi.spyOn(Date, "now").mockReturnValue(stoppedAt.getTime()); expect(bannerItem(new Date(2026, 9, 21, 17, 30)).description).toBe("Resets tomorrow at 17:30"); diff --git a/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx b/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx index 61774393c445d..2159203e235b2 100644 --- a/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx +++ b/apps/web/src/components/chat/UsageLimitRecoveryBanner.tsx @@ -31,6 +31,8 @@ type RecoveryProps = { stoppedAt: string; settled: boolean; requestPending: boolean; + /** The run continues in a linked thread, so resuming it here would run the same work twice. */ + handedOn?: boolean; snoozedUntil: string | null; recovery: OrchestrationV2LimitRecovery | null; timestampFormat: TimestampFormat; @@ -48,13 +50,21 @@ function parseEpochMs(isoDate: string | null): number | null { function limitRecoveryScheduleState( props: Pick< RecoveryProps, - "runId" | "resetAt" | "stoppedAt" | "settled" | "requestPending" | "recovery" | "snoozedUntil" + | "runId" + | "resetAt" + | "stoppedAt" + | "settled" + | "requestPending" + | "handedOn" + | "recovery" + | "snoozedUntil" >, ) { // The server refuses recovery changes while a request is pending. const canSchedule = !props.settled && !props.requestPending && + props.handedOn !== true && props.resetAt !== null && Date.parse(props.resetAt) > Date.parse(props.stoppedAt); const resumes = diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsx index 964656733193d..2cdbe20486841 100644 --- a/apps/web/src/components/chat/V2LifecycleRow.tsx +++ b/apps/web/src/components/chat/V2LifecycleRow.tsx @@ -584,6 +584,7 @@ function SubagentTimelineLink(props: { elapsed={agent ? : null} model={agent?.model ?? null} modelSelection={agent?.modelSelection} + substituteFor={agent?.teamChat?.substituteFor} status={liveStatus} result={agent?.result ?? props.result} progress={agent?.progress ?? props.progress} @@ -597,6 +598,7 @@ function SubagentTimelineTooltip( props: Parameters[0] & { model: string | null; modelSelection: OrchestrationV2Subagent["modelSelection"]; + substituteFor: NonNullable["substituteFor"]; elapsed: ReactNode; }, ) { @@ -619,6 +621,7 @@ function SubagentTimelineTooltip( providerInstanceId={props.providerInstanceId} origin={props.origin} modelSelection={props.modelSelection} + substituteFor={props.substituteFor} provider={providers.find((provider) => provider.instanceId === props.providerInstanceId)} providers={providers} driver={props.driver} diff --git a/apps/web/src/components/chat/useComposerSend.ts b/apps/web/src/components/chat/useComposerSend.ts index 41019aae9cff3..d66050caa7c1d 100644 --- a/apps/web/src/components/chat/useComposerSend.ts +++ b/apps/web/src/components/chat/useComposerSend.ts @@ -1076,6 +1076,7 @@ export function useComposerSend(input: ComposerSendInput) { entries: providerInstanceEntries, critique: orchestratorDraft.critique, access: orchestratorDraft.access, + limitedSeat: orchestratorDraft.limitedSeat, extras: orchestratorDraft.extraParticipants, orchestrator: { harness: ctxSelectedProvider diff --git a/apps/web/src/components/delivery/OrchestratorChatSetup.tsx b/apps/web/src/components/delivery/OrchestratorChatSetup.tsx index 95ad77522d1b9..bf053eea8ff71 100644 --- a/apps/web/src/components/delivery/OrchestratorChatSetup.tsx +++ b/apps/web/src/components/delivery/OrchestratorChatSetup.tsx @@ -71,6 +71,7 @@ export function OrchestratorChatSetup(props: { entries: props.entries, critique: draft?.critique, access: draft?.access, + limitedSeat: draft?.limitedSeat, extras: draft?.extraParticipants, orchestrator: { harness: leadEntry ? (DELIVERY_HARNESS_BY_DRIVER[leadEntry.driverKind] ?? null) : null, diff --git a/apps/web/src/components/delivery/OrchestratorLineup.browser.test.tsx b/apps/web/src/components/delivery/OrchestratorLineup.browser.test.tsx index c8b9866845c40..c60472f76292c 100644 --- a/apps/web/src/components/delivery/OrchestratorLineup.browser.test.tsx +++ b/apps/web/src/components/delivery/OrchestratorLineup.browser.test.tsx @@ -443,3 +443,84 @@ it("saves reasoning and context window together in the participant model selecti ); await expect.element(scout.getByRole("button", { name: /Maximum/ })).toBeVisible(); }); + +it("saves what a limited seat does from the footer, and leaves the control off a board task", async () => { + testState.threadState = { + data: { binding: RESEARCH_BINDING, lineup: LINEUP_OF_THREE, pending: null }, + }; + testState.setLineup.mockClear(); + await using screen = await render( + , + ); + + const control = page.getByRole("combobox", { name: "When a seat is limited" }); + await expect.element(control).toHaveTextContent("Swap automatically"); + await control.click(); + await page.getByRole("option", { name: "Ask me" }).click(); + await vi.waitFor(() => { + expect(testState.setLineup).toHaveBeenCalledWith({ + environmentId: "env-a", + input: { threadId: "t1", orchestration: { ...LINEUP_OF_THREE, limitedSeat: "ask" } }, + }); + }); + await expect.element(control).toHaveTextContent("Ask me"); + + await screen.rerender( + , + ); + await expect.element(control).not.toBeInTheDocument(); + await expect.element(page.getByRole("combobox", { name: "Critique round" })).toBeInTheDocument(); +}); + +// The model picker is 360px wide; its provider rail and border leave the team panel 315px, and a +// classic scrollbar takes 15px more. +it.each([315, 300])( + "fits the footer's three selects in a %ipx panel, with nothing cut off", + async (width) => { + testState.threadState = { + data: { + binding: RESEARCH_BINDING, + lineup: { ...LINEUP_OF_THREE, access: "approval-required", critique: "first" }, + pending: null, + }, + }; + await page.viewport(1024, 768); + await using _screen = await render( +
+ {}} + /> +
, + ); + const panel = document.querySelector("[data-popover-panel]")!.getBoundingClientRect(); + for (const name of ["Critique round", "Participants' access", "When a seat is limited"]) { + const trigger = page.getByRole("combobox", { name }); + await expect.element(trigger).toBeVisible(); + const element = trigger.element(); + const box = element.getBoundingClientRect(); + expect(box.left, name).toBeGreaterThanOrEqual(panel.left); + expect(box.right, name).toBeLessThanOrEqual(panel.right); + // Neither the trigger nor the value inside it is cut short. + for (const part of [element, element.firstElementChild!]) + expect(part.scrollWidth, name).toBeLessThanOrEqual(part.clientWidth + 1); + } + }, +); diff --git a/apps/web/src/components/delivery/OrchestratorLineup.tsx b/apps/web/src/components/delivery/OrchestratorLineup.tsx index cc79ab1bc83dc..3857493b86dcb 100644 --- a/apps/web/src/components/delivery/OrchestratorLineup.tsx +++ b/apps/web/src/components/delivery/OrchestratorLineup.tsx @@ -1,5 +1,6 @@ import { DELIVERY_HARNESS_BY_DRIVER, + deliveryLimitedSeatPolicy, type DeliveryOrchestrationConfig, type EnvironmentId, type ModelSelection, @@ -45,6 +46,8 @@ function valueOfLineup( included: true, modelSelection: joined.modelSelection, ...(joined.access ? { access: joined.access } : {}), + ...(joined.picked ? { picked: true } : {}), + ...(joined.substitute ? { substitute: joined.substitute } : {}), } : { included: false }, ]; @@ -57,9 +60,12 @@ function valueOfLineup( role: item.role, modelSelection: item.modelSelection, ...(item.access ? { access: item.access } : {}), + ...(item.substitute ? { substitute: item.substitute } : {}), })), ...(lineup.critique ? { critique: lineup.critique } : {}), ...(lineup.access ? { access: lineup.access } : {}), + // A started conversation keeps its own answer; the team's default is for new ones. + limitedSeat: deliveryLimitedSeatPolicy(lineup), }; } @@ -81,6 +87,8 @@ export function OrchestratorLineup(props: { readonly role: string; readonly modelSelection: ModelSelection; }) => void; + /** A board task's conversation, where the team's own setting decides for a limited seat. */ + readonly boardOwned?: boolean | undefined; /** Leaves the team for ordinary chat; the composer remembers it server-side. */ readonly onLeaveToSingle?: () => void; }) { @@ -119,6 +127,7 @@ export function OrchestratorLineup(props: { entries: props.entries, critique: forValue.critique, access: forValue.access, + limitedSeat: forValue.limitedSeat, extras: forValue.extraParticipants, orchestrator: { harness: @@ -227,6 +236,7 @@ export function OrchestratorLineup(props: { roster={roster} entries={props.entries} models={props.models} + boardOwned={props.boardOwned} {...(props.onFocusChat ? { onFocus: props.onFocusChat } : {})} {...(binding ? { about: "A conversation keeps the team it started with." } : {})} {...(lineup && props.onLeaveToSingle diff --git a/apps/web/src/components/delivery/OrchestratorParticipants.tsx b/apps/web/src/components/delivery/OrchestratorParticipants.tsx index b7538f0b31952..b255ff4181ebd 100644 --- a/apps/web/src/components/delivery/OrchestratorParticipants.tsx +++ b/apps/web/src/components/delivery/OrchestratorParticipants.tsx @@ -6,7 +6,16 @@ import type { } from "@t3tools/contracts"; import { DELIVERY_HARNESS_BY_DRIVER } from "@t3tools/contracts"; import { createModelSelection } from "@t3tools/shared/model"; -import { CrownIcon, MessageCircleIcon, PlusIcon, RepeatIcon, Undo2Icon, XIcon } from "lucide-react"; +import { useGT } from "gt-react"; +import { + CrownIcon, + GaugeIcon, + MessageCircleIcon, + PlusIcon, + RepeatIcon, + Undo2Icon, + XIcon, +} from "lucide-react"; import type { ReactNode } from "react"; import { cn } from "~/lib/utils"; import type { DeliveryTeam } from "../../lib/delivery"; @@ -14,6 +23,7 @@ import type { OrchestratorAccess, OrchestratorCritique, OrchestratorExtraParticipant, + OrchestratorLimitedSeat, OrchestratorParticipantAccess, OrchestratorParticipantChoice, resolveOrchestratorRoster, @@ -51,6 +61,7 @@ export interface OrchestratorLineupValue { readonly extraParticipants?: ReadonlyArray; readonly critique?: OrchestratorCritique; readonly access?: OrchestratorAccess | undefined; + readonly limitedSeat?: OrchestratorLimitedSeat | undefined; } /** The participants of a team conversation, with its critique round and access. */ @@ -73,12 +84,24 @@ export function OrchestratorParticipants(props: { readonly onFocus?: | ((row: { readonly role: string; readonly modelSelection: ModelSelection }) => void) | undefined; + /** A board task's conversation: its team's own setting decides what a limited seat does. */ + readonly boardOwned?: boolean | undefined; /** What the owning panel adds to the explanation behind the info button. */ readonly about?: ReactNode; /** The owning panel's own action, at the end of the footer row. */ readonly footer?: ReactNode; }) { + const gt = useGT(); const { team, value, roster } = props; + const limitedSeatOptions: ReadonlyArray<{ + readonly value: OrchestratorLimitedSeat; + readonly label: string; + }> = [ + { value: "swap", label: gt("Swap automatically") }, + { value: "ask", label: gt("Ask me") }, + { value: "skip", label: gt("Leave it out") }, + ]; + const limitedSeatLabel = gt("When a seat is limited"); const entries = props.entries.filter((entry) => DELIVERY_HARNESS_BY_DRIVER[entry.driverKind]); const models = new Map(props.models); for (const row of roster.rows) { @@ -145,6 +168,14 @@ export function OrchestratorParticipants(props: { edit, commit, push and post. A participant's own access, set beside it, comes first, and a seat the team keeps read-only stays read-only unless you change it here. + {props.boardOwned ? null : ( + + {limitedSeatLabel}: + {gt( + "a seat whose model has reached its usage limit moves to the first free model in your Favorites, waits for you to choose, or sits the message out. It applies from your next message. A model you chose for a seat by hand is never swapped without asking.", + )} + + )}
@@ -173,14 +204,21 @@ export function OrchestratorParticipants(props: { ? lead({ role: row.role, modelSelection }) : row.extra ? setExtras( - extras.map((extra) => - extra.id === row.seat ? { ...extra, modelSelection } : extra, - ), + extras.map((extra) => { + if (extra.id !== row.seat) return extra; + // A new choice by hand ends whatever stood in for the old one. + const { substitute: _substitute, ...kept } = extra; + return { ...kept, modelSelection }; + }), ) : props.onChange({ participantChoices: { ...value.participantChoices, - [row.seat]: { ...value.participantChoices?.[row.seat], modelSelection }, + [row.seat]: (() => { + const { substitute: _substitute, ...kept } = + value.participantChoices?.[row.seat] ?? {}; + return { ...kept, modelSelection, picked: true }; + })(), }, }); const setAccess = (access: OrchestratorParticipantAccess) => @@ -474,6 +512,33 @@ export function OrchestratorParticipants(props: { ))} + {props.boardOwned ? null : ( + + )} {props.footer ? {props.footer} : null}
{roster.problem ? ( diff --git a/apps/web/src/components/settings/FavoriteModelsOrderList.tsx b/apps/web/src/components/settings/FavoriteModelsOrderList.tsx new file mode 100644 index 0000000000000..cb02daa5f4465 --- /dev/null +++ b/apps/web/src/components/settings/FavoriteModelsOrderList.tsx @@ -0,0 +1,163 @@ +import { + DndContext, + type DragEndEvent, + PointerSensor, + closestCenter, + useSensor, + useSensors, +} from "@dnd-kit/core"; +import { restrictToParentElement, restrictToVerticalAxis } from "@dnd-kit/modifiers"; +import { SortableContext, useSortable, verticalListSortingStrategy } from "@dnd-kit/sortable"; +import { CSS } from "@dnd-kit/utilities"; +import type { ServerProvider, UnifiedSettings } from "@t3tools/contracts"; +import { useGT } from "gt-react"; +import { ArrowDownIcon, ArrowUpIcon, GripVerticalIcon } from "lucide-react"; +import { useState } from "react"; + +import { cn } from "~/lib/utils"; +import { Button } from "../ui/button"; + +type Favorites = UnifiedSettings["favorites"]; + +const favoriteKey = (favorite: Favorites[number]) => `${favorite.provider}\u0000${favorite.model}`; + +function moveFavorite(favorites: Favorites, key: string, steps: number): Favorites { + const from = favorites.findIndex((favorite) => favoriteKey(favorite) === key); + const to = Math.max(0, Math.min(favorites.length - 1, from + steps)); + if (from === -1 || from === to) return favorites; + const next = [...favorites]; + const [entry] = next.splice(from, 1); + if (!entry) return favorites; + next.splice(to, 0, entry); + return next; +} + +/** The starred models across providers, first choice first. Step buttons serve the keyboard. */ +export function FavoriteModelsOrderList(props: { + readonly favorites: Favorites; + readonly providers: ReadonlyArray; + readonly disabled: boolean; + readonly onReorder: (next: Favorites) => Promise; +}) { + const gt = useGT(); + // The order a person just made, shown until the server's own has been read back. + const [saving, setSaving] = useState(null); + const favorites = saving ?? props.favorites; + const keys = favorites.map(favoriteKey); + const sensors = useSensors(useSensor(PointerSensor, { activationConstraint: { distance: 4 } })); + const move = (key: string, steps: number) => { + const next = moveFavorite(favorites, key, steps); + if (next === favorites) return; + setSaving(next); + void props + .onReorder(next) + .finally(() => setSaving((current) => (current === next ? null : current))); + }; + const handleDragEnd = (event: DragEndEvent) => { + if (event.over === null || event.active.id === event.over.id) return; + const from = keys.indexOf(String(event.active.id)); + const to = keys.indexOf(String(event.over.id)); + if (from !== -1 && to !== -1) move(String(event.active.id), to - from); + }; + + return ( + + +
    + {favorites.map((favorite, index) => { + const provider = props.providers.find( + (candidate) => candidate.instanceId === favorite.provider, + ); + return ( + model.slug === favorite.model)?.name ?? + favorite.model + } + provider={provider?.displayName ?? favorite.provider} + position={index + 1} + count={favorites.length} + disabled={props.disabled} + onMove={(steps) => move(favoriteKey(favorite), steps)} + /> + ); + })} +
+
+
+ ); +} + +function FavoriteRow(props: { + readonly id: string; + readonly name: string; + readonly provider: string; + readonly position: number; + readonly count: number; + readonly disabled: boolean; + readonly onMove: (steps: number) => void; +}) { + const gt = useGT(); + const { name } = props; + const { listeners, setNodeRef, setActivatorNodeRef, transform, transition, isDragging } = + useSortable({ id: props.id, disabled: props.disabled }); + return ( +
  • + {props.position} + + {name} + {props.provider} + + + + + + + + +
  • + ); +} diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsx index 892c9cd219454..65f4a72587cf7 100644 --- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx +++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx @@ -1,3 +1,4 @@ +import { FavoriteModelsOrderList } from "./FavoriteModelsOrderList"; import { SettingsGroup } from "./SettingsGroup"; import { RefreshIcon } from "~/components/ui/refresh-icon"; import { @@ -1164,6 +1165,31 @@ export function EnvironmentProviderSettings({ /> ) : null} + + +
    + {favorites.length === 0 ? ( +

    + Star a model in a provider's model list to add it here. +

    + ) : ( + updateModelPreferences({ setModelFavoriteOrder: next })} + /> + )} +
    +
    +
    + ; +const isLimitedSeatPolicy = Schema.is(DeliveryLimitedSeatPolicy); const isRecord = (value: unknown): value is Json => typeof value === "object" && value !== null && !Array.isArray(value); const text = (value: unknown, fallback = ""): string => @@ -81,6 +84,8 @@ export interface DeliveryTeam { readonly defined: Readonly>; }; readonly qaGate: { readonly seats: ReadonlyArray; readonly minimum: number } | null; + /** What the team's profile says a new conversation does when a seat is limited, if it says. */ + readonly whenSeatLimited: DeliveryLimitedSeatPolicy | null; } export interface DeliveryRole { @@ -495,6 +500,7 @@ const parseTeam = (team: Json): DeliveryTeam => { }, workload: { build: shares(workload.build), defined: shares(workload.defined) }, qaGate: qa ? { seats: strings(qa.seats), minimum: count(qa.minimumPassingProviders) } : null, + whenSeatLimited: isLimitedSeatPolicy(team.whenSeatLimited) ? team.whenSeatLimited : null, }; }; diff --git a/apps/web/src/lib/orchestratorChat.test.ts b/apps/web/src/lib/orchestratorChat.test.ts index e05427822dea0..8b82d5a1a705f 100644 --- a/apps/web/src/lib/orchestratorChat.test.ts +++ b/apps/web/src/lib/orchestratorChat.test.ts @@ -506,3 +506,84 @@ it("does not put a held retry back on the roster it failed with once a newer lin }), ).toEqual({ source: "held", orchestration: heldOrchestration }); }); + +it("takes what a limited seat does from the person, then the team's profile, then swaps", () => { + const { team, entries } = setup(); + const resolve = ( + forTeam: typeof team, + limitedSeat?: "swap" | "ask" | "skip", + ): DeliveryOrchestrationConfig | null => + resolveOrchestratorRoster({ team: forTeam, choices: undefined, entries, limitedSeat }) + .configuration; + + // Swap automatically is the default, and the default is not written down. + expect(resolve(team)).not.toHaveProperty("limitedSeat"); + const asks = { ...team, whenSeatLimited: "ask" as const }; + expect(resolve(asks)?.limitedSeat).toBe("ask"); + expect(resolve(asks, "skip")?.limitedSeat).toBe("skip"); + // A person's own "swap" stands against a team that asks. + expect(resolve(asks, "swap")).not.toHaveProperty("limitedSeat"); +}); + +it("reads the team profile's default for a limited seat, and ignores a value it does not know", () => { + const teamOf = (whenSeatLimited: unknown) => + parseTeams([{ team: "research", available: true, seats: [], whenSeatLimited }])[0]!; + expect(teamOf("skip").whenSeatLimited).toBe("skip"); + expect(teamOf("later").whenSeatLimited).toBeNull(); + expect(teamOf(undefined).whenSeatLimited).toBeNull(); +}); + +it("marks a model chosen by hand, a seat's duty and an agreed substitute for the limited-seat rule", () => { + const { entries } = setup(); + const team = parseTeams([ + { + team: "development", + available: true, + roles: [{ role: "developer" }, { role: "qa" }], + seats: [ + { + seat: "developer", + title: "Developer", + role: "developer", + harness: "claude", + model: "a", + stages: ["plan", "build"], + available: true, + }, + { + seat: "qa", + title: "QA", + role: "qa", + harness: "codex", + model: "b", + stages: ["qa"], + available: true, + }, + ], + }, + ])[0]!; + const chosen = createModelSelection(ProviderInstanceId.make("codex"), "c"); + const first = resolveOrchestratorRoster({ team, choices: undefined, entries }); + expect(first.problem).toBeNull(); + const untouched = first.configuration; + expect(untouched?.participants).toEqual([ + expect.objectContaining({ seat: "developer", duty: "build" }), + expect.objectContaining({ seat: "qa", duty: "qa" }), + ]); + expect(untouched?.participants[1]).not.toHaveProperty("picked"); + + const picked = resolveOrchestratorRoster({ + team, + entries, + // A saved lineup round-trips every seat's model; only a hand pick carries the mark. + choices: { + developer: { included: true, modelSelection: chosen }, + qa: { included: true, modelSelection: chosen, picked: true, substitute: chosen }, + }, + extras: [{ id: "custom-1", role: "qa", modelSelection: chosen }], + }).configuration; + expect(picked?.participants[0]).not.toHaveProperty("picked"); + expect(picked?.participants[1]).toMatchObject({ picked: true, substitute: chosen }); + // An added participant is a person's own choice, and takes the duty of its role. + expect(picked?.participants[2]).toMatchObject({ seat: "custom-1", picked: true, duty: "qa" }); +}); diff --git a/apps/web/src/lib/orchestratorChat.ts b/apps/web/src/lib/orchestratorChat.ts index 8b44cc5714044..2761c72d71a77 100644 --- a/apps/web/src/lib/orchestratorChat.ts +++ b/apps/web/src/lib/orchestratorChat.ts @@ -1,5 +1,6 @@ import { DELIVERY_HARNESS_BY_DRIVER, + type DeliveryLimitedSeatPolicy, type DeliveryOrchestrationConfig, type ModelSelection, } from "@t3tools/contracts"; @@ -22,6 +23,10 @@ export interface OrchestratorParticipantChoice { readonly modelSelection?: ModelSelection; /** This seat's access for the conversation, over the team's and the conversation's. */ readonly access?: OrchestratorParticipantAccess; + /** The model was chosen by hand here, so a limit never swaps it without asking. */ + readonly picked?: boolean; + /** What the person agreed the seat runs on while its own model is limited. */ + readonly substitute?: ModelSelection; } /** A participant added for one conversation: any provider and model, in one of the team's roles. */ @@ -30,10 +35,12 @@ export interface OrchestratorExtraParticipant { readonly role: string; readonly modelSelection?: ModelSelection; readonly access?: OrchestratorParticipantAccess; + readonly substitute?: ModelSelection; } export type OrchestratorCritique = NonNullable; export type OrchestratorAccess = NonNullable; +export type OrchestratorLimitedSeat = DeliveryLimitedSeatPolicy; export function resolveOrchestratorRoster(input: { readonly team: DeliveryTeam | null; @@ -45,6 +52,8 @@ export function resolveOrchestratorRoster(input: { readonly entries: ReadonlyArray; readonly critique?: OrchestratorCritique | undefined; readonly access?: OrchestratorAccess | undefined; + /** What a person chose for a limited seat; absent, the team's profile decides, else swap. */ + readonly limitedSeat?: OrchestratorLimitedSeat | undefined; readonly extras?: ReadonlyArray | undefined; /** The harness and role the orchestrator itself runs as, when known. */ readonly orchestrator?: { @@ -107,6 +116,12 @@ export function resolveOrchestratorRoster(input: { : null; return { problem, providerProblem: null }; }; + const dutyOf = (stages: ReadonlyArray) => + stages.includes("qa") + ? ("qa" as const) + : stages.includes("build") + ? ("build" as const) + : undefined; const teamRow = (seat: DeliveryTeam["seats"][number]) => { const settings = input.team?.settings.find((item) => item.seat === seat.seat); const choice = input.choices?.[seat.seat]; @@ -163,6 +178,9 @@ export function resolveOrchestratorRoster(input: { access, /** Set when the seat's access is its own and not the conversation's. */ ownAccess: own, + picked: choice?.picked === true && choice.modelSelection !== undefined, + substitute: choice?.substitute, + duty: dutyOf(seat.stages), /** The seat the orchestrator itself holds. */ orchestrator: seat.seat === ownSeat, extra: false, @@ -194,6 +212,14 @@ export function resolveOrchestratorRoster(input: { modelSelection: extra.modelSelection ?? null, access: extra.access ?? input.access ?? ("read-only" as const), ownAccess: extra.access, + // An added participant's model is always a person's own choice. + picked: extra.modelSelection !== undefined, + substitute: extra.substitute, + duty: dutyOf( + (input.team?.seats ?? []) + .filter((seat) => seat.role === extra.role) + .flatMap((seat) => seat.stages), + ), orchestrator: false, extra: true, problem, @@ -213,10 +239,12 @@ export function resolveOrchestratorRoster(input: { : selected.length < 2 || selected.length > 12 ? "Choose between 2 and 12 participants." : (selected.find((row) => row.problem)?.problem ?? null); + const limitedSeat = input.limitedSeat ?? input.team?.whenSeatLimited ?? "swap"; const configuration: DeliveryOrchestrationConfig | null = problem ? null : { ...(input.critique && input.critique !== "first" ? { critique: input.critique } : {}), + ...(limitedSeat !== "swap" ? { limitedSeat } : {}), ...(input.access ? { access: input.access } : {}), ...(input.callsTeam ? { team: input.callsTeam } : {}), participants: selected.flatMap((row) => @@ -227,12 +255,15 @@ export function resolveOrchestratorRoster(input: { role: row.role, modelSelection: row.modelSelection, ...(row.ownAccess ? { access: row.ownAccess } : {}), + ...(row.picked ? { picked: true } : {}), + ...(row.duty ? { duty: row.duty } : {}), + ...(row.substitute ? { substitute: row.substitute } : {}), }, ] : [], ), }; - return { rows, configuration, problem }; + return { rows, configuration, problem, limitedSeat }; } /** diff --git a/apps/web/src/state/delivery.ts b/apps/web/src/state/delivery.ts index 83c6dbde4c238..cd3e3bc20f7a5 100644 --- a/apps/web/src/state/delivery.ts +++ b/apps/web/src/state/delivery.ts @@ -23,17 +23,24 @@ import type { OrchestratorAccess, OrchestratorCritique, OrchestratorExtraParticipant, + OrchestratorLimitedSeat, OrchestratorParticipantChoice, } from "../lib/orchestratorChat"; import { boardPreferencesOf, useBoardStore } from "./deliveryBoard"; import { useEnvironments, usePrimaryEnvironmentId } from "./environments"; import { useEnvironmentQuery } from "./query"; +import { serverEnvironment } from "./server"; +import { environmentThreadShells } from "./threads"; import { useAtomCommand } from "./use-atom-command"; export type { SeatChoice }; export { useBoardStore } from "./deliveryBoard"; -export const deliveryEnvironment = createDeliveryEnvironmentAtoms(connectionAtomRuntime); +export const deliveryEnvironment = createDeliveryEnvironmentAtoms(connectionAtomRuntime, { + threadShellAtom: environmentThreadShells.threadShellAtom, + settingsAtom: serverEnvironment.settingsValueAtom, + providersAtom: serverEnvironment.providersValueAtom, +}); /** Whether this environment has a delivery engine turned on. */ export function useDeliveryEnabled(environmentId: EnvironmentId | null): boolean { @@ -347,6 +354,8 @@ export interface OrchestratorDraft { readonly critique?: OrchestratorCritique; /** The access participants run with; absent is the conversation's own. */ readonly access?: OrchestratorAccess | undefined; + /** When a seat is limited; absent is the team profile's default, else swap automatically. */ + readonly limitedSeat?: OrchestratorLimitedSeat | undefined; /** No team behind the conversation: every participant is added by hand. */ readonly teamless?: boolean; readonly started?: boolean; diff --git a/docs/user/composer.md b/docs/user/composer.md index 03c66e5bac98f..770ba927afd59 100644 --- a/docs/user/composer.md +++ b/docs/user/composer.md @@ -47,6 +47,18 @@ that cannot be held to read-only says so in the setup: leave it out or use full The lead uses the project's folder and your selected access settings. Use **Use ordinary chat** to leave Orchestrator before starting. +**When a seat is limited** decides what happens when a participant's model, or the +orchestrator's, has reached its usage limit. **Swap automatically**, the default, starts +that seat's next turn on the first free model in your Favorites: one that is available, +not limited itself, not on the limited model's account or provider, and not already used +in the conversation. A limited orchestrator continues in a new linked thread with a +summary, and the old thread stays readable and no longer resumes by itself. **Ask me** +shows a notice naming that model with one button to swap. **Leave it out** has the seat +sit the message out. A model you chose for a seat by hand is never swapped without +asking. With no favorite free, the seat waits and a notice says so. Put your Favorites +in order under Settings, Providers, **Favorites order**. The setting applies from your +next message; a board task's conversation follows its team's own setting instead. + Choose **No team** in the setup to run a conversation with participants of your own only: add two or more, each with any provider and model. They join as themselves, with no team instructions, and nothing is saved. diff --git a/packages/client-runtime/package.json b/packages/client-runtime/package.json index ab288e3a7b967..2db88ea0392c2 100644 --- a/packages/client-runtime/package.json +++ b/packages/client-runtime/package.json @@ -619,6 +619,10 @@ "types": "./src/pullRequestReply.ts", "default": "./src/pullRequestReply.ts" }, + "./limited-seat-notices": { + "types": "./src/limitedSeatNotices.ts", + "default": "./src/limitedSeatNotices.ts" + }, "./issue-presentation": { "types": "./src/issuePresentation.ts", "default": "./src/issuePresentation.ts" diff --git a/packages/client-runtime/src/limitedSeatNotices.test.ts b/packages/client-runtime/src/limitedSeatNotices.test.ts new file mode 100644 index 0000000000000..10ee7452e0c7f --- /dev/null +++ b/packages/client-runtime/src/limitedSeatNotices.test.ts @@ -0,0 +1,46 @@ +import { type DeliveryLimitedSeatNotice, ProviderInstanceId } from "@t3tools/contracts"; +import { createModelSelection } from "@t3tools/shared/model"; +import { expect, it } from "vite-plus/test"; + +import { limitedSeatNoticeViews } from "./limitedSeatNotices.ts"; + +const limited = { + instanceId: ProviderInstanceId.make("claude"), + model: "claude-fable", + resetAt: "2026-11-22T17:00:00.000Z", +}; +const kimi = createModelSelection(ProviderInstanceId.make("kimi"), "kimi-k3"); +const options = { + modelName: (model: { readonly model: string }) => model.model.toUpperCase(), + formatReset: () => "Resets 5 PM", +}; +const views = (notices: ReadonlyArray, policy: "ask" | null = "ask") => + limitedSeatNoticeViews({ policy, notices }, options); + +it("shows nothing where the setting does not govern or nothing was read yet", () => { + const notice = { seat: null, limited, state: "offered", substitute: kimi } as const; + expect(views([notice], null)).toEqual([]); + expect(limitedSeatNoticeViews(null, options)).toEqual([]); +}); + +it("offers a seat the free favorite by name, from the next message", () => { + const [view] = views([{ seat: "critic", limited, state: "offered", substitute: kimi }]); + expect(view).toMatchObject({ + title: "critic: CLAUDE-FABLE has reached its usage limit", + description: "KIMI-K3 is free. critic uses it from your next message.", + action: { type: "swap", label: "Swap to KIMI-K3", substitute: kimi }, + }); +}); + +it("says when the limit resets where no favorite is free", () => { + const [view] = views([{ seat: null, limited, state: "none-free", substitute: null }]); + expect(view).toMatchObject({ + description: "No favorite model is free, so this conversation waits. Resets 5 PM", + action: null, + }); +}); + +it("says what stands in for a seat a person agreed to swap", () => { + const [view] = views([{ seat: "critic", limited, state: "swapped", substitute: kimi }]); + expect(view).toMatchObject({ title: "critic runs on KIMI-K3", action: null }); +}); diff --git a/packages/client-runtime/src/limitedSeatNotices.ts b/packages/client-runtime/src/limitedSeatNotices.ts new file mode 100644 index 0000000000000..a2a4866eb1918 --- /dev/null +++ b/packages/client-runtime/src/limitedSeatNotices.ts @@ -0,0 +1,110 @@ +import type { + DeliveryLimitedSeatNotice, + DeliveryLimitedSeatStatus, + ModelSelection, +} from "@t3tools/contracts"; +import { mFallback, msg } from "gt-i18n"; +import type { MFunctionType } from "gt-i18n/types"; + +/** One limited-seat notice in words, with what its one action does. */ +export interface LimitedSeatNoticeView { + readonly id: string; + readonly notice: DeliveryLimitedSeatNotice; + readonly title: string; + readonly description: string; + readonly action: + | { readonly type: "swap"; readonly label: string; readonly substitute: ModelSelection } + | { readonly type: "open"; readonly label: string } + | null; +} + +/** The notices of a conversation whose seats or lead are limited, the lead's first. */ +export function limitedSeatNoticeViews( + status: DeliveryLimitedSeatStatus | null, + options: { + /** The name a model is shown by; its slug where the catalog has no name for it. */ + readonly modelName: (model: Pick) => string; + /** A reset time as the banner beside it writes one; null leaves the time out. */ + readonly formatReset: (resetAt: string) => string | null; + }, + resolve: MFunctionType = mFallback, +): ReadonlyArray { + if (status === null || status.policy === null) return []; + return status.notices.map((notice) => { + const model = options.modelName(notice.limited); + const substitute = notice.substitute === null ? null : options.modelName(notice.substitute); + const reset = notice.limited.resetAt ? options.formatReset(notice.limited.resetAt) : null; + const limited = + notice.seat === null + ? resolve(msg("{model} has reached its usage limit", { model })) + : resolve(msg("{seat}: {model} has reached its usage limit", { seat: notice.seat, model })); + const id = `limited-seat:${notice.seat ?? ""}:${notice.limited.instanceId}:${notice.limited.model}:${notice.state}`; + if (notice.state === "swapped" && substitute !== null) { + return notice.seat === null + ? { + id, + notice, + title: resolve(msg("Continued on {substitute}", { substitute })), + description: resolve( + msg( + "{model} reached its usage limit, so this conversation continues in a linked thread. This one stays readable.", + { model }, + ), + ), + action: { type: "open", label: resolve(msg("Open thread")) }, + } + : { + id, + notice, + title: resolve(msg("{seat} runs on {substitute}", { seat: notice.seat, substitute })), + description: resolve( + msg( + "{model} has reached its usage limit. {seat} returns to it once the limit resets.", + { + model, + seat: notice.seat, + }, + ), + ), + action: null, + }; + } + if (notice.state === "offered" && notice.substitute !== null && substitute !== null) { + return { + id, + notice, + title: limited, + description: + notice.seat === null + ? resolve( + msg( + "{substitute} is free. Swapping continues this conversation in a new linked thread with a summary.", + { substitute }, + ), + ) + : resolve( + msg("{substitute} is free. {seat} uses it from your next message.", { + substitute, + seat: notice.seat, + }), + ), + action: { + type: "swap", + label: resolve(msg("Swap to {substitute}", { substitute })), + substitute: notice.substitute, + }, + }; + } + const waits = + notice.seat === null + ? resolve(msg("No favorite model is free, so this conversation waits.")) + : resolve(msg("No favorite model is free, so {seat} waits.", { seat: notice.seat })); + return { + id, + notice, + title: limited, + description: reset === null ? waits : `${waits} ${reset}`, + action: null, + }; + }); +} diff --git a/packages/client-runtime/src/state/delivery.test.ts b/packages/client-runtime/src/state/delivery.test.ts index 836146b243015..5ad86c728fc55 100644 --- a/packages/client-runtime/src/state/delivery.test.ts +++ b/packages/client-runtime/src/state/delivery.test.ts @@ -4,6 +4,7 @@ import { AuthOrchestrationOperateScope, type AuthSessionState, EnvironmentId, + ThreadId, WS_METHODS, type DeliveryActInput, type DeliveryReadInput, @@ -26,7 +27,11 @@ import { import { EnvironmentSupervisor } from "../connection/supervisor.ts"; import type { WsRpcProtocolClient } from "../rpc/protocol.ts"; import type { RpcSession } from "../rpc/session.ts"; -import { createDeliveryEnvironmentAtoms } from "./delivery.ts"; +import { + createDeliveryEnvironmentAtoms, + limitedLeadHandedOn, + limitedSeatsRevision, +} from "./delivery.ts"; vi.mock("./session.ts", () => ({ createEnvironmentSessionAtoms: () => ({ sessionStateAtom: () => grantedSession }), @@ -49,7 +54,11 @@ const MAC = EnvironmentId.make("mac"); const WINDOWS = EnvironmentId.make("windows"); const TASK_PATH = "/api/tasks/1016"; -const makeHarness = Effect.fn("TestDeliveryEnvironments.makeHarness")(function* () { +const makeHarness = Effect.fn("TestDeliveryEnvironments.makeHarness")(function* ( + options: Parameters[1] = {}, + /** The lineup the server holds for a conversation, as its thread-binding read answers. */ + lineup: { current: unknown } = { current: undefined }, +) { const calls: Array<{ environmentId: EnvironmentId; method: string; input: unknown }> = []; const supervisors = new Map(); for (const environmentId of [MAC, WINDOWS]) { @@ -62,6 +71,16 @@ const makeHarness = Effect.fn("TestDeliveryEnvironments.makeHarness")(function* [WS_METHODS.deliveryRead]: (input: DeliveryReadInput) => respond(WS_METHODS.deliveryRead, input), [WS_METHODS.deliveryAct]: (input: DeliveryActInput) => respond(WS_METHODS.deliveryAct, input), + [WS_METHODS.deliveryLimitedSeats]: (input: unknown) => + respond(WS_METHODS.deliveryLimitedSeats, input).pipe( + Effect.as({ policy: "swap", notices: [] }), + ), + [WS_METHODS.deliveryThreadBinding]: () => + Effect.sync(() => ({ + binding: null, + pending: null, + ...(lineup.current === undefined ? {} : { lineup: lineup.current }), + })), } as unknown as WsRpcProtocolClient; const session: RpcSession = { client, @@ -112,6 +131,7 @@ const makeHarness = Effect.fn("TestDeliveryEnvironments.makeHarness")(function* } as unknown as EnvironmentRegistry["Service"]); const atoms = createDeliveryEnvironmentAtoms( Atom.runtime(Layer.succeed(EnvironmentRegistry, service)), + options, ); const registry = AtomRegistry.make(); yield* Effect.addFinalizer(() => Effect.sync(() => registry.dispose())); @@ -226,3 +246,147 @@ describe("delivery environment routing", () => { }), ); }); + +describe("limited-seat notices", () => { + const thread = ThreadId.make("lead-thread"); + const run = (runId: string, status: string) => + ({ latestRun: { runId, status }, runtime: null, modelSelection: fable }) as never; + const fable = { instanceId: "claude", model: "claude-fable" }; + const provider = (overrides: Record = {}) => + ({ + instanceId: "kimi", + enabled: true, + installed: true, + status: "ready", + auth: { status: "authenticated" }, + usageLimits: { windows: [{ id: "weekly", usedPercent: 40 }] }, + ...overrides, + }) as never; + const base = { + shell: run("run-1", "failed"), + continued: null, + lineup: { participants: [], limitedSeat: "ask" } as never, + settings: { favorites: [{ provider: "kimi", model: "kimi-k3" }] } as never, + providers: [provider()], + }; + + it("change with everything a notice is decided from, and with nothing else", () => { + const revision = limitedSeatsRevision(base); + const changes = { + "the setting": { lineup: { participants: [], limitedSeat: "skip" } as never }, + "the lineup's seats": { + lineup: { + participants: [{ seat: "critic", role: "reviewer", modelSelection: fable }], + limitedSeat: "ask", + } as never, + }, + "Favorites and their order": { + settings: { + favorites: [ + { provider: "deepseek", model: "deepseek-v4" }, + { provider: "kimi", model: "kimi-k3" }, + ], + } as never, + }, + "a provider turned off": { providers: [provider({ enabled: false })] }, + "a provider signed out": { providers: [provider({ auth: { status: "unauthenticated" } })] }, + "a provider reaching its limit": { + providers: [provider({ usageLimits: { windows: [{ id: "weekly", usedPercent: 100 }] } })], + }, + "the run": { shell: run("run-2", "running") }, + "the thread the run was handed on to": { + continued: { latestRun: null, runtime: null, modelSelection: fable } as never, + }, + }; + for (const [name, change] of Object.entries(changes)) + expect(limitedSeatsRevision({ ...base, ...change }), name).not.toBe(revision); + // A usage window filling up is not a change until it is full. + expect( + limitedSeatsRevision({ + ...base, + providers: [provider({ usageLimits: { windows: [{ id: "weekly", usedPercent: 41 }] } })], + }), + ).toBe(revision); + // The handed-on thread's first turn changes its model, and the notice names that model. + const forked = { latestRun: null, runtime: null, modelSelection: fable } as never; + const started = { + latestRun: { runId: "run-c", status: "running" }, + runtime: null, + modelSelection: { instanceId: "kimi", model: "kimi-k3" }, + } as never; + expect(limitedSeatsRevision({ ...base, continued: started })).not.toBe( + limitedSeatsRevision({ ...base, continued: forked }), + ); + }); + + it("knows a limited run was handed on by the thread it continues in", () => { + const continued = new Set(["limited-lead:run-1"]); + const has = (threadId: ThreadId) => continued.has(threadId); + expect(limitedLeadHandedOn(run("run-1", "failed"), has)).toBe(true); + expect(limitedLeadHandedOn(run("run-2", "failed"), has)).toBe(false); + expect(limitedLeadHandedOn(null, has)).toBe(false); + }); + + it.effect("are read again when the lineup, Favorites or a provider changes", () => + Effect.gen(function* () { + const settings = Atom.make(base.settings as object).pipe(Atom.keepAlive); + const providers = Atom.make(base.providers as object).pipe(Atom.keepAlive); + const shells = Atom.family((threadId: string) => + Atom.make(threadId === thread ? (base.shell as object) : null).pipe( + Atom.keepAlive, + ), + ); + const lineup = { current: base.lineup as unknown }; + const { atoms, calls, registry } = yield* makeHarness( + { + threadShellAtom: (ref) => shells(ref.threadId) as never, + settingsAtom: () => settings as never, + providersAtom: () => providers as never, + }, + lineup, + ); + const target = { environmentId: MAC, input: { threadId: thread } }; + const query = atoms.limitedSeats(target); + const reads = () => + calls.filter((call) => call.method === WS_METHODS.deliveryLimitedSeats).length; + const read = AtomRegistry.getResult(registry, query, { suspendOnWaiting: true }).pipe( + Effect.tap(() => Effect.yieldNow), + ); + registry.mount(query); + registry.mount(atoms.limitedLeadHandedOn({ environmentId: MAC, threadId: thread })); + yield* read; + yield* AtomRegistry.getResult(registry, atoms.threadBinding(target)); + yield* read; + const settled = reads(); + + registry.set(settings, { favorites: [] }); + yield* read; + expect(reads()).toBe(settled + 1); + + registry.set(providers, [provider({ enabled: false })]); + yield* read; + expect(reads()).toBe(settled + 2); + + // The lineup panel saves a new setting, then reads the conversation's state again. + lineup.current = { participants: [], limitedSeat: "skip" }; + registry.refresh(atoms.threadBinding(target)); + yield* AtomRegistry.getResult(registry, atoms.threadBinding(target), { + suspendOnWaiting: true, + }); + yield* read; + expect(reads()).toBe(settled + 3); + + // The run is handed on: the old thread stops offering its resume, and reads its notice. + const handedOn = atoms.limitedLeadHandedOn({ environmentId: MAC, threadId: thread }); + expect(registry.get(handedOn)).toBe(false); + registry.set(shells("limited-lead:run-1"), { + latestRun: null, + runtime: null, + modelSelection: fable, + }); + expect(registry.get(handedOn)).toBe(true); + yield* read; + expect(reads()).toBe(settled + 4); + }), + ); +}); diff --git a/packages/client-runtime/src/state/delivery.ts b/packages/client-runtime/src/state/delivery.ts index d26ca83a8d833..db54281aa4044 100644 --- a/packages/client-runtime/src/state/delivery.ts +++ b/packages/client-runtime/src/state/delivery.ts @@ -1,18 +1,124 @@ -import { WS_METHODS } from "@t3tools/contracts"; -import { Atom } from "effect/reactivity"; +import { + type DeliveryThreadState, + type EnvironmentId, + type ScopedThreadRef, + type ServerProvider, + type ServerSettings, + type ThreadId, + WS_METHODS, +} from "@t3tools/contracts"; +import { limitedLeadHandoffThreadId } from "@t3tools/shared/limitedSeat"; +import { AsyncResult, Atom } from "effect/reactivity"; import { deliveryBindingAtom } from "../deliveryModelLock.ts"; import type { EnvironmentRegistry } from "../connection/registry.ts"; +import { scopeThreadRef } from "../environment/scoped.ts"; +import type { EnvironmentThreadShell } from "./models.ts"; import { createEnvironmentRpcCommand, createEnvironmentRpcQueryAtomFamily } from "./runtime.ts"; +type LimitedSeatsShell = Pick; + +/** + * Everything a conversation's limited-seat notices are decided from, as one value that changes + * when any of it does: the lead's latest run and the reset it reported, the thread that run was + * handed on to, the lineup with its setting, Favorites, and what each provider can run now. + */ +export function limitedSeatsRevision(input: { + readonly shell: LimitedSeatsShell | null; + /** The thread the latest run was handed on to, once the client holds it. */ + readonly continued: LimitedSeatsShell | null; + readonly lineup: DeliveryThreadState["lineup"]; + readonly settings: Pick | null; + readonly providers: ReadonlyArray | null; +}): string { + const { shell, continued } = input; + return JSON.stringify([ + shell?.latestRun?.runId ?? null, + shell?.latestRun?.status ?? null, + shell?.runtime?.usageLimitResetAt ?? null, + shell?.modelSelection ?? null, + continued === null ? null : [continued.modelSelection, continued.latestRun?.runId ?? null], + input.lineup ?? null, + input.settings?.favorites ?? null, + input.settings?.projectSettingsOverrides ?? null, + (input.providers ?? []).map((provider) => [ + provider.instanceId, + provider.enabled, + provider.installed, + provider.status, + provider.availability ?? null, + provider.auth.status, + provider.auth.email ?? null, + provider.supportsSessions ?? null, + // A window's fill moves all day; only reaching or leaving its limit changes a notice. + (provider.usageLimits?.windows ?? []) + .filter((window) => (window.usedPercent ?? 0) >= 100) + .map((window) => [window.id, window.resetsAt ?? null]), + ]), + ]); +} + +/** Whether a thread's limited run continues in a linked thread, so it must not resume here too. */ +export function limitedLeadHandedOn( + shell: Pick | null, + hasThread: (threadId: ThreadId) => boolean, +): boolean { + const runId = shell?.latestRun?.runId; + return runId !== undefined && hasThread(limitedLeadHandoffThreadId(runId)); +} + export function createDeliveryEnvironmentAtoms( runtime: Atom.AtomRuntime, + options: { + /** A thread as the client holds it, so its limited-seat notices follow its runs. */ + readonly threadShellAtom?: (ref: ScopedThreadRef) => Atom.Atom; + /** Favorites and provider statuses decide a substitute, so the notices follow them too. */ + readonly settingsAtom?: ( + environmentId: EnvironmentId, + ) => Atom.Atom | null>; + readonly providersAtom?: ( + environmentId: EnvironmentId, + ) => Atom.Atom | null>; + } = {}, ) { + const { threadShellAtom, settingsAtom, providersAtom } = options; const threadBinding = createEnvironmentRpcQueryAtomFamily(runtime, { label: "environment-data:delivery:thread-binding", tag: WS_METHODS.deliveryThreadBinding, staleTimeMs: 1_000, }); + const limitedSeatsRevisionAtom = Atom.family((key: string) => + Atom.make((get) => { + const [environmentId, threadId] = JSON.parse(key) as [EnvironmentId, ThreadId]; + const shell = threadShellAtom + ? get(threadShellAtom(scopeThreadRef(environmentId, threadId))) + : null; + const runId = shell?.latestRun?.runId; + return limitedSeatsRevision({ + shell, + continued: + threadShellAtom && runId !== undefined + ? get(threadShellAtom(scopeThreadRef(environmentId, limitedLeadHandoffThreadId(runId)))) + : null, + lineup: AsyncResult.getOrElse( + get(threadBinding({ environmentId, input: { threadId } })), + () => null, + )?.lineup, + settings: settingsAtom ? get(settingsAtom(environmentId)) : null, + providers: providersAtom ? get(providersAtom(environmentId)) : null, + }); + }), + ); + const limitedLeadHandedOnAtom = Atom.family((key: string) => + Atom.make((get) => { + if (threadShellAtom === undefined) return false; + const [environmentId, threadId] = JSON.parse(key) as [EnvironmentId, ThreadId]; + return limitedLeadHandedOn( + get(threadShellAtom(scopeThreadRef(environmentId, threadId))), + (continued) => get(threadShellAtom(scopeThreadRef(environmentId, continued))) !== null, + ); + }), + ); const modelBinding = Atom.family((query: ReturnType) => Atom.family((threadId: string) => deliveryBindingAtom(query, threadId)), ); @@ -62,6 +168,27 @@ export function createDeliveryEnvironmentAtoms( key: ({ environmentId, input }) => JSON.stringify([environmentId, input.threadId]), }, }), + /** Which seats of a conversation are limited now, and what could stand in. */ + limitedSeats: createEnvironmentRpcQueryAtomFamily(runtime, { + label: "environment-data:delivery:limited-seats", + tag: WS_METHODS.deliveryLimitedSeats, + staleTimeMs: 2_000, + refreshTrigger: ({ environmentId, input }) => + limitedSeatsRevisionAtom(JSON.stringify([environmentId, input.threadId])), + }), + /** Whether a thread's limited run continues in a linked thread; it then offers no resume. */ + limitedLeadHandedOn: (ref: ScopedThreadRef) => + limitedLeadHandedOnAtom(JSON.stringify([ref.environmentId, ref.threadId])), + /** One click of a limited-seat notice. A second click while the first runs joins it. */ + swapLimitedSeat: createEnvironmentRpcCommand(runtime, { + label: "environment-data:delivery:swap-limited-seat", + tag: WS_METHODS.deliverySwapLimitedSeat, + concurrency: { + mode: "singleFlight", + key: ({ environmentId, input }) => + JSON.stringify([environmentId, input.threadId, input.seat]), + }, + }), bindThread: createEnvironmentRpcCommand(runtime, { label: "environment-data:delivery:bind-thread", tag: WS_METHODS.deliveryBindThread, diff --git a/packages/contracts/src/delivery.ts b/packages/contracts/src/delivery.ts index 3e0db5242fbfe..060dfc9d8d456 100644 --- a/packages/contracts/src/delivery.ts +++ b/packages/contracts/src/delivery.ts @@ -1,9 +1,14 @@ // Relay engine-owned payloads as JSON; type only the state T3 stores or acts on. import * as Schema from "effect/Schema"; -import { ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { IsoDateTime, ProjectId, ThreadId, TrimmedNonEmptyString } from "./baseSchemas.ts"; +import { ProviderInstanceId } from "./providerInstance.ts"; import { ModelSelection } from "./modelSelection.ts"; +/** What a conversation does when a seat's model has reached its usage limit. */ +export const DeliveryLimitedSeatPolicy = Schema.Literals(["swap", "ask", "skip"]); +export type DeliveryLimitedSeatPolicy = typeof DeliveryLimitedSeatPolicy.Type; + export const DeliveryOrchestrationConfig = Schema.Struct({ participants: Schema.Array( Schema.Struct({ @@ -12,10 +17,18 @@ export const DeliveryOrchestrationConfig = Schema.Struct({ modelSelection: ModelSelection, /** This participant's own access. Absent means the conversation's. */ access: Schema.optional(Schema.Literals(["read-only", "approval-required", "full-access"])), + /** A person chose this seat's model by hand, so it is never swapped without asking. */ + picked: Schema.optional(Schema.Boolean), + /** What the seat does in its team. A QA seat never stands in on a builder seat's model. */ + duty: Schema.optional(Schema.Literals(["build", "qa"])), + /** What a person agreed the seat runs on while its own model is limited. */ + substitute: Schema.optional(ModelSelection), }), ).check(Schema.isMinLength(2), Schema.isMaxLength(12)), /** When participants critique each other. Absent means the conversation's first message only. */ critique: Schema.optional(Schema.Literals(["first", "always", "never"])), + /** When a seat is limited. Absent means swap automatically. Read at the start of each turn. */ + limitedSeat: Schema.optional(DeliveryLimitedSeatPolicy), /** The access participants run with. Absent means read-only: what would change something is declined. */ access: Schema.optional(Schema.Literals(["approval-required", "full-access"])), /** The team participants take their roles from, when the conversation itself is bound to none. */ @@ -29,6 +42,10 @@ export const deliveryParticipantAccess = ( seat: string, ) => lineup.participants.find((item) => item.seat === seat)?.access ?? lineup.access ?? "read-only"; +export const deliveryLimitedSeatPolicy = ( + lineup: Pick, +): DeliveryLimitedSeatPolicy => lineup.limitedSeat ?? "swap"; + /** * The team a conversation was switched away from, so one click brings it back. * The lead model is what the thread itself ran while the team was on; restoring @@ -274,6 +291,48 @@ export const DeliverySetThreadLineupInput = Schema.Struct({ export type DeliverySetThreadLineupInput = typeof DeliverySetThreadLineupInput.Type; export const DeliveryThreadBindingInput = Schema.Struct({ threadId: ThreadId }); + +/** A seat, or the lead, whose model has reached its usage limit, and what could stand in. */ +export const DeliveryLimitedSeatNotice = Schema.Struct({ + /** The seat's name; null for the conversation's lead. */ + seat: Schema.NullOr(TrimmedNonEmptyString), + limited: Schema.Struct({ + instanceId: ProviderInstanceId, + model: TrimmedNonEmptyString, + resetAt: Schema.NullOr(IsoDateTime), + }), + /** + * `offered`: one click swaps to `substitute`. `none-free`: no favorite is free, so the seat + * waits. `swapped`: `substitute` stands in, for a lead in the thread `continuedIn`. + */ + state: Schema.Literals(["offered", "none-free", "swapped"]), + /** The first free favorite, or the model that stands in. Null when none is free. */ + substitute: Schema.NullOr(ModelSelection), + /** The thread a limited lead was handed on to. */ + continuedIn: Schema.optional(ThreadId), +}); +export type DeliveryLimitedSeatNotice = typeof DeliveryLimitedSeatNotice.Type; + +export const DeliveryLimitedSeatStatus = Schema.Struct({ + /** Null where this setting does not govern: an ordinary chat, or a board task's conversation. */ + policy: Schema.NullOr(DeliveryLimitedSeatPolicy), + notices: Schema.Array(DeliveryLimitedSeatNotice), +}); +export type DeliveryLimitedSeatStatus = typeof DeliveryLimitedSeatStatus.Type; + +/** Swaps a limited seat, or the lead when `seat` is null, to a favorite the status offered. */ +export const DeliveryLimitedSeatSwapInput = Schema.Struct({ + threadId: ThreadId, + seat: Schema.NullOr(TrimmedNonEmptyString), + modelSelection: ModelSelection, +}); +export type DeliveryLimitedSeatSwapInput = typeof DeliveryLimitedSeatSwapInput.Type; + +export const DeliveryLimitedSeatSwapResult = Schema.Struct({ + /** The thread the conversation continues in, when its lead was handed on. */ + continuedIn: Schema.NullOr(ThreadId), +}); +export type DeliveryLimitedSeatSwapResult = typeof DeliveryLimitedSeatSwapResult.Type; export type DeliveryThreadBindingInput = typeof DeliveryThreadBindingInput.Type; export class DeliveryError extends Schema.TaggedError()("DeliveryError", { diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 7e96ecb31f199..161522c300b3d 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -1015,6 +1015,14 @@ const TeamChatParticipation = Schema.Struct({ sourceRunId: RunId, stage: Schema.Literals(["contribution", "critique"]), seat: TrimmedNonEmptyString, + /** The seat's own model, when this turn runs on a substitute because that one was limited. */ + substituteFor: Schema.optional( + Schema.Struct({ + instanceId: ProviderInstanceId, + model: TrimmedNonEmptyString, + resetAt: Schema.NullOr(IsoDateTime), + }), + ), }); export const OrchestrationV2Subagent = Schema.Struct({ diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 48cfa729d179f..75f45273a5082 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -65,6 +65,9 @@ import { DeliveryActInput, DeliveryBindThreadInput, DeliverySetThreadLineupInput, + DeliveryLimitedSeatStatus, + DeliveryLimitedSeatSwapInput, + DeliveryLimitedSeatSwapResult, DeliveryError, DeliveryReadInput, DeliveryResponse, @@ -640,6 +643,8 @@ export const WS_METHODS = { deliveryArchivedBoardThreads: "delivery.archivedBoardThreads", deliveryReleaseThread: "delivery.releaseThread", deliverySetThreadLineup: "delivery.setThreadLineup", + deliveryLimitedSeats: "delivery.limitedSeats", + deliverySwapLimitedSeat: "delivery.swapLimitedSeat", scheduledTasksList: "scheduledTasks.list", scheduledTasksSubscribe: "scheduledTasks.subscribe", scheduledTasksUpsert: "scheduledTasks.upsert", @@ -1209,6 +1214,20 @@ const WsDeliverySetThreadLineupRpc = Rpc.make(WS_METHODS.deliverySetThreadLineup error: Schema.Union([EnvironmentAuthorizationError, DeliveryError]), }); +/** Which seats of a conversation are limited now, and what could stand in for each. */ +const WsDeliveryLimitedSeatsRpc = Rpc.make(WS_METHODS.deliveryLimitedSeats, { + payload: DeliveryThreadBindingInput, + success: DeliveryLimitedSeatStatus, + error: Schema.Union([EnvironmentAuthorizationError, DeliveryError]), +}); + +/** Swaps one limited seat, or hands a limited lead on to a linked thread. Safe to repeat. */ +const WsDeliverySwapLimitedSeatRpc = Rpc.make(WS_METHODS.deliverySwapLimitedSeat, { + payload: DeliveryLimitedSeatSwapInput, + success: DeliveryLimitedSeatSwapResult, + error: Schema.Union([EnvironmentAuthorizationError, DeliveryError]), +}); + /** Gives up a team choice whose setup never completed, so the thread can start without a team. */ const WsDeliveryReleaseThreadRpc = Rpc.make(WS_METHODS.deliveryReleaseThread, { payload: DeliveryThreadBindingInput, @@ -2727,6 +2746,8 @@ export const ForkWsRpcGroup = RpcGroup.make( WsDeliveryArchivedBoardThreadsRpc, WsDeliveryReleaseThreadRpc, WsDeliverySetThreadLineupRpc, + WsDeliveryLimitedSeatsRpc, + WsDeliverySwapLimitedSeatRpc, WsServerSubscribeCheckoutUpdateRpc, WsServerCheckCheckoutUpdateRpc, WsServerStartCheckoutUpdateRpc, diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 1fdbd017ede35..c30a87bb3de12 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -2001,6 +2001,8 @@ export const ServerSettingsPatch = Schema.Struct({ setModelFavorites: Schema.optionalKey( Schema.Array(Schema.Struct({ ...ModelFavorite.fields, favorite: Schema.Boolean })), ), + /** Puts these favorites first, in this order. Ones not listed keep their order after them. */ + setModelFavoriteOrder: Schema.optionalKey(ModelFavorites), setModelsHidden: Schema.optionalKey( Schema.Array(Schema.Struct({ ...ModelFavorite.fields, hidden: Schema.Boolean })), ), diff --git a/packages/shared/package.json b/packages/shared/package.json index a8246ace64855..83c2c179d4e3b 100644 --- a/packages/shared/package.json +++ b/packages/shared/package.json @@ -419,6 +419,10 @@ "types": "./src/usageFormat.ts", "import": "./src/usageFormat.ts" }, + "./limitedSeat": { + "types": "./src/limitedSeat.ts", + "import": "./src/limitedSeat.ts" + }, "./usageLimits": { "types": "./src/usageLimits.ts", "import": "./src/usageLimits.ts" diff --git a/packages/shared/src/limitedSeat.test.ts b/packages/shared/src/limitedSeat.test.ts new file mode 100644 index 0000000000000..bb13d1592ebe4 --- /dev/null +++ b/packages/shared/src/limitedSeat.test.ts @@ -0,0 +1,222 @@ +import { + DEFAULT_SERVER_SETTINGS, + ProjectId, + ProviderDriverKind, + ProviderInstanceId, + type ServerProvider, +} from "@t3tools/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + firstFreeFavorite, + type LimitedSeatFacts, + limitedSeatCandidates, + modelAccountFamily, + seatLimit, +} from "./limitedSeat.ts"; + +const now = Date.parse("2026-11-22T12:00:00.000Z"); +const later = "2026-11-22T17:00:00.000Z"; +const id = ProviderInstanceId.make; +const projectId = ProjectId.make("project"); + +function provider( + instanceId: string, + driver: string, + overrides: Partial = {}, +): ServerProvider { + return { + instanceId: id(instanceId), + driver: ProviderDriverKind.make(driver), + enabled: true, + installed: true, + version: null, + status: "ready", + auth: { status: "authenticated" }, + checkedAt: "2026-11-22T11:00:00.000Z", + models: [], + slashCommands: [], + skills: [], + ...overrides, + }; +} + +const exhausted: NonNullable = { + checkedAt: "2026-11-22T11:00:00.000Z", + windows: [ + { id: "primary", kind: "session", label: "5 hours", usedPercent: 100, resetsAt: later }, + ], +}; + +const favorite = (instanceId: string, model: string) => ({ provider: id(instanceId), model }); +const seat = (instanceId: string, model: string) => ({ instanceId: id(instanceId), model }); + +function facts( + overrides: Partial> & { + readonly favorites?: LimitedSeatFacts["settings"]["favorites"]; + } = {}, +): LimitedSeatFacts { + const providers = overrides.providers ?? [ + provider("claude", "claudeAgent", { usageLimits: exhausted }), + provider("codex", "codex"), + provider("kimi", "kimi"), + provider("deepseek", "deepseek"), + ]; + return { + now, + projectId, + threadLimits: [], + ...overrides, + providers, + settings: { + ...DEFAULT_SERVER_SETTINGS, + providerInstances: Object.fromEntries( + providers.map((entry) => [entry.instanceId, { driver: entry.driver, enabled: true }]), + ), + favorites: overrides.favorites ?? [ + favorite("claude", "claude-opus"), + favorite("codex", "gpt-astra"), + favorite("kimi", "kimi-k3"), + favorite("deepseek", "deepseek-v4"), + ], + }, + }; +} + +const limited = seat("claude", "claude-fable"); +const pick = (input: Partial[0]> = {}) => + firstFreeFavorite(limitedSeatCandidates({ facts: facts(), limited, inUse: [], ...input })); + +describe("the swap pool for a limited seat", () => { + it("reads a limit from the provider's windows and from a turn that failed on it", () => { + expect(seatLimit(facts(), limited)).toMatchObject({ resetAt: later }); + expect(seatLimit(facts(), seat("codex", "gpt-astra"))).toBeNull(); + const failed = facts({ threadLimits: [{ ...seat("codex", "gpt-astra"), resetAt: later }] }); + expect(seatLimit(failed, seat("codex", "gpt-astra"))).toMatchObject({ resetAt: later }); + // A window that has already reset no longer limits anything. + const reset = facts({ + threadLimits: [{ ...seat("codex", "gpt-astra"), resetAt: "2026-11-22T11:59:00.000Z" }], + }); + expect(seatLimit(reset, seat("codex", "gpt-astra"))).toBeNull(); + }); + + it("takes the first favorite in the person's order, and never a model outside Favorites", () => { + expect(pick()).toEqual(seat("codex", "gpt-astra")); + expect(pick({ facts: facts({ favorites: [] }) })).toBeNull(); + }); + + it.each([ + { + name: "one whose provider is not ready", + providers: { codex: { status: "error" as const } }, + skip: "unavailable", + }, + { + name: "one whose provider is signed out", + providers: { codex: { auth: { status: "unauthenticated" as const } } }, + skip: "unavailable", + }, + { + name: "one that is itself usage-limited", + providers: { codex: { usageLimits: exhausted } }, + skip: "limited", + }, + ])("skips $name", ({ providers, skip }) => { + const base = facts(); + const candidates = limitedSeatCandidates({ + facts: { + ...base, + providers: base.providers.map((entry) => ({ + ...entry, + ...(providers as Record>)[entry.instanceId], + })), + }, + limited, + inUse: [], + }); + expect(candidates.find((entry) => entry.instanceId === "codex")?.skip).toBe(skip); + expect(firstFreeFavorite(candidates)).toEqual(seat("kimi", "kimi-k3")); + }); + + it("skips a favorite turned off for the project", () => { + const base = facts(); + const candidates = limitedSeatCandidates({ + facts: { + ...base, + settings: { + ...base.settings, + projectSettingsOverrides: { + [projectId]: { providerInstances: { [id("codex")]: { enabled: false } } }, + }, + }, + }, + limited, + inUse: [], + }); + expect(candidates[1]?.skip).toBe("unavailable"); + }); + + it("skips the limited model's own account and its provider family", () => { + const candidates = limitedSeatCandidates({ + facts: facts({ + providers: [ + provider("claude", "claudeAgent", { usageLimits: exhausted }), + // Another harness on the same vendor, and a second sign-in to the same harness. + provider("pi", "pi"), + provider("claude-2", "claudeAgent"), + provider("codex", "codex"), + ], + favorites: [ + favorite("claude", "claude-opus"), + favorite("pi", "anthropic/claude-opus"), + favorite("claude-2", "claude-opus"), + favorite("codex", "gpt-astra"), + ], + }), + limited, + inUse: [], + }); + // The limited instance's own window already rules out its other models. + expect(candidates.map((entry) => entry.skip)).toEqual([ + "limited", + "same-account", + "same-account", + null, + ]); + }); + + it("skips a model another seat or the lead already runs", () => { + expect(pick({ inUse: [seat("codex", "gpt-astra")] })).toEqual(seat("kimi", "kimi-k3")); + }); + + it("keeps a QA seat off the builder's model, on any account", () => { + const candidates = limitedSeatCandidates({ + facts: facts(), + limited, + inUse: [], + builderModels: [seat("codex-other", "gpt-astra")], + }); + expect(candidates[1]?.skip).toBe("not-independent"); + expect(firstFreeFavorite(candidates)).toEqual(seat("kimi", "kimi-k3")); + }); + + it("finds none free when every favorite is skipped", () => { + expect( + pick({ + inUse: [ + seat("codex", "gpt-astra"), + seat("kimi", "kimi-k3"), + seat("deepseek", "deepseek-v4"), + ], + }), + ).toBeNull(); + }); + + it("names the family by the model's vendor, then by the harness", () => { + expect(modelAccountFamily("pi", "openai/gpt-6-astra")).toBe("openai"); + expect(modelAccountFamily("codex", "astra")).toBe("openai"); + expect(modelAccountFamily("opencode", "zai-coding-plan/glm-5.3")).toBe("zhipu"); + expect(modelAccountFamily("opencode", "fireworks/llama")).toBe("fireworks"); + expect(modelAccountFamily("hermes", "default")).toBe("driver:hermes"); + }); +}); diff --git a/packages/shared/src/limitedSeat.ts b/packages/shared/src/limitedSeat.ts new file mode 100644 index 0000000000000..54db7d1602395 --- /dev/null +++ b/packages/shared/src/limitedSeat.ts @@ -0,0 +1,244 @@ +import { + isProviderAvailable, + type ModelSelection, + type ProjectId, + type ProviderInstanceId, + type RunId, + resolveProjectProviderInstanceEnabled, + type ServerProvider, + type ServerSettings, + ThreadId, +} from "@t3tools/contracts"; + +import { exhaustedUsageWindow } from "./usageLimits.ts"; + +/** + * The thread a limited lead's run is handed on to. One per run, however often it is asked for, + * so its existence is how the server and the clients know a run was handed on. + */ +export const limitedLeadHandoffThreadId = (runId: RunId) => ThreadId.make(`limited-lead:${runId}`); + +/** A model as a seat runs it: on one provider instance. */ +export interface SeatModel { + readonly instanceId: ProviderInstanceId; + readonly model: string; +} + +/** A model a thread or one of its seats failed on with a usage limit that has not reset yet. */ +export interface SeatLimit extends SeatModel { + readonly resetAt: string | null; +} + +/** What T3 knows when it decides whether a seat is limited and what could stand in for it. */ +export interface LimitedSeatFacts { + readonly now: number; + readonly providers: ReadonlyArray; + readonly settings: Pick< + ServerSettings, + "favorites" | "providerInstances" | "projectSettingsOverrides" + >; + readonly projectId: ProjectId | null; + /** Limits read from turns that failed, which a provider's own status may not show. */ + readonly threadLimits: ReadonlyArray; +} + +const MODEL_FAMILIES: ReadonlyArray = [ + [/claude|anthropic/i, "anthropic"], + [/gpt|openai|codex|\bo\d\b/i, "openai"], + [/gemini|google/i, "google"], + [/grok|xai/i, "xai"], + [/kimi|moonshot/i, "moonshot"], + [/deepseek/i, "deepseek"], + [/glm|zai|z\.ai|zhipu/i, "zhipu"], +]; +const DRIVER_FAMILIES: Readonly> = { + claudeAgent: "anthropic", + codex: "openai", + grok: "xai", + kimi: "moonshot", + deepseek: "deepseek", +}; + +/** + * Whose usage a model draws on, as far as T3 can tell: the vendor its name shows, else the + * harness's own. T3 holds no account identity across providers, so this errs toward "the same". + */ +export function modelAccountFamily(driver: string | undefined, model: string): string { + const named = MODEL_FAMILIES.find(([pattern]) => pattern.test(model))?.[1]; + if (named) return named; + const vendor = model.includes("/") ? model.split("/")[0]?.toLowerCase() : undefined; + return vendor || (driver ? (DRIVER_FAMILIES[driver] ?? `driver:${driver}`) : "unknown"); +} + +const sameModel = (left: SeatModel, right: SeatModel) => + left.instanceId === right.instanceId && left.model === right.model; + +/** Why a seat's model cannot run now, or null when no limit is known. */ +export function seatLimit(facts: LimitedSeatFacts, seat: SeatModel): SeatLimit | null { + const provider = facts.providers.find((entry) => entry.instanceId === seat.instanceId); + const window = exhaustedUsageWindow(provider, facts.now, seat.model); + if (window) return { ...seat, resetAt: window.resetsAt ?? null }; + return ( + facts.threadLimits.find( + (limit) => + sameModel(limit, seat) && (limit.resetAt === null || Date.parse(limit.resetAt) > facts.now), + ) ?? null + ); +} + +export type LimitedSeatSkipReason = + | "unavailable" + | "limited" + | "same-account" + | "in-use" + | "not-independent"; + +export interface LimitedSeatCandidate extends SeatModel { + /** Null for a favorite that is free to stand in. */ + readonly skip: LimitedSeatSkipReason | null; +} + +/** + * The person's Favorites in their order, each free or skipped with its reason. Nothing outside + * Favorites is ever offered. The first free one is the substitute. + */ +export function limitedSeatCandidates(input: { + readonly facts: LimitedSeatFacts; + /** The model that reached its limit. */ + readonly limited: SeatModel; + /** What the other seats and the lead of the conversation run on. */ + readonly inUse: ReadonlyArray; + /** For a QA seat, what the builder seats run on; QA must not share a model with them. */ + readonly builderModels?: ReadonlyArray | undefined; +}): ReadonlyArray { + const { facts, limited } = input; + const providerOf = (instanceId: ProviderInstanceId) => + facts.providers.find((entry) => entry.instanceId === instanceId); + const limitedProvider = providerOf(limited.instanceId); + const limitedFamily = modelAccountFamily(limitedProvider?.driver, limited.model); + const reason = (candidate: SeatModel): LimitedSeatSkipReason | null => { + const provider = providerOf(candidate.instanceId); + if ( + !provider || + !provider.enabled || + !provider.installed || + provider.status !== "ready" || + provider.auth.status === "unauthenticated" || + provider.supportsSessions === false || + !isProviderAvailable(provider) || + !resolveProjectProviderInstanceEnabled(facts.settings, facts.projectId, candidate.instanceId) + ) + return "unavailable"; + if (seatLimit(facts, candidate)) return "limited"; + const sameAccount = + candidate.instanceId === limited.instanceId || + (provider.driver === limitedProvider?.driver && + provider.auth.email !== undefined && + provider.auth.email === limitedProvider.auth.email) || + modelAccountFamily(provider.driver, candidate.model) === limitedFamily; + if (sameAccount) return "same-account"; + if (input.inUse.some((used) => sameModel(used, candidate))) return "in-use"; + // The same model on another account is still the builder's model. + if (input.builderModels?.some((builder) => builder.model === candidate.model)) + return "not-independent"; + return null; + }; + return (facts.settings.favorites ?? []).map((favorite) => { + const candidate = { instanceId: favorite.provider, model: favorite.model }; + return { ...candidate, skip: reason(candidate) }; + }); +} + +/** The first free favorite, or null when none is free. */ +export const firstFreeFavorite = ( + candidates: ReadonlyArray, +): SeatModel | null => { + const free = candidates.find((candidate) => candidate.skip === null); + return free ? { instanceId: free.instanceId, model: free.model } : null; +}; + +export const seatModelOf = (selection: ModelSelection): SeatModel => ({ + instanceId: selection.instanceId, + model: selection.model, +}); + +/** A seat of a conversation, as the limited-seat rule reads it. */ +export interface LimitedSeatRosterSeat { + readonly seat: string; + readonly modelSelection: ModelSelection; + readonly duty?: "build" | "qa" | undefined; +} + +/** + * What a limited seat stands in on by agreement: the substitute a person agreed to for it, where + * the seat asks before it swaps. Undefined while its own model is free, or where it swaps unasked. + * The notice, the swap and the turn all read another seat through this, so they agree on what is + * in use. + */ +export function agreedStandIn(input: { + readonly facts: LimitedSeatFacts; + readonly policy: "swap" | "ask" | "skip"; + readonly seat: LimitedSeatRosterSeat & { + readonly picked?: boolean | undefined; + readonly substitute?: ModelSelection | undefined; + }; +}): ModelSelection | undefined { + const { facts, policy, seat } = input; + if (seat.substitute === undefined || policy === "skip") return undefined; + if (policy !== "ask" && seat.picked !== true) return undefined; + return seatLimit(facts, seatModelOf(seat.modelSelection)) === null ? undefined : seat.substitute; +} + +/** The pool for one seat of a conversation: every other seat's model and the lead's are in use. */ +export function limitedSeatPool(input: { + readonly facts: LimitedSeatFacts; + readonly roster: ReadonlyArray; + readonly lead: ModelSelection; + readonly seat: Seat; + /** What a seat runs on this turn, when a substitute already stands in for it. */ + readonly runsOn?: (seat: Seat) => ModelSelection; +}): ReadonlyArray { + const runsOn = input.runsOn ?? ((seat: Seat) => seat.modelSelection); + return limitedSeatCandidates({ + facts: input.facts, + limited: seatModelOf(input.seat.modelSelection), + inUse: [ + seatModelOf(input.lead), + ...input.roster + .filter((other) => other.seat !== input.seat.seat) + .map((other) => seatModelOf(runsOn(other))), + ], + builderModels: + input.seat.duty === "qa" + ? input.roster + .flatMap((other) => + other.duty === "build" ? [other.modelSelection, runsOn(other)] : [], + ) + .map(seatModelOf) + : undefined, + }); +} + +/** The pool for the lead of a conversation: every seat's model is in use. */ +export const limitedLeadPool = (input: { + readonly facts: LimitedSeatFacts; + readonly roster: ReadonlyArray; + readonly lead: ModelSelection; +}): ReadonlyArray => + limitedSeatCandidates({ + facts: input.facts, + limited: seatModelOf(input.lead), + inUse: input.roster.map((seat) => seatModelOf(seat.modelSelection)), + }); + +/** Whether a model is among the free candidates of a pool. */ +export const isFreeCandidate = ( + pool: ReadonlyArray, + model: SeatModel, +): boolean => + pool.some( + (candidate) => + candidate.skip === null && + candidate.instanceId === model.instanceId && + candidate.model === model.model, + ); diff --git a/packages/shared/src/serverSettings.test.ts b/packages/shared/src/serverSettings.test.ts index 9836fe10fc77f..c03bab0ae54eb 100644 --- a/packages/shared/src/serverSettings.test.ts +++ b/packages/shared/src/serverSettings.test.ts @@ -1037,6 +1037,22 @@ describe("synchronized model preferences", () => { ).toEqual([]); }); + it("reorders favorites without dropping one another client added or reviving a removed one", () => { + const favorite = (model: string) => ({ provider, model }); + const three = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { + setModelFavorites: ["sol", "astra", "luna"].map((model) => ({ + provider, + model, + favorite: true, + })), + }); + // This client last saw sol and astra, plus terra, which was unstarred since. + const reordered = applyServerSettingsPatch(three, { + setModelFavoriteOrder: [favorite("astra"), favorite("terra"), favorite("sol")], + }); + expect(reordered.favorites).toEqual([favorite("astra"), favorite("sol"), favorite("luna")]); + }); + it("keeps the same model on different provider instances as separate favorites", () => { const otherProvider = ProviderInstanceId.make("codex_personal"); const first = applyServerSettingsPatch(DEFAULT_SERVER_SETTINGS, { diff --git a/packages/shared/src/serverSettings.ts b/packages/shared/src/serverSettings.ts index 3085c1fd1b9a1..4409ebd3d362b 100644 --- a/packages/shared/src/serverSettings.ts +++ b/packages/shared/src/serverSettings.ts @@ -392,6 +392,7 @@ export function applyServerSettingsPatch( const { migrateModelPreferences, setModelFavorites, + setModelFavoriteOrder, setModelsHidden, setProviderModelOrder, providerModelPreferences, @@ -452,7 +453,7 @@ export function applyServerSettingsPatch( : undefined; const initialFavorites = patch.favorites ?? current.favorites ?? migrateModelPreferences?.favorites ?? null; - const favorites = + const toggledFavorites = setModelFavorites?.reduce( (current, change) => { const exists = current.some( @@ -468,6 +469,23 @@ export function applyServerSettingsPatch( }, [...(initialFavorites ?? [])], ) ?? initialFavorites; + // Only an order is sent, so a favorite another client added meanwhile is kept, not dropped. + const favorites = + setModelFavoriteOrder && toggledFavorites + ? [ + ...setModelFavoriteOrder.flatMap((entry) => + toggledFavorites.filter( + (favorite) => favorite.provider === entry.provider && favorite.model === entry.model, + ), + ), + ...toggledFavorites.filter( + (favorite) => + !setModelFavoriteOrder.some( + (entry) => entry.provider === favorite.provider && entry.model === favorite.model, + ), + ), + ] + : toggledFavorites; const initialModelPreferences = providerModelPreferences ?? current.providerModelPreferences ??