From 886260b79a806b371c3041af69d10ad3183f9d32 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 18:07:25 -0500 Subject: [PATCH] feat(antigravity): add composer prompt suggestions and provider toggles Antigravity's CLI does not emit native follow-up prompt suggestions, and the Claude and Codex suggestion switches previously lived under Settings -> Threads. This adds background composer prompt suggestions for Antigravity via an isolated, tool-free ACP turn preferring Gemini Hydrogen (then non-lite Gemini Flash, then the thread model) at low thinking, guarded by a per-model 90% usage ceiling and cancelled immediately on new turns, interrupts, or session stops. It also moves Claude and Codex suggestion toggles into a new Suggestions section on Settings -> Providers alongside Antigravity, showing switches only for enabled providers and preserving moved place links. --- apps/server/evals/toolUse/runCase.ts | 1 + apps/server/integration/replay/runReplay.ts | 5 +- apps/server/src/guide/topics.ts | 2 +- .../src/provider/Drivers/AntigravityDriver.ts | 69 ++++- .../provider/Layers/CodexPromptSuggestions.ts | 88 +------ .../src/provider/acp/AcpAdapter.test.ts | 227 ++++++++++++++++ apps/server/src/provider/acp/AcpAdapter.ts | 244 ++++++++++++++++-- .../src/provider/acp/AcpProviderDriver.ts | 27 +- .../provider/acp/AcpTextGeneration.test.ts | 82 +++++- .../src/provider/acp/AcpTextGeneration.ts | 194 +++++++++++++- .../AntigravityPromptSuggestions.test.ts | 182 +++++++++++++ .../AntigravityPromptSuggestions.ts | 149 +++++++++++ apps/server/src/provider/promptSuggestions.ts | 155 +++++++++++ apps/web/src/components/chat/ChatComposer.tsx | 12 +- .../settings/ProviderSuggestionsSection.tsx | 126 +++++++++ .../settings/SettingsPanels.browser.tsx | 72 ++++++ .../components/settings/SettingsPanels.tsx | 12 +- .../components/settings/ThreadsSettings.tsx | 68 ----- .../settings/settingsPlaceAvailability.tsx | 53 +++- .../settings/settingsRowRegistry.tsx | 13 +- packages/contracts/src/settings.ts | 9 + packages/shared/src/appPlaces.test.ts | 6 + packages/shared/src/appPlaces.ts | 32 ++- packages/shared/src/model.ts | 5 +- packages/shared/src/usageLimits.test.ts | 43 +++ packages/shared/src/usageLimits.ts | 30 +++ 26 files changed, 1713 insertions(+), 193 deletions(-) create mode 100644 apps/server/src/provider/antigravity/AntigravityPromptSuggestions.test.ts create mode 100644 apps/server/src/provider/antigravity/AntigravityPromptSuggestions.ts create mode 100644 apps/server/src/provider/promptSuggestions.ts create mode 100644 apps/web/src/components/settings/ProviderSuggestionsSection.tsx diff --git a/apps/server/evals/toolUse/runCase.ts b/apps/server/evals/toolUse/runCase.ts index ad4b949d1..b9da11f99 100644 --- a/apps/server/evals/toolUse/runCase.ts +++ b/apps/server/evals/toolUse/runCase.ts @@ -54,6 +54,7 @@ const decodeCodexSettings = Schema.decodeEffect(CodexSettings); */ export const EVAL_SERVER_SETTINGS = { codexSuggestions: false, + antigravitySuggestions: false, enableAgentPages: false, enableCommandRequests: false, } as const; diff --git a/apps/server/integration/replay/runReplay.ts b/apps/server/integration/replay/runReplay.ts index 21d227b41..8b6289acb 100644 --- a/apps/server/integration/replay/runReplay.ts +++ b/apps/server/integration/replay/runReplay.ts @@ -36,7 +36,10 @@ const decodeCodexSettings = Schema.decodeEffect(CodexSettings); const decodeClaudeSettings = Schema.decodeEffect(ClaudeSettings); /** Settings that would make our code send requests at times a replay can't reproduce. */ -const REPLAY_SERVER_SETTINGS = { codexSuggestions: false } as const; +const REPLAY_SERVER_SETTINGS = { + codexSuggestions: false, + antigravitySuggestions: false, +} as const; type ProviderMode = | { readonly kind: "replay"; readonly transcript: Transcript } diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 5aae2bc98..031cbf953 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -58,7 +58,7 @@ The agent and model a new thread starts with is {place:threads.agent}. You can s While an agent works, the arrow beside the send button picks how a message goes: Steer now adds it to the reply in progress, Send when done holds it for the next one, and the choice sticks. Enter sends that way; Cmd+Enter (Ctrl+Enter on Windows and Linux) sends that one message the other way. -After a reply to your message, Claude or Codex can suggest what you might send next: gray text in the empty message box, taken with Tab (Use on a phone), hidden with Escape. Claude makes its own and skips them when you're on track to run out of usage early, unless {place:threads.claudeSuggestions} is on. Codex's are made by Threadlines with one extra Codex answer each, only after messages you sent, never while a usage limit is 90% used, and {place:threads.codexSuggestions} turns them off. +After a reply to your message, Claude, Codex, or Antigravity can suggest what you might send next: gray text in the empty message box, taken with Tab (Use on a phone), hidden with Escape. Claude makes its own and skips them when you're on track to run out of usage early, unless {place:providers.claudeSuggestions} is on. Codex's are made by Threadlines with one extra Codex answer each, only after messages you sent, never while a usage limit is 90% used, and {place:providers.codexSuggestions} turns them off. Antigravity's are made by Threadlines with a short isolated answer on a fast Gemini model (preferring Gemini Hydrogen, then Flash, at low thinking), only after messages you sent, never while that model's usage limit is 90% used, and {place:providers.antigravitySuggestions} turns them off. A goal (type /goal and what to reach in the message box) keeps the agent working toward it across turns; the bar above the message box shows it, with pause, resume and clear. A Codex goal pauses by itself while the thread waits for your answer on a card or for threads it started to report back, so it doesn't spend turns asking whether you answered yet; the bar says why, and it carries on once the wait is over. Pausing, resuming or clearing it yourself in between is yours to keep. Claude's goals have no pause and carry on as before. diff --git a/apps/server/src/provider/Drivers/AntigravityDriver.ts b/apps/server/src/provider/Drivers/AntigravityDriver.ts index c4002a658..57d138561 100644 --- a/apps/server/src/provider/Drivers/AntigravityDriver.ts +++ b/apps/server/src/provider/Drivers/AntigravityDriver.ts @@ -10,12 +10,15 @@ */ import { join } from "node:path"; +import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; +import * as FileSystem from "effect/FileSystem"; import * as Option from "effect/Option"; import { HttpClient } from "effect/http"; import { ChildProcessSpawner } from "effect/process"; import { ServerConfig } from "../../config.ts"; +import { ServerSettingsService } from "../../serverSettings.ts"; import { ANTIGRAVITY_DRIVER_KIND, ANTIGRAVITY_PRESENTATION, @@ -23,6 +26,12 @@ import { validateAntigravityRuntime, } from "../acp/AntigravityAcpSupport.ts"; import { type AcpProviderDriverEnv, makeAcpProviderDriver } from "../acp/AcpProviderDriver.ts"; +import { sampleAcpPromptSuggestion } from "../acp/AcpTextGeneration.ts"; +import { + isAntigravitySuggestionUsageNearLimit, + selectAntigravitySuggestionTarget, +} from "../antigravity/AntigravityPromptSuggestions.ts"; +import { buildTranscriptPromptSuggestionPrompt } from "../promptSuggestions.ts"; import { antigravityReleaseFor } from "../antigravity/AntigravityRelease.ts"; import { type AntigravityReleaseSource, @@ -53,7 +62,7 @@ import type { ProviderDriver } from "../ProviderDriver.ts"; import { AntigravitySettings } from "@threadlines/contracts"; import * as Schema from "effect/Schema"; -export type AntigravityDriverEnv = AcpProviderDriverEnv; +export type AntigravityDriverEnv = AcpProviderDriverEnv | ServerSettingsService; /** Linux's C library: Alpine and other musl systems get Google's musl build. */ function hostLibc(): "glibc" | "musl" { @@ -157,7 +166,63 @@ export const AntigravityDriver: ProviderDriver { + const isAllowed = (targetModelName: string | undefined) => + Effect.gen(function* () { + const on = yield* serverSettings.getSettings.pipe( + Effect.map((current) => current.antigravitySuggestions), + Effect.orElseSucceed(() => false), + ); + if (!on) return false; + const current = yield* getSnapshot; + return !isAntigravitySuggestionUsageNearLimit( + current.accountUsage, + targetModelName, + yield* Clock.currentTimeMillis, + ); + }); + return Effect.succeed({ + shouldSuggest: (model) => + Effect.gen(function* () { + const current = yield* getSnapshot; + const target = selectAntigravitySuggestionTarget(current.models, model); + return yield* isAllowed(target.modelName); + }), + sample: ({ cwd, model, messages }) => + Effect.gen(function* () { + const prompt = buildTranscriptPromptSuggestionPrompt(messages); + if (prompt === undefined) return undefined; + // Select and quota-check one target from a single snapshot so + // a catalog refresh cannot switch models between check and call. + const current = yield* getSnapshot; + const target = selectAntigravitySuggestionTarget(current.models, model); + if (!(yield* isAllowed(target.modelName))) return undefined; + let checkedModelName = target.modelName; + const sampled = yield* sampleAcpPromptSuggestion({ + descriptor, + settings: effectiveSettings, + environment, + commandSpawner, + fileSystem, + cwd, + prompt, + model: target.model, + options: target.options, + allowLiveModel: ({ name }) => { + checkedModelName = name; + return isAllowed(name); + }, + }); + if (sampled === undefined) return undefined; + return (yield* isAllowed(checkedModelName)) ? sampled : undefined; + }), + }); + }, + }).create(input); usage.attach(instance.snapshot); const builtEnvironment = providerInstanceEnvironmentKey(input.environment); const authFlows = makeAntigravityAuthFlows({ diff --git a/apps/server/src/provider/Layers/CodexPromptSuggestions.ts b/apps/server/src/provider/Layers/CodexPromptSuggestions.ts index 4b1a712d3..e6e923432 100644 --- a/apps/server/src/provider/Layers/CodexPromptSuggestions.ts +++ b/apps/server/src/provider/Layers/CodexPromptSuggestions.ts @@ -3,85 +3,25 @@ * composer, taken with Tab), made by Threadlines since Codex makes none of its * own: after a turn the user started, one `thread/sample` answer from a hidden * copy of the thread (CodexSessionRuntime.sampleThread) reusing its cached - * context. This module holds what is asked and what of the answer is kept. + * context. Shared prompt, sanitizer, and effort selection live in + * `provider/promptSuggestions.ts`. * * @module provider/Layers/CodexPromptSuggestions */ -import type { ServerProviderModel } from "@threadlines/contracts"; -import { findReasoningOptionDescriptor } from "@threadlines/shared/model"; +import { + PROMPT_SUGGESTION_INSTRUCTIONS, + PROMPT_SUGGESTION_USAGE_CEILING_PERCENT, + modelReasoningEfforts, + sanitizePromptSuggestion, + selectSuggestionEffort, +} from "../promptSuggestions.ts"; /** What the hidden copy is asked (Codex takes at most 4,000 bytes). */ -export const CODEX_SUGGESTION_PROMPT = `Stop being the assistant for a moment. Predict the next message the user will type in this conversation, so it can be offered in their message box. - -Read what they asked for and how the last reply ended. Suggest what they would most likely send next, in their own words and style: a next step, a yes to an option the reply offered, a request to run, check, or fix something. Never suggest thanks, praise, or comments on the reply, and never speak as the assistant. - -If there is no clear next message, reply with nothing. Otherwise reply with only the message: one line, at most 12 words, no quotes.`; +export const CODEX_SUGGESTION_PROMPT = PROMPT_SUGGESTION_INSTRUCTIONS; /** No suggestions while any plan-wide usage window is this far used. */ -export const CODEX_SUGGESTION_USAGE_CEILING_PERCENT = 90; - -/** - * The reasoning a suggestion asks for, best first, among the levels a model - * lists: the answer is a dozen words, and the lowest levels can read thin. - */ -const SUGGESTION_EFFORTS = ["low", "minimal", "medium", "none"] as const; - -const MAX_SUGGESTION_CHARS = 120; -const MAX_SUGGESTION_WORDS = 20; -const QUOTE_PAIRS: ReadonlyArray = [ - ['"', '"'], - ["'", "'"], - ["“", "”"], - ["‘", "’"], - ["`", "`"], -]; -const NO_SUGGESTION = /^\(?(?:none|nothing|no suggestion|n\/a)\)?\.?$/iu; - -/** - * The suggestion in a sample's answer, or undefined when it isn't one: no - * text, more than one line, too long for the box's one line, or a word for - * "nothing". Quotes the model wrapped it in come off. - */ -export function codexSuggestionFromSample(text: string | null | undefined): string | undefined { - let line = text?.trim() ?? ""; - for (const [open, close] of QUOTE_PAIRS) { - if (line.length > 1 && line.startsWith(open) && line.endsWith(close)) { - line = line.slice(open.length, -close.length).trim(); - break; - } - } - if (line.length === 0 || /[\r\n]/u.test(line) || NO_SUGGESTION.test(line)) return undefined; - if (line.length > MAX_SUGGESTION_CHARS) return undefined; - if (line.split(/\s+/u).length > MAX_SUGGESTION_WORDS) return undefined; - return line; -} +export const CODEX_SUGGESTION_USAGE_CEILING_PERCENT = PROMPT_SUGGESTION_USAGE_CEILING_PERCENT; -/** - * The reasoning effort to ask a sample for, from the levels the thread's - * model lists; none (the thread's own) when it lists none of the light ones - * or isn't known. Codex applies it only where the model can change effort - * without losing the cache. - */ -export function codexSuggestionEffort( - modelEfforts: ReadonlyArray | undefined, -): string | undefined { - if (modelEfforts === undefined) return undefined; - return SUGGESTION_EFFORTS.find((effort) => modelEfforts.includes(effort)); -} - -/** - * The reasoning levels a model lists, from the instance's catalog; the - * catalog's default model stands for a turn that named none. Undefined for a - * model the catalog doesn't know. - */ -export function modelReasoningEfforts( - models: ReadonlyArray, - model: string | undefined, -): ReadonlyArray | undefined { - const entry = - model === undefined - ? models.find((candidate) => candidate.isDefault === true) - : models.find((candidate) => candidate.slug === model); - const descriptor = findReasoningOptionDescriptor(entry?.capabilities?.optionDescriptors ?? []); - return descriptor?.options.map((option) => option.id); -} +export const codexSuggestionFromSample = sanitizePromptSuggestion; +export const codexSuggestionEffort = selectSuggestionEffort; +export { modelReasoningEfforts }; diff --git a/apps/server/src/provider/acp/AcpAdapter.test.ts b/apps/server/src/provider/acp/AcpAdapter.test.ts index 22d41d5b5..ae1dd716f 100644 --- a/apps/server/src/provider/acp/AcpAdapter.test.ts +++ b/apps/server/src/provider/acp/AcpAdapter.test.ts @@ -8,6 +8,7 @@ import * as NodeServices from "@effect/platform-node/NodeServices"; import { assert, it } from "@effect/vitest"; import * as Context from "effect/Context"; import * as Deferred from "effect/Deferred"; +import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; import { mcpSessionRegistry } from "../../mcp/McpSessionRegistry.ts"; import * as Fiber from "effect/Fiber"; @@ -2161,3 +2162,229 @@ it("names an edit's files relative to the session, whichever way the agent wrote { path: "b.ts", kind: "add", additions: 1, deletions: 0 }, ]); }); + +it.effect( + "emits prompt suggestions after completed user turns, skips non-user turns, and drops stale suggestions when a new turn starts", + () => + Effect.gen(function* () { + const mockBinary = yield* Effect.promise(() => + makeMockAgentWrapper({ + T3_ACP_PROMPT_RESPONSE_TEXT: "Done! Want me to run the browser suite next?", + }), + ); + const sampleStarted = yield* Deferred.make(); + const releaseBlockedSample = yield* Deferred.make(); + let blockNextSample = false; + const seenBatches: Array> = + []; + + const adapter = yield* makeAcpAdapter( + CURSOR_ACP_DESCRIPTOR, + decodeCursorSettings({ enabled: true, binaryPath: mockBinary }), + { + promptSuggestions: { + shouldSuggest: () => Effect.succeed(true), + sample: ({ messages }) => + Effect.gen(function* () { + seenBatches.push(messages); + if (blockNextSample) { + yield* Deferred.succeed(sampleStarted, undefined); + yield* Deferred.await(releaseBlockedSample); + return "Stale suggestion that must be dropped"; + } + return ' "Run the browser suite." '; + }), + }, + }, + ); + + const events = yield* Queue.unbounded(); + const allEvents: Array = []; + const eventFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => + Effect.sync(() => { + allEvents.push(event); + }).pipe(Effect.andThen(Queue.offer(events, event)), Effect.asVoid), + ).pipe(Effect.forkScoped); + + const threadId = ThreadId.make("acp-prompt-suggestions-thread"); + yield* adapter.startSession({ + provider: ProviderDriverKind.make("cursor"), + threadId, + cwd: process.cwd(), + runtimeMode: "full-access", + }); + + // 1. User-originated turn completes -> emits sanitized prompt suggestion. + const firstTurn = yield* adapter.sendTurn({ + threadId, + input: "Fix the sidebar spacing", + suggestNextMessage: true, + }); + + const waitForEvent = (predicate: (event: ProviderRuntimeEvent) => boolean) => + Effect.gen(function* () { + while (true) { + const next = yield* Queue.take(events); + if (predicate(next)) return next; + } + }).pipe(Effect.timeout("5 seconds")); + + const suggestionEvent = yield* waitForEvent( + (event) => + event.type === "turn.prompt-suggestion.updated" && event.turnId === firstTurn.turnId, + ); + assert.equal(suggestionEvent.type, "turn.prompt-suggestion.updated"); + if (suggestionEvent.type === "turn.prompt-suggestion.updated") { + assert.equal(suggestionEvent.payload.suggestion, "Run the browser suite."); + } + assert.deepEqual(seenBatches[0], [ + { role: "user", text: "Fix the sidebar spacing" }, + { role: "assistant", text: "Done! Want me to run the browser suite next?" }, + ]); + + // 2. Non-user turn (suggestNextMessage omitted) -> no suggestion sampled. + const secondTurn = yield* adapter.sendTurn({ + threadId, + input: "Background check", + }); + yield* waitForEvent( + (event) => event.type === "turn.completed" && event.turnId === secondTurn.turnId, + ); + assert.equal(seenBatches.length, 1); + + // 3. Stale suggestion cancelled when a newer turn starts before it resolves. + blockNextSample = true; + const thirdTurn = yield* adapter.sendTurn({ + threadId, + input: "Check lint too", + suggestNextMessage: true, + }); + yield* Deferred.await(sampleStarted).pipe(Effect.timeout("5 seconds")); + blockNextSample = false; + + const fourthTurn = yield* adapter.sendTurn({ + threadId, + input: "Actually skip lint and ship", + suggestNextMessage: true, + }); + yield* Deferred.succeed(releaseBlockedSample, undefined); + + const fourthSuggestion = yield* waitForEvent( + (event) => + event.type === "turn.prompt-suggestion.updated" && event.turnId === fourthTurn.turnId, + ); + assert.equal(fourthSuggestion.type, "turn.prompt-suggestion.updated"); + // Make sure the third turn's blocked suggestion never arrived. + assert.equal( + allEvents.some( + (event) => + event.type === "turn.prompt-suggestion.updated" && event.turnId === thirdTurn.turnId, + ), + false, + ); + + yield* adapter.stopSession(threadId); + yield* Fiber.interrupt(eventFiber); + }).pipe( + Effect.scoped, + Effect.provide( + ServerConfig.layerTest(process.cwd(), { + prefix: "threadlines-acp-suggestions-test-", + }).pipe(Layer.provideMerge(NodeServices.layer)), + ), + ), +); + +it.effect( + "does not sample a prompt suggestion when a turn-machine turn is interrupted while reading its outcome", + () => + Effect.gen(function* () { + const mockBinary = yield* Effect.promise(() => + makeMockAgentWrapper({ + T3_ACP_PROMPT_RESPONSE_TEXT: "Finished the refactor.", + }), + ); + const outcomeReadReached = yield* Deferred.make(); + const releaseOutcomeRead = yield* Deferred.make(); + let sampleCalls = 0; + + const adapter = yield* makeAcpAdapter( + { + ...CURSOR_ACP_DESCRIPTOR, + turnMachine: { + workAfterPrompt: () => undefined, + steer: false, + silentLimit: Duration.minutes(5), + }, + }, + decodeCursorSettings({ enabled: true, binaryPath: mockBinary }), + { + turnMachineSeams: (seam) => + seam.point === "outcomeRead" + ? Deferred.succeed(outcomeReadReached, undefined).pipe( + Effect.andThen(Deferred.await(releaseOutcomeRead)), + ) + : Effect.void, + promptSuggestions: { + shouldSuggest: () => Effect.succeed(true), + sample: () => + Effect.sync(() => { + sampleCalls += 1; + return "Should not run after interrupt"; + }), + }, + }, + ); + + const events = yield* Queue.unbounded(); + const allEvents: Array = []; + const eventFiber = yield* Stream.runForEach(adapter.streamEvents, (event) => + Effect.sync(() => { + allEvents.push(event); + }).pipe(Effect.andThen(Queue.offer(events, event)), Effect.asVoid), + ).pipe(Effect.forkScoped); + + const threadId = ThreadId.make("acp-machine-interrupt-suggestion-thread"); + yield* adapter.startSession({ + provider: ProviderDriverKind.make("cursor"), + threadId, + cwd: process.cwd(), + runtimeMode: "full-access", + }); + + const turn = yield* adapter.sendTurn({ + threadId, + input: "Refactor the helper", + suggestNextMessage: true, + }); + + // Hold the turn at outcomeRead, interrupt it, then let the answered + // outcome settle as completed. The interrupt must suppress suggestions. + yield* Deferred.await(outcomeReadReached).pipe(Effect.timeout("5 seconds")); + yield* adapter.interruptTurn(threadId); + yield* Deferred.succeed(releaseOutcomeRead, undefined); + + yield* Effect.gen(function* () { + while (true) { + const next = yield* Queue.take(events); + if (next.type === "turn.completed" && next.turnId === turn.turnId) return; + } + }).pipe(Effect.timeout("5 seconds")); + + yield* adapter.stopSession(threadId); + yield* Fiber.interrupt(eventFiber); + + assert.equal(sampleCalls, 0); + assert.equal( + allEvents.some((event) => event.type === "turn.prompt-suggestion.updated"), + false, + ); + }).pipe( + Effect.scoped, + Effect.provide( + ServerConfig.layerTest(process.cwd(), { + prefix: "threadlines-acp-machine-suggestions-test-", + }).pipe(Layer.provideMerge(NodeServices.layer)), + ), + ), +); diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index c748e2733..5bc646f78 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -97,6 +97,13 @@ import { steerRejectedError, } from "../Errors.ts"; import { buildFileAttachmentNote } from "../fileAttachmentPrompt.ts"; +import { + appendTailCapped, + PROMPT_SUGGESTION_MAX_CHARS_PER_MESSAGE, + PROMPT_SUGGESTION_MAX_MESSAGES, + type PromptSuggestionMessage, + sanitizePromptSuggestion, +} from "../promptSuggestions.ts"; import { type EventNdjsonLogger, makeEventNdjsonLogger } from "../Layers/EventNdjsonLogger.ts"; import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; import { @@ -248,6 +255,19 @@ export interface AcpAdapterOptions { ) => Effect.Effect; /** The skills the provider status lists, by name: a typed `/name` runs one. */ readonly skillNames?: Effect.Effect>; + /** + * Optional next-message prompt suggestion sampler (gray composer hint, taken + * with Tab). Run asynchronously after completed user-originated turns, never + * in side/lockdown sessions, and cancelled whenever a new turn or stop begins. + */ + readonly promptSuggestions?: { + readonly shouldSuggest: (model: string | undefined) => Effect.Effect; + readonly sample: (input: { + readonly cwd: string; + readonly model: string | undefined; + readonly messages: ReadonlyArray; + }) => Effect.Effect; + }; /** Tests only: holds the turn machine's driver up at its seams (`AcpTurnMachineSeam`). */ readonly turnMachineSeams?: (seam: AcpTurnMachineSeam) => Effect.Effect; } @@ -296,6 +316,14 @@ interface AcpSessionContext { activeTurnId: TurnId | undefined; /** Head of the current turn's assistant text, kept for plan-gate detection. */ activeTurnText: string; + /** Tail of the current turn's assistant text, kept for prompt suggestions. */ + activeTurnReplyTail: string; + /** Rolling recent user and assistant messages, for isolated prompt suggestions. */ + readonly recentMessages: Array; + /** In-flight prompt suggestion fiber for the last completed turn. */ + suggestionFiber: Fiber.Fiber | undefined; + /** Incremented on every turn start, interrupt, or stop so stale suggestions drop. */ + suggestionGeneration: number; /** Last provider status this turn (fx rate-limit retries etc.), for failure detail. */ lastProviderStatus: string | undefined; /** Last context fill reported, so repeated identical `usage_update`s stay quiet. */ @@ -447,6 +475,8 @@ interface AcpMachineSession { { readonly prompt: AcpMachinePrompt; readonly messageId?: string; + readonly userMessageText?: string; + readonly suggestNextMessage?: boolean; readonly planMode: AcpPromptPlanMode | undefined; readonly reply: Deferred.Deferred; } @@ -467,6 +497,8 @@ interface AcpMachineSession { readonly model: string | undefined; readonly resolvedModel: string | undefined; readonly planMode: AcpPromptPlanMode | undefined; + readonly suggestNextMessage: boolean; + readonly suggestionGeneration: number; } >; readonly timers: Map>; @@ -1074,6 +1106,7 @@ export function makeAcpAdapter( const resetTurnState = (ctx: AcpSessionContext) => { ctx.lastPlanFingerprint = undefined; ctx.activeTurnText = ""; + ctx.activeTurnReplyTail = ""; ctx.lastProviderStatus = undefined; ctx.planMarkdown = undefined; ctx.promptOutcome = undefined; @@ -1081,6 +1114,87 @@ export function makeAcpAdapter( ctx.costReportedThisTurn = false; }; + const pushRecentMessage = ( + ctx: AcpSessionContext, + role: PromptSuggestionMessage["role"], + rawText: string, + ) => { + const trimmed = rawText.trim(); + if (trimmed.length === 0) return; + const text = + trimmed.length <= PROMPT_SUGGESTION_MAX_CHARS_PER_MESSAGE + ? trimmed + : trimmed.slice(trimmed.length - PROMPT_SUGGESTION_MAX_CHARS_PER_MESSAGE); + ctx.recentMessages.push({ role, text }); + if (ctx.recentMessages.length > PROMPT_SUGGESTION_MAX_MESSAGES) { + ctx.recentMessages.splice(0, ctx.recentMessages.length - PROMPT_SUGGESTION_MAX_MESSAGES); + } + }; + + /** Cancels any in-flight suggestion for this session because the thread moved on. */ + const dropSuggestion = (ctx: AcpSessionContext) => + Effect.suspend(() => { + ctx.suggestionGeneration += 1; + const fiber = ctx.suggestionFiber; + ctx.suggestionFiber = undefined; + return fiber ? Fiber.interrupt(fiber).pipe(Effect.asVoid) : Effect.void; + }); + + /** Samples the user's likely next message in the background after a completed user turn. */ + const startSuggestion = ( + ctx: AcpSessionContext, + promptSuggestions: NonNullable["promptSuggestions"]>, + input: { + readonly turnId: TurnId; + readonly model: string | undefined; + readonly completedEventId: EventId; + }, + ) => + Effect.gen(function* () { + yield* dropSuggestion(ctx); + if (ctx.stopped || ctx.lockdown !== undefined || ctx.recentMessages.length === 0) return; + const generation = ctx.suggestionGeneration; + const messages = [...ctx.recentMessages]; + const fiber = yield* Effect.gen(function* () { + if (!(yield* promptSuggestions.shouldSuggest(input.model))) return; + if (ctx.stopped || ctx.suggestionGeneration !== generation) return; + const sampled = yield* promptSuggestions.sample({ + cwd: ctx.session.cwd ?? ctx.cwdRoots[0] ?? process.cwd(), + model: input.model, + messages, + }); + const suggestion = sanitizePromptSuggestion(sampled); + if ( + suggestion === undefined || + ctx.stopped || + ctx.suggestionGeneration !== generation || + !(yield* promptSuggestions.shouldSuggest(input.model)) + ) { + return; + } + yield* offerRuntimeEvent({ + type: "turn.prompt-suggestion.updated", + eventId: EventId.make(`${input.completedEventId}:prompt-suggestion`), + provider: PROVIDER, + createdAt: yield* nowIso, + threadId: ctx.threadId, + turnId: input.turnId, + payload: { suggestion }, + }); + }).pipe( + Effect.withSpan("AcpAdapter.suggestNextMessage"), + Effect.catchCause((cause) => + Effect.logDebug("ACP made no prompt suggestion", { + provider: PROVIDER, + threadId: ctx.threadId, + cause, + }), + ), + Effect.forkIn(ctx.scope), + ); + ctx.suggestionFiber = fiber; + }); + /** * Writes down what a finished prompt spent: the tokens on its result and * the change in the session's running cost across it, when the cost is @@ -1136,6 +1250,7 @@ export function makeAcpAdapter( ) => Effect.gen(function* () { if (ctx.stopped || ctx.activeTurnId !== undefined) return; + yield* dropSuggestion(ctx); ctx.activeTurnId = turnId; ctx.agentTurn = { turnId, ended: yield* Deferred.make() }; ctx.agentTurnLastActivityMs = Date.now(); @@ -1443,6 +1558,7 @@ export function makeAcpAdapter( Effect.gen(function* () { if (ctx.stopped) return; ctx.stopped = true; + yield* dropSuggestion(ctx); yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals); yield* settlePendingUserInputsAsEmptyAnswers(ctx.pendingUserInputs); // The agent's process takes its subagents with it. @@ -2462,6 +2578,30 @@ export function makeAcpAdapter( lastPlanFingerprint: undefined, activeTurnId: undefined, activeTurnText: "", + activeTurnReplyTail: "", + recentMessages: (input.contextSeed?.entries ?? []) + .flatMap((entry): ReadonlyArray => { + if ( + entry.kind !== "message" || + (entry.role !== "user" && entry.role !== "assistant") + ) { + return []; + } + const text = entry.text.trim(); + if (text.length === 0) return []; + return [ + { + role: entry.role, + text: + text.length <= PROMPT_SUGGESTION_MAX_CHARS_PER_MESSAGE + ? text + : text.slice(text.length - PROMPT_SUGGESTION_MAX_CHARS_PER_MESSAGE), + }, + ]; + }) + .slice(-PROMPT_SUGGESTION_MAX_MESSAGES), + suggestionFiber: undefined, + suggestionGeneration: 0, lastProviderStatus: undefined, lastContextUsageKey: undefined, acpSessionId: started.sessionId, @@ -2767,6 +2907,11 @@ export function makeAcpAdapter( if (ctx.activeTurnText.length < PLAN_GATE_SCAN_MAX_CHARS) { ctx.activeTurnText += event.text; } + ctx.activeTurnReplyTail = appendTailCapped( + ctx.activeTurnReplyTail, + event.text, + PROMPT_SUGGESTION_MAX_CHARS_PER_MESSAGE, + ); yield* logNative(ctx.threadId, "session/update", event.rawPayload); yield* offerRuntimeEvent( makeAcpContentDeltaEvent({ @@ -3292,8 +3437,12 @@ export function makeAcpAdapter( const turnId = TurnId.make(command.turnId); const caller = command.sendId === undefined ? undefined : machine.callers.get(command.sendId); + yield* dropSuggestion(ctx); ctx.activeTurnId = turnId; resetTurnState(ctx); + if (caller?.userMessageText) { + pushRecentMessage(ctx, "user", caller.userMessageText); + } ctx.history.push( caller?.messageId !== undefined ? { turnId, messageId: caller.messageId } @@ -3307,6 +3456,8 @@ export function makeAcpAdapter( model: caller?.prompt.model ?? ctx.session.model, resolvedModel: caller?.prompt.resolvedModel ?? resolveModelId(ctx.session.model), planMode: caller?.planMode, + suggestNextMessage: caller?.suggestNextMessage === true, + suggestionGeneration: ctx.suggestionGeneration, }); yield* offerRuntimeEvent({ type: "turn.started", @@ -3365,6 +3516,9 @@ export function makeAcpAdapter( const caller = machine.callers.get(callerId); machine.callers.delete(callerId); if (caller === undefined) return; + if (command.type === "acceptSteer" && caller.userMessageText) { + pushRecentMessage(ctx, "user", caller.userMessageText); + } yield* Deferred.succeed( caller.reply, command.type === "acceptSend" || command.type === "acceptSteer" @@ -3633,7 +3787,24 @@ export function makeAcpAdapter( ctx.session = { ...ctx.session, activeTurnId: undefined, updatedAt: yield* nowIso }; } const stamp = yield* makeEventStamp(); - if (end.kind === "aborted") { + const completedPayload: AcpTurnCompletedPayload | undefined = + end.kind === "aborted" + ? undefined + : end.kind === "answered" + ? end.outcome.answer + : end.kind === "agentDone" + ? { state: "completed", stopReason: null } + : end.kind === "stopped" + ? { state: "cancelled", stopReason: "cancelled" } + : { + state: "failed", + stopReason: null, + errorMessage: `${descriptor.presentation.displayName} stopped before its work finished.`, + }; + if (ctx.activeTurnReplyTail.trim().length > 0) { + pushRecentMessage(ctx, "assistant", ctx.activeTurnReplyTail); + } + if (completedPayload === undefined) { yield* offerRuntimeEvent({ type: "turn.aborted", ...stamp, @@ -3649,19 +3820,21 @@ export function makeAcpAdapter( provider: PROVIDER, threadId: ctx.threadId, turnId: id, - payload: - end.kind === "answered" - ? end.outcome.answer - : end.kind === "agentDone" - ? { state: "completed", stopReason: null } - : end.kind === "stopped" - ? { state: "cancelled", stopReason: "cancelled" } - : { - state: "failed", - stopReason: null, - errorMessage: `${descriptor.presentation.displayName} stopped before its work finished.`, - }, + payload: completedPayload, }); + const promptSuggestions = options?.promptSuggestions; + if ( + completedPayload.state === "completed" && + data?.suggestNextMessage === true && + ctx.suggestionGeneration === data.suggestionGeneration && + promptSuggestions !== undefined + ) { + yield* startSuggestion(ctx, promptSuggestions, { + turnId: id, + model: data.model, + completedEventId: stamp.eventId, + }); + } } // Cost reported after the turn's last prompt answered (its own replies). const costUsd = takeReportedCost(ctx); @@ -3686,6 +3859,7 @@ export function makeAcpAdapter( input: Parameters[0], ) => Effect.gen(function* () { + yield* dropSuggestion(ctx); const turnId = TurnId.make(crypto.randomUUID()); const prepared = yield* prepareTurnPrompt(ctx, input); carryPromptPreface(ctx, turnId, prepared); @@ -3699,6 +3873,7 @@ export function makeAcpAdapter( } if (ctx.projectBriefCarrier?.turnId === turnId) requeueProjectBrief(ctx); }; + const userMessageText = (input.typed?.text ?? input.input ?? "").trim(); machine.callers.set(sendId, { prompt: { parts: prepared.promptParts, @@ -3709,6 +3884,8 @@ export function makeAcpAdapter( delivered, }, ...(input.messageId !== undefined ? { messageId: input.messageId } : {}), + ...(userMessageText.length > 0 ? { userMessageText } : {}), + suggestNextMessage: input.suggestNextMessage === true, planMode: prepared.planMode, reply, }); @@ -3773,6 +3950,7 @@ export function makeAcpAdapter( preamble: undefined, delivered: undefined, }, + ...(text.length > 0 ? { userMessageText: text } : {}), planMode: undefined, reply, }); @@ -3947,6 +4125,7 @@ export function makeAcpAdapter( const startTurn = (ctx: AcpSessionContext, input: Parameters[0]) => Effect.gen(function* () { + yield* dropSuggestion(ctx); if (ctx.promptFiber) { // ACP serializes prompts per session; a turn sent while one is in // flight starts after it, never interleaved with it. @@ -3968,8 +4147,10 @@ export function makeAcpAdapter( } const turnId = TurnId.make(crypto.randomUUID()); const prepared = yield* prepareTurnPrompt(ctx, input); - const { planMode, resolvedModel, promptParts } = prepared; + const { planMode, model, resolvedModel, promptParts } = prepared; yield* prepared.configure; + yield* dropSuggestion(ctx); + const turnSuggestionGeneration = ctx.suggestionGeneration; ctx.activeTurnId = turnId; const prompt = { turnId, @@ -3978,6 +4159,10 @@ export function makeAcpAdapter( }; ctx.openPrompt = prompt; resetTurnState(ctx); + const userMessageText = (input.typed?.text ?? input.input ?? "").trim(); + if (userMessageText.length > 0) { + pushRecentMessage(ctx, "user", userMessageText); + } carryPromptPreface(ctx, turnId, prepared); ctx.session = { ...ctx.session, activeTurnId: turnId, updatedAt: yield* nowIso }; ctx.history.push({ @@ -4041,18 +4226,36 @@ export function makeAcpAdapter( updatedAt: yield* nowIso, ...(resolvedModel !== undefined ? { model: resolvedModel } : {}), }; + if (ctx.activeTurnReplyTail.trim().length > 0) { + pushRecentMessage(ctx, "assistant", ctx.activeTurnReplyTail); + } + const completedStamp = yield* makeEventStamp(); + const completedPayload = answeredTurnPayload( + result.stopReason, + ctx.activeTurnText, + ctx.lastProviderStatus, + ); yield* offerRuntimeEvent({ type: "turn.completed", - ...(yield* makeEventStamp()), + ...completedStamp, provider: PROVIDER, threadId: input.threadId, turnId, - payload: answeredTurnPayload( - result.stopReason, - ctx.activeTurnText, - ctx.lastProviderStatus, - ), + payload: completedPayload, }); + const promptSuggestions = options?.promptSuggestions; + if ( + completedPayload.state === "completed" && + input.suggestNextMessage === true && + ctx.suggestionGeneration === turnSuggestionGeneration && + promptSuggestions !== undefined + ) { + yield* startSuggestion(ctx, promptSuggestions, { + turnId, + model, + completedEventId: completedStamp.eventId, + }); + } yield* settleTurnUsage(ctx, turnId, resolvedModel, usageTotalsOf(result.usage)); return; } @@ -4132,6 +4335,7 @@ export function makeAcpAdapter( const interruptTurn: AcpAdapterShape["interruptTurn"] = (threadId) => Effect.gen(function* () { const ctx = yield* requireSession(threadId); + yield* dropSuggestion(ctx); const turnId = ctx.activeTurnId; const promptFiber = ctx.promptFiber; yield* settlePendingApprovalsAsCancelled(ctx.pendingApprovals); diff --git a/apps/server/src/provider/acp/AcpProviderDriver.ts b/apps/server/src/provider/acp/AcpProviderDriver.ts index 09954c2f3..52b8775d8 100644 --- a/apps/server/src/provider/acp/AcpProviderDriver.ts +++ b/apps/server/src/provider/acp/AcpProviderDriver.ts @@ -45,7 +45,7 @@ import { } from "../providerMaintenance.ts"; import { withKnownCliDirsOnPath } from "../providerDetection.ts"; import type { ServerProviderDraft } from "../providerSnapshot.ts"; -import { makeAcpAdapter } from "./AcpAdapter.ts"; +import { type AcpAdapterOptions, makeAcpAdapter } from "./AcpAdapter.ts"; import { buildInitialAcpProviderSnapshot, checkAcpProviderStatus, @@ -192,9 +192,19 @@ export function resolveAcpBinaryPath( ); } -export function makeAcpProviderDriver( +export interface AcpProviderDriverOptions { + readonly promptSuggestions?: (context: { + readonly descriptor: AcpProviderDescriptor; + readonly settings: Settings; + readonly environment: NodeJS.ProcessEnv; + readonly getSnapshot: Effect.Effect; + }) => Effect.Effect["promptSuggestions"]>, never, R>; +} + +export function makeAcpProviderDriver( descriptor: AcpProviderDescriptor, -): ProviderDriver { + driverOptions?: AcpProviderDriverOptions, +): ProviderDriver { const DRIVER_KIND = descriptor.driverKind; const maintenanceResolver = makeAcpProviderMaintenanceResolver(descriptor); @@ -310,11 +320,22 @@ export function makeAcpProviderDriver( ), ), }; + const promptSuggestions = driverOptions?.promptSuggestions + ? yield* driverOptions.promptSuggestions({ + descriptor, + settings: effectiveConfig, + environment: processEnv, + getSnapshot: Effect.suspend( + () => liveSnapshot?.getSnapshot ?? Effect.die("ACP provider snapshot not ready"), + ), + }) + : undefined; const adapter = yield* makeAcpAdapter(descriptor, effectiveConfig, { environment: processEnv, ...(eventLoggers.native ? { nativeEventLogger: eventLoggers.native } : {}), instanceId, ...(recordTurnUsage ? { recordTurnUsage } : {}), + ...(promptSuggestions ? { promptSuggestions } : {}), ...agentCommandHooks, }); const textGeneration = yield* makeAcpTextGeneration( diff --git a/apps/server/src/provider/acp/AcpTextGeneration.test.ts b/apps/server/src/provider/acp/AcpTextGeneration.test.ts index 0ed642187..11ee9e3d9 100644 --- a/apps/server/src/provider/acp/AcpTextGeneration.test.ts +++ b/apps/server/src/provider/acp/AcpTextGeneration.test.ts @@ -9,8 +9,10 @@ import { it } from "@effect/vitest"; import * as Clock from "effect/Clock"; import * as Effect from "effect/Effect"; import * as Exit from "effect/Exit"; +import * as FileSystem from "effect/FileSystem"; import * as Layer from "effect/Layer"; import * as Schema from "effect/Schema"; +import { ChildProcessSpawner } from "effect/process"; import { createModelSelection } from "@threadlines/shared/model"; import { expect } from "vite-plus/test"; @@ -18,7 +20,7 @@ import { CursorSettings, ProviderInstanceId } from "@threadlines/contracts"; import { ServerConfig } from "../../config.ts"; import { type TextGenerationShape } from "../../textGeneration/TextGeneration.ts"; -import { makeAcpTextGeneration } from "./AcpTextGeneration.ts"; +import { makeAcpTextGeneration, sampleAcpPromptSuggestion } from "./AcpTextGeneration.ts"; import { CURSOR_ACP_DESCRIPTOR } from "./CursorAcpSupport.ts"; const decodeCursorSettings = Schema.decodeSync(CursorSettings); @@ -328,4 +330,82 @@ it.layer(CursorTextGenerationTestLayer)("CursorTextGeneration", (it) => { }), ); }); + + it.effect("samples a prompt suggestion in an isolated session and cleans it up", () => + Effect.gen(function* () { + const tempDir = mkdtempSync(path.join(os.tmpdir(), "threadlines-suggestion-acp-")); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + rmSync(tempDir, { recursive: true, force: true }); + }), + ); + const closedSessionIds: Array = []; + const agentPath = makeAcpAgentWrapper(tempDir, { + T3_ACP_PROMPT_RESPONSE_TEXT: "Run the browser suite next", + }); + const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + + const sampled = yield* sampleAcpPromptSuggestion({ + descriptor: { + ...CURSOR_ACP_DESCRIPTOR, + isolateTextGeneration: true, + onEphemeralSessionClosed: (sessionId) => + Effect.sync(() => { + closedSessionIds.push(sessionId); + }), + }, + settings: decodeCursorSettings({ enabled: true, binaryPath: agentPath }), + environment: process.env, + commandSpawner, + fileSystem, + cwd: process.cwd(), + prompt: "Predict the next user message.", + model: "composer-2", + }); + + expect(sampled).toBe("Run the browser suite next"); + expect(closedSessionIds.length).toBe(1); + }).pipe(Effect.scoped), + ); + + it.effect( + "aborts prompt sampling without falling back when the requested model is not offered", + () => + Effect.gen(function* () { + const tempDir = mkdtempSync( + path.join(os.tmpdir(), "threadlines-suggestion-missing-model-"), + ); + yield* Effect.addFinalizer(() => + Effect.sync(() => { + rmSync(tempDir, { recursive: true, force: true }); + }), + ); + const requestLogPath = path.join(tempDir, "requests.jsonl"); + const agentPath = makeAcpAgentWrapper(tempDir, { + T3_ACP_REQUEST_LOG_PATH: requestLogPath, + T3_ACP_PROMPT_RESPONSE_TEXT: "Should never be prompted", + }); + const commandSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + + const sampled = yield* sampleAcpPromptSuggestion({ + descriptor: { + ...CURSOR_ACP_DESCRIPTOR, + isolateTextGeneration: true, + }, + settings: decodeCursorSettings({ enabled: true, binaryPath: agentPath }), + environment: process.env, + commandSpawner, + fileSystem, + cwd: process.cwd(), + prompt: "Predict the next user message.", + model: "gemini-4-hydrogen-unavailable", + }); + + expect(sampled).toBeUndefined(); + const rawLog = readFileSync(requestLogPath, "utf8"); + expect(rawLog).not.toContain('"method":"session/prompt"'); + }).pipe(Effect.scoped), + ); }); diff --git a/apps/server/src/provider/acp/AcpTextGeneration.ts b/apps/server/src/provider/acp/AcpTextGeneration.ts index fce60c5a2..1c64ab099 100644 --- a/apps/server/src/provider/acp/AcpTextGeneration.ts +++ b/apps/server/src/provider/acp/AcpTextGeneration.ts @@ -13,7 +13,11 @@ import * as Ref from "effect/Ref"; import * as Schema from "effect/Schema"; import { ChildProcessSpawner } from "effect/process"; -import { type ModelSelection, TextGenerationError } from "@threadlines/contracts"; +import { + type ModelSelection, + type ProviderOptionSelection, + TextGenerationError, +} from "@threadlines/contracts"; import { sanitizeBranchFragment, sanitizeFeatureBranchName } from "@threadlines/shared/git"; import { extractJsonObject } from "@threadlines/shared/schemaJson"; @@ -29,12 +33,24 @@ import { sanitizePrTitle, sanitizeThreadTitle, } from "../../textGeneration/TextGenerationUtils.ts"; +import { selectSuggestionEffort } from "../promptSuggestions.ts"; import type { AcpProviderDescriptor, AcpProviderSettings } from "./AcpProviderDescriptor.ts"; -import { applyAcpModelSelection, makeAcpProviderRuntime } from "./AcpProviderRuntime.ts"; +import { + flattenSessionConfigSelectOptions, + selectConfigOptionCurrentValue, +} from "./AcpProviderModels.ts"; +import { + applyAcpModelSelection, + defaultResolveAcpModelId, + makeAcpProviderRuntime, +} from "./AcpProviderRuntime.ts"; +import { findModelConfigOption } from "./AcpRuntimeModel.ts"; const ACP_TEXT_GENERATION_TIMEOUT_MS = 180_000; +const ACP_PROMPT_SUGGESTION_TIMEOUT_MS = 30_000; /** Text generation must not touch the workspace; prefer the agent's ask/read-only mode. */ const ACP_TEXT_GENERATION_MODE_ID = "ask"; +const REASONING_CONFIG_ID = /^(?:thought_level|reasoning_effort|reasoning|effort)$/iu; type TextGenerationOperation = | "generateCommitMessage" @@ -311,3 +327,177 @@ export const makeAcpTextGeneration = Effect.fn("makeAcpTextGeneration")(function generateThreadTitle, } satisfies TextGenerationShape; }); + +/** + * Runs a short, isolated, tool-free ACP turn to sample a next-message prompt + * suggestion, then tears down the throwaway session and cleans up any on-disk + * session artifacts via `descriptor.onEphemeralSessionClosed`. + */ +export function sampleAcpPromptSuggestion(input: { + readonly descriptor: AcpProviderDescriptor; + readonly settings: Settings; + readonly environment: NodeJS.ProcessEnv; + readonly commandSpawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; + readonly fileSystem: FileSystem.FileSystem; + readonly cwd: string; + readonly prompt: string; + readonly model: string | undefined; + readonly options?: ReadonlyArray; + /** + * Optional gate run against the live session's active model when `model` was + * not pinned up front, so a session's default model can be quota-checked + * before sending the prompt. + */ + readonly allowLiveModel?: (model: { + readonly slug: string; + readonly name: string; + }) => Effect.Effect; +}): Effect.Effect { + const { descriptor } = input; + let openedSessionId: string | undefined; + return Effect.gen(function* () { + const outputRef = yield* Ref.make(""); + let sawToolCall = false; + const runCwd = descriptor.isolateTextGeneration + ? yield* input.fileSystem.makeTempDirectoryScoped({ prefix: "threadlines-suggestion-" }) + : input.cwd; + const runtime = yield* makeAcpProviderRuntime(descriptor, { + settings: input.settings, + environment: input.environment, + childProcessSpawner: input.commandSpawner, + cwd: runCwd, + clientInfo: { ...THREADLINES_ACP_CLIENT_INFO, name: "threadlines-prompt-suggestion" }, + }); + // Prompt suggestions never run tools or touch files. + yield* runtime.handleRequestPermission(() => { + sawToolCall = true; + return Effect.succeed({ outcome: { outcome: "cancelled" as const } }); + }); + yield* runtime.handleSessionUpdate((notification) => { + if (openedSessionId === undefined && notification.sessionId) { + openedSessionId = notification.sessionId; + } + const update = notification.update; + if (update.sessionUpdate === "tool_call") { + sawToolCall = true; + return runtime.cancel.pipe(Effect.ignore, Effect.forkDetach, Effect.asVoid); + } + if (update.sessionUpdate !== "agent_message_chunk") return Effect.void; + const content = update.content; + if (content.type !== "text") return Effect.void; + return Ref.update(outputRef, (current) => current + content.text); + }); + + const promptResult = yield* Effect.gen(function* () { + const started = yield* runtime.start(); + openedSessionId = started.sessionId; + const modeState = yield* runtime.getModeState; + const availableModeIds = modeState?.availableModes.map((mode) => mode.id) ?? []; + const targetMode = + descriptor.agentModeFor?.({ + runtimeMode: "approval-required", + interactionMode: undefined, + availableModeIds, + }) ?? ACP_TEXT_GENERATION_MODE_ID; + // When the session advertises the requested supervised/read-only mode, + // require switching to it before prompting so a failed mode switch never + // runs the prompt in a more permissive mode. + if (availableModeIds.includes(targetMode)) { + if (modeState?.currentModeId !== targetMode) { + yield* runtime.setMode(targetMode); + } + } else { + yield* Effect.ignore(runtime.setMode(targetMode)); + } + + // Require the requested suggestion model to actually be selected; if the + // live session does not offer it or rejects it, abort instead of spending + // quota from the session's default model pool. When no model was named, + // check the live session's active default model before prompting. + const initialConfigOptions = yield* runtime.getConfigOptions; + const initialModelOption = findModelConfigOption(initialConfigOptions); + const modelChoices = flattenSessionConfigSelectOptions(initialModelOption); + if (input.model !== undefined) { + const resolveModelId = descriptor.resolveModelId ?? defaultResolveAcpModelId; + const resolvedModel = resolveModelId(input.model, { + selections: input.options, + configOptions: initialConfigOptions, + }); + if ( + resolvedModel === undefined || + (modelChoices.length > 0 && + !modelChoices.some((choice) => choice.value === resolvedModel)) + ) { + return undefined; + } + yield* runtime.setModel(resolvedModel); + } else if (input.allowLiveModel !== undefined) { + const currentSlug = selectConfigOptionCurrentValue(initialModelOption); + if (currentSlug !== undefined) { + const currentChoice = modelChoices.find((choice) => choice.value === currentSlug); + const allowed = yield* input.allowLiveModel({ + slug: currentSlug, + name: currentChoice?.name || currentSlug, + }); + if (!allowed) return undefined; + } + } + + // Always check the live session's reasoning/thought_level option after + // model selection so a stale catalog cannot leave a model at high effort. + const liveConfigOptions = yield* runtime.getConfigOptions; + const reasoningOption = liveConfigOptions.find( + (candidate) => + candidate.type === "select" && + (candidate.category === "thought_level" || REASONING_CONFIG_ID.test(candidate.id)), + ); + if (reasoningOption) { + const choices = flattenSessionConfigSelectOptions(reasoningOption); + const effort = selectSuggestionEffort(choices.map((choice) => choice.value)); + const currentValue = selectConfigOptionCurrentValue(reasoningOption); + if (effort !== undefined && effort !== currentValue) { + yield* Effect.ignore(runtime.setConfigOption(reasoningOption.id, effort)); + } + } else if ((input.options?.length ?? 0) > 0) { + yield* Effect.ignore( + applyAcpModelSelection({ + descriptor, + runtime, + model: undefined, + selections: input.options, + mapError: ({ cause }) => cause, + }), + ); + } + return yield* runtime.prompt({ + prompt: [{ type: "text", text: input.prompt }], + }); + }).pipe(Effect.timeoutOption(ACP_PROMPT_SUGGESTION_TIMEOUT_MS)); + + if ( + sawToolCall || + Option.isNone(promptResult) || + promptResult.value === undefined || + promptResult.value.stopReason === "cancelled" + ) { + return undefined; + } + const raw = (yield* Ref.get(outputRef)).trim(); + return raw.length > 0 ? raw : undefined; + }).pipe( + Effect.scoped, + Effect.ensuring( + Effect.suspend(() => + openedSessionId !== undefined && descriptor.onEphemeralSessionClosed + ? descriptor.onEphemeralSessionClosed(openedSessionId).pipe(Effect.ignore) + : Effect.void, + ), + ), + Effect.catchCause((cause) => + Effect.logDebug("ACP prompt suggestion failed", { + provider: descriptor.driverKind, + cause, + }).pipe(Effect.as(undefined)), + ), + ); +} diff --git a/apps/server/src/provider/antigravity/AntigravityPromptSuggestions.test.ts b/apps/server/src/provider/antigravity/AntigravityPromptSuggestions.test.ts new file mode 100644 index 000000000..07f4b4894 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityPromptSuggestions.test.ts @@ -0,0 +1,182 @@ +import type { ServerProviderAccountUsage, ServerProviderModel } from "@threadlines/contracts"; +import { describe, expect, it } from "vite-plus/test"; + +import { + buildTranscriptPromptSuggestionPrompt, + PROMPT_SUGGESTION_MAX_CHARS_PER_MESSAGE, + PROMPT_SUGGESTION_MAX_MESSAGES, +} from "../promptSuggestions.ts"; +import { + isAntigravitySuggestionUsageNearLimit, + selectAntigravitySuggestionTarget, +} from "./AntigravityPromptSuggestions.ts"; + +const makeModel = ( + slug: string, + name: string, + efforts?: ReadonlyArray, +): ServerProviderModel => ({ + slug, + name, + isCustom: false, + capabilities: efforts + ? { + optionDescriptors: [ + { + id: "thought_level", + label: "Thinking Level", + type: "select", + options: efforts.map((id) => ({ id, label: id })), + }, + ], + } + : null, +}); + +describe("selectAntigravitySuggestionTarget", () => { + it("prefers Gemini Hydrogen over Flash and heavier models, with light thinking", () => { + const models = [ + makeModel("gemini-4-neon", "Gemini 4 Neon", ["low", "medium", "high", "xhigh"]), + makeModel("gemini-4-argon", "Gemini 4 Argon", ["low", "high"]), + makeModel("gemini-4-hydrogen", "Gemini 4 Hydrogen", ["low", "medium", "high"]), + makeModel("gemini-3.8-flash", "Gemini 3.8 Flash", ["minimal", "low", "high"]), + makeModel("claude-opus-5-5", "Claude Opus 5.5", ["high"]), + ]; + + expect(selectAntigravitySuggestionTarget(models, "claude-opus-5-5")).toEqual({ + model: "gemini-4-hydrogen", + modelName: "Gemini 4 Hydrogen", + options: [{ id: "thought_level", value: "low" }], + }); + }); + + it("falls back to non-lite Gemini Flash when Hydrogen is absent", () => { + const models = [ + makeModel("gemini-4-argon", "Gemini 4 Argon", ["low", "high"]), + makeModel("gemini-3.8-flash-lite", "Gemini 3.8 Flash Lite", ["minimal", "low"]), + makeModel("gemini-3.8-flash", "Gemini 3.8 Flash", ["minimal", "high"]), + ]; + + expect(selectAntigravitySuggestionTarget(models, "gemini-4-argon")).toEqual({ + model: "gemini-3.8-flash", + modelName: "Gemini 3.8 Flash", + options: [{ id: "thought_level", value: "minimal" }], + }); + }); + + it("falls back to the thread model when neither Hydrogen nor Flash is listed", () => { + const models = [makeModel("gemini-4-argon", "Gemini 4 Argon", ["low", "high"])]; + + expect(selectAntigravitySuggestionTarget(models, "gemini-4-argon")).toEqual({ + model: "gemini-4-argon", + modelName: "Gemini 4 Argon", + options: [{ id: "thought_level", value: "low" }], + }); + expect(selectAntigravitySuggestionTarget([], "claude-opus-5-5")).toEqual({ + model: "claude-opus-5-5", + modelName: "claude-opus-5-5", + options: [], + }); + const catalogWithDefault: ReadonlyArray = [ + { ...makeModel("gemini-4-argon", "Gemini 4 Argon", ["low", "high"]), isDefault: true }, + ]; + expect(selectAntigravitySuggestionTarget(catalogWithDefault, undefined)).toEqual({ + model: "gemini-4-argon", + modelName: "Gemini 4 Argon", + options: [{ id: "thought_level", value: "low" }], + }); + }); +}); + +describe("isAntigravitySuggestionUsageNearLimit", () => { + const nowMs = Date.parse("2026-11-23T18:00:00.000Z"); + const resetsAt = nowMs + 3_600_000; + + it("still enforces plan-wide limits when the model name is unknown", () => { + const planWideUsage: ServerProviderAccountUsage = { + source: "codex-rate-limits", + checkedAt: "2026-11-23T17:59:00.000Z", + limits: [ + { + primary: { + usedPercent: 92, + remainingPercent: 8, + resetsAt, + }, + }, + ], + }; + expect(isAntigravitySuggestionUsageNearLimit(planWideUsage, undefined, nowMs)).toBe(true); + const scopedUsage: ServerProviderAccountUsage = { + source: "grok-billing", + checkedAt: "2026-11-23T17:59:00.000Z", + limits: [ + { + limitId: "antigravity", + scoped: [ + { + scopeLabel: "Claude & GPT", + scopeModels: ["Claude", "GPT"], + usedPercent: 95, + remainingPercent: 5, + resetsAt, + }, + ], + }, + ], + }; + expect(isAntigravitySuggestionUsageNearLimit(scopedUsage, undefined, nowMs)).toBe(true); + }); + + it("pauses only when the chosen suggestion model's own pool hits 90%", () => { + const usage: ServerProviderAccountUsage = { + source: "grok-billing", + checkedAt: "2026-11-23T17:59:00.000Z", + limits: [ + { + limitId: "antigravity", + scoped: [ + { + scopeLabel: "Gemini", + scopeModels: ["Gemini"], + usedPercent: 45, + remainingPercent: 55, + resetsAt, + }, + { + scopeLabel: "Claude & GPT", + scopeModels: ["Claude", "GPT"], + usedPercent: 95, + remainingPercent: 5, + resetsAt, + }, + ], + }, + ], + }; + + expect(isAntigravitySuggestionUsageNearLimit(usage, "Gemini 4 Hydrogen", nowMs)).toBe(false); + expect(isAntigravitySuggestionUsageNearLimit(usage, "Claude Opus 5.5", nowMs)).toBe(true); + }); +}); + +describe("buildTranscriptPromptSuggestionPrompt", () => { + it("keeps the newest messages and preserves the tail of a long assistant reply", () => { + const messages = Array.from({ length: PROMPT_SUGGESTION_MAX_MESSAGES + 3 }, (_, index) => ({ + role: (index % 2 === 0 ? "user" : "assistant") as "user" | "assistant", + text: `turn-${index}`, + })); + const longTail = "Should I run the browser tests now?"; + messages.push({ + role: "assistant", + text: `${"x".repeat(PROMPT_SUGGESTION_MAX_CHARS_PER_MESSAGE + 500)}${longTail}`, + }); + + const prompt = buildTranscriptPromptSuggestionPrompt(messages); + expect(prompt).toBeDefined(); + expect(prompt).not.toContain("turn-0"); + expect(prompt).not.toContain("turn-3"); + expect(prompt).toContain("turn-4"); + expect(prompt).toContain(longTail); + }); +}); diff --git a/apps/server/src/provider/antigravity/AntigravityPromptSuggestions.ts b/apps/server/src/provider/antigravity/AntigravityPromptSuggestions.ts new file mode 100644 index 000000000..2528788c8 --- /dev/null +++ b/apps/server/src/provider/antigravity/AntigravityPromptSuggestions.ts @@ -0,0 +1,149 @@ +/** + * Antigravity prompt suggestion model selection and quota guard. + * + * Prefers a fast-but-smart Gemini Hydrogen model (e.g. `gemini-4-hydrogen`), + * then Gemini Flash (non-lite first), then the thread's own model, at the + * lightest good thinking level so suggestions stay quick without spending + * frontier or Claude/GPT quota. + * + * @module provider/antigravity/AntigravityPromptSuggestions + */ +import type { + ProviderOptionSelection, + ServerProviderAccountUsage, + ServerProviderModel, +} from "@threadlines/contracts"; +import { findReasoningOptionDescriptor } from "@threadlines/shared/model"; +import { + isAccountUsageNearLimit, + isModelUsageNearLimit, + usageResetTimeMs, +} from "@threadlines/shared/usageLimits"; + +import { + PROMPT_SUGGESTION_USAGE_CEILING_PERCENT, + selectSuggestionEffort, +} from "../promptSuggestions.ts"; + +export interface AntigravitySuggestionTarget { + /** Model slug to select on the ephemeral suggestion session, if any. */ + readonly model: string | undefined; + /** Display name (or slug fallback) matched against Antigravity's scoped usage windows. */ + readonly modelName: string | undefined; + /** Lightest good reasoning option selection for `model`, when supported. */ + readonly options: ReadonlyArray; +} + +const GEMINI_VERSION = /^gemini-(\d+(?:\.\d+)*)-/iu; + +function parseGeminiVersion(slug: string): ReadonlyArray { + const match = GEMINI_VERSION.exec(slug.trim()); + if (!match?.[1]) return []; + return match[1].split(".").map((part) => Number(part)); +} + +function compareDescVersion(left: ServerProviderModel, right: ServerProviderModel): number { + const a = parseGeminiVersion(left.slug); + const b = parseGeminiVersion(right.slug); + const length = Math.max(a.length, b.length); + for (let index = 0; index < length; index += 1) { + const diff = (b[index] ?? 0) - (a[index] ?? 0); + if (diff !== 0) return diff; + } + return 0; +} + +function isGeminiModel(model: ServerProviderModel): boolean { + return /^gemini-/iu.test(model.slug) || /\bgemini\b/iu.test(model.name); +} + +function isHydrogenModel(model: ServerProviderModel): boolean { + return ( + isGeminiModel(model) && (/\bhydrogen\b/iu.test(model.slug) || /\bhydrogen\b/iu.test(model.name)) + ); +} + +function isFlashModel(model: ServerProviderModel): boolean { + return isGeminiModel(model) && (/\bflash\b/iu.test(model.slug) || /\bflash\b/iu.test(model.name)); +} + +function isFlashLiteModel(model: ServerProviderModel): boolean { + return /flash[-_\s]?lite/iu.test(model.slug) || /flash[-_\s]?lite/iu.test(model.name); +} + +function reasoningOptionsFor( + model: ServerProviderModel | undefined, +): ReadonlyArray { + const descriptor = findReasoningOptionDescriptor(model?.capabilities?.optionDescriptors ?? []); + if (!descriptor) return []; + const effort = selectSuggestionEffort(descriptor.options.map((option) => option.id)); + return effort === undefined ? [] : [{ id: descriptor.id, value: effort }]; +} + +/** + * Picks the suggestion model and light thinking option from the account's live + * model catalog: + * 1. Highest-version Gemini Hydrogen (e.g. `gemini-4-hydrogen`) + * 2. Highest-version non-lite Gemini Flash (e.g. `gemini-3.8-flash`) + * 3. Any Gemini Flash + * 4. The thread's active `fallbackModel` + */ +export function selectAntigravitySuggestionTarget( + models: ReadonlyArray, + fallbackModel: string | undefined, +): AntigravitySuggestionTarget { + const hydrogen = models.filter(isHydrogenModel).toSorted(compareDescVersion)[0]; + const flash = + hydrogen ?? + models + .filter((model) => isFlashModel(model) && !isFlashLiteModel(model)) + .toSorted(compareDescVersion)[0] ?? + models.filter(isFlashModel).toSorted(compareDescVersion)[0]; + + const chosen = + flash ?? + (fallbackModel !== undefined + ? models.find((candidate) => candidate.slug === fallbackModel) + : undefined) ?? + models.find((candidate) => candidate.isDefault === true); + + if (chosen !== undefined) { + return { + model: chosen.slug, + modelName: chosen.name || chosen.slug, + options: reasoningOptionsFor(chosen), + }; + } + + return { + model: fallbackModel, + modelName: fallbackModel, + options: [], + }; +} + +/** + * Whether the chosen Antigravity suggestion model's usage pool (or a plan-wide + * limit) is at or above `percent` (default 90%), pausing suggestions without + * blocking on unrelated pools like Claude & GPT. When `modelName` is unknown, + * fails safe if any active scoped or plan-wide window is at or above `percent`. + */ +export function isAntigravitySuggestionUsageNearLimit( + accountUsage: ServerProviderAccountUsage | undefined, + modelName: string | undefined, + nowMs: number, + percent: number = PROMPT_SUGGESTION_USAGE_CEILING_PERCENT, +): boolean { + if (modelName !== undefined) { + return isModelUsageNearLimit(accountUsage, modelName, nowMs, percent); + } + if (isAccountUsageNearLimit(accountUsage, nowMs, percent)) return true; + if (accountUsage === undefined) return false; + return accountUsage.limits.some((limit) => + (limit.scoped ?? []).some((window) => { + if (window.usedPercent < percent) return false; + const resetsAtMs = usageResetTimeMs(window.resetsAt); + return resetsAtMs === undefined || resetsAtMs > nowMs; + }), + ); +} diff --git a/apps/server/src/provider/promptSuggestions.ts b/apps/server/src/provider/promptSuggestions.ts new file mode 100644 index 000000000..ee69923dd --- /dev/null +++ b/apps/server/src/provider/promptSuggestions.ts @@ -0,0 +1,155 @@ +/** + * Provider-neutral prompt suggestion rules shared by Codex and ACP providers: + * what the model is asked, how recent conversation context is bounded for + * isolated samplers, which reasoning effort is preferred, and how the returned + * single-line suggestion is sanitized. + * + * @module provider/promptSuggestions + */ +import type { ServerProviderModel } from "@threadlines/contracts"; +import { findReasoningOptionDescriptor } from "@threadlines/shared/model"; + +/** What the model is asked to predict for the composer's gray follow-up hint. */ +export const PROMPT_SUGGESTION_INSTRUCTIONS = `Stop being the assistant for a moment. Predict the next message the user will type in this conversation, so it can be offered in their message box. + +Read what they asked for and how the last reply ended. Suggest what they would most likely send next, in their own words and style: a next step, a yes to an option the reply offered, a request to run, check, or fix something. Never suggest thanks, praise, or comments on the reply, and never speak as the assistant. + +If there is no clear next message, reply with nothing. Otherwise reply with only the message: one line, at most 12 words, no quotes.`; + +/** No Threadlines-generated suggestions while a relevant usage window is this far used. */ +export const PROMPT_SUGGESTION_USAGE_CEILING_PERCENT = 90; + +/** + * The reasoning a suggestion asks for, best first, among the levels a model + * lists: the answer is a dozen words, and the lowest levels can read thin. + */ +const SUGGESTION_EFFORTS = ["low", "minimal", "medium", "none", "off"] as const; + +const MAX_SUGGESTION_CHARS = 120; +const MAX_SUGGESTION_WORDS = 20; +const QUOTE_PAIRS: ReadonlyArray = [ + ['"', '"'], + ["'", "'"], + ["“", "”"], + ["‘", "’"], + ["`", "`"], +]; +const NO_SUGGESTION = /^\(?(?:none|nothing|no suggestion|n\/a)\)?\.?$/iu; + +export const PROMPT_SUGGESTION_MAX_MESSAGES = 8; +export const PROMPT_SUGGESTION_MAX_CHARS_PER_MESSAGE = 4_000; +export const PROMPT_SUGGESTION_MAX_TOTAL_CHARS = 12_000; + +export interface PromptSuggestionMessage { + readonly role: "user" | "assistant"; + readonly text: string; +} + +/** + * Keeps the tail of a streaming string up to `maxChars`, so a long reply keeps + * its ending (where next steps and questions usually live). + */ +export function appendTailCapped(current: string, chunk: string, maxChars: number): string { + if (chunk.length === 0 || maxChars <= 0) return current; + const combined = current + chunk; + return combined.length <= maxChars ? combined : combined.slice(combined.length - maxChars); +} + +/** + * The suggestion in a sample's answer, or undefined when it isn't one: no + * text, more than one line, too long for the box's one line, or a word for + * "nothing". Quotes the model wrapped it in come off. + */ +export function sanitizePromptSuggestion(text: string | null | undefined): string | undefined { + let line = text?.trim() ?? ""; + for (const [open, close] of QUOTE_PAIRS) { + if (line.length > 1 && line.startsWith(open) && line.endsWith(close)) { + line = line.slice(open.length, -close.length).trim(); + break; + } + } + if (line.length === 0 || /[\r\n]/u.test(line) || NO_SUGGESTION.test(line)) return undefined; + if (line.length > MAX_SUGGESTION_CHARS) return undefined; + if (line.split(/\s+/u).length > MAX_SUGGESTION_WORDS) return undefined; + return line; +} + +/** + * The reasoning effort to ask a suggestion sample for, from the levels a model + * lists; undefined when it lists none of the light ones or isn't known. + */ +export function selectSuggestionEffort( + modelEfforts: ReadonlyArray | undefined, +): string | undefined { + if (modelEfforts === undefined) return undefined; + return SUGGESTION_EFFORTS.find((effort) => modelEfforts.includes(effort)); +} + +/** + * The reasoning levels a model lists, from the instance's catalog; the + * catalog's default model stands for a turn that named none. Undefined for a + * model the catalog doesn't know. + */ +export function modelReasoningEfforts( + models: ReadonlyArray, + model: string | undefined, +): ReadonlyArray | undefined { + const entry = + model === undefined + ? models.find((candidate) => candidate.isDefault === true) + : models.find((candidate) => candidate.slug === model); + const descriptor = findReasoningOptionDescriptor(entry?.capabilities?.optionDescriptors ?? []); + return descriptor?.options.map((option) => option.id); +} + +/** + * Builds a bounded prompt for an isolated suggestion call that does not share + * the thread's live session cache. Keeps the newest messages and the tail of + * each long message so the end of the last reply stays intact. + */ +export function buildTranscriptPromptSuggestionPrompt( + messages: ReadonlyArray, +): string | undefined { + const nonEmpty = messages + .map((message) => ({ role: message.role, text: message.text.trim() })) + .filter((message) => message.text.length > 0) + .slice(-PROMPT_SUGGESTION_MAX_MESSAGES); + if (nonEmpty.length === 0) return undefined; + + const selectedReversed: Array = []; + let totalChars = 0; + + for (let index = nonEmpty.length - 1; index >= 0; index -= 1) { + const message = nonEmpty[index]!; + const label = message.role === "user" ? "User" : "Assistant"; + const clipped = + message.text.length <= PROMPT_SUGGESTION_MAX_CHARS_PER_MESSAGE + ? message.text + : `...\n${message.text.slice(message.text.length - PROMPT_SUGGESTION_MAX_CHARS_PER_MESSAGE)}`; + const block = `${label}:\n${clipped}`; + const remainingBudget = PROMPT_SUGGESTION_MAX_TOTAL_CHARS - totalChars; + if (remainingBudget <= 0) break; + if (block.length <= remainingBudget) { + selectedReversed.push(block); + totalChars += block.length + 2; + continue; + } + if (selectedReversed.length === 0) { + const prefix = `${label}:\n...\n`; + const available = Math.max(0, remainingBudget - prefix.length); + selectedReversed.push( + available > 0 ? `${prefix}${message.text.slice(message.text.length - available)}` : label, + ); + } + break; + } + + const transcript = selectedReversed.reverse().join("\n\n"); + return `${PROMPT_SUGGESTION_INSTRUCTIONS} + +Do not use any tools. + + +${transcript} +`; +} diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index d891c6727..dc2e0e4af 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -1904,10 +1904,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const recipientDriverKind = addressedRoomAgent ? addressedRoomAgentEntry?.driverKind : selectedProvider; - // Codex's suggestions are Threadlines' own, with a switch in Settings on - // the computer the thread runs on. + // Codex and Antigravity suggestions are Threadlines' own, each with a switch + // in Settings › Providers on the computer the thread runs on. const codexSuggestionsOn = useEnvironmentServerSetting(environmentId, "codexSuggestions"); - const recipientSuggestionsOff = recipientDriverKind === "codex" && !codexSuggestionsOn; + const antigravitySuggestionsOn = useEnvironmentServerSetting( + environmentId, + "antigravitySuggestions", + ); + const recipientSuggestionsOff = + (recipientDriverKind === "codex" && !codexSuggestionsOn) || + (recipientDriverKind === "antigravity" && !antigravitySuggestionsOn); const promptSuggestion = useMemo( () => selectPromptSuggestion({ diff --git a/apps/web/src/components/settings/ProviderSuggestionsSection.tsx b/apps/web/src/components/settings/ProviderSuggestionsSection.tsx new file mode 100644 index 000000000..5c537e2a6 --- /dev/null +++ b/apps/web/src/components/settings/ProviderSuggestionsSection.tsx @@ -0,0 +1,126 @@ +import { useSettings, useUpdateSettings } from "../../hooks/useSettings"; +import { Switch } from "../ui/switch"; +import { SettingResetButton, SettingsRow, SettingsSection } from "./settingsLayout"; +import { ShownPlace } from "./settingsPlaceAvailability"; + +/** + * Claude skips suggesting the user's next message while the user is on track + * to run out of usage early; on keeps the suggestions coming. For every Claude + * account, read before each message, so running threads follow it from their + * next message. + */ +export function ClaudeSuggestionsRow() { + const on = useSettings((settings) => settings.claudeSuggestionsWhenUsageRunsFast); + const { updateSettings } = useUpdateSettings(); + return ( + updateSettings({ claudeSuggestionsWhenUsageRunsFast: false })} + /> + ) : null + } + control={ + + updateSettings({ claudeSuggestionsWhenUsageRunsFast: Boolean(checked) }) + } + aria-label="Keep Claude's suggestions when you're using a lot" + /> + } + /> + ); +} + +/** + * Codex suggests the user's next message after replying to them: one extra + * answer from the thread's cached context each time. Read by the thread's + * computer before each suggestion; off also hides Codex suggestions already + * made. + */ +export function CodexSuggestionsRow() { + const on = useSettings((settings) => settings.codexSuggestions); + const { updateSettings } = useUpdateSettings(); + return ( + updateSettings({ codexSuggestions: true })} + /> + ) + } + control={ + updateSettings({ codexSuggestions: Boolean(checked) })} + aria-label="Codex suggestions" + /> + } + /> + ); +} + +/** + * Antigravity suggests the user's next message after replying to them: one + * short isolated answer on a fast Gemini model (preferring Hydrogen, then + * Flash, at low thinking). Read before each suggestion; off also hides + * Antigravity suggestions already made. + */ +export function AntigravitySuggestionsRow() { + const on = useSettings((settings) => settings.antigravitySuggestions); + const { updateSettings } = useUpdateSettings(); + return ( + updateSettings({ antigravitySuggestions: true })} + /> + ) + } + control={ + + updateSettings({ antigravitySuggestions: Boolean(checked) }) + } + aria-label="Antigravity suggestions" + /> + } + /> + ); +} + +/** + * Per-provider next-message suggestion toggles on Settings › Providers, + * showing only providers the user currently has turned on. + */ +export function ProviderSuggestionsSection() { + return ( + + + + + + + + + + + + + + ); +} diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index 5abfec466..a11b85a25 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -7892,3 +7892,75 @@ describe("AppearanceSettingsPanel", () => { expect(tops.filter((top) => top !== start)).toEqual([]); }); }); + +describe("ProviderSettingsPanel suggestions", () => { + beforeEach(async () => { + resetAppAtomRegistryForTests(); + resetServerStateForTests(); + await __resetLocalApiForTests(); + await resetTestPage(); + }); + + afterEach(async () => { + Reflect.deleteProperty(window, "nativeApi"); + await resetTestPage(); + resetServerStateForTests(); + await __resetLocalApiForTests(); + }); + + it("shows suggestion switches only for enabled providers and updates Antigravity suggestions", async () => { + const updateSettings = vi.fn(async (patch: Record) => ({ + ...DEFAULT_SERVER_SETTINGS, + providers: { + ...DEFAULT_SERVER_SETTINGS.providers, + antigravity: { ...DEFAULT_SERVER_SETTINGS.providers.antigravity, enabled: true }, + }, + ...patch, + })); + window.nativeApi = { + persistence: { + getClientSettings: vi.fn().mockResolvedValue(null), + updateClientSettings: vi.fn(async (patch: object) => patch), + subscribeClientSettings: () => () => undefined, + }, + server: { + updateSettings, + }, + } as unknown as LocalApi; + + // Default settings have Claude and Codex on, Antigravity off. + setServerConfigSnapshot(createBaseServerConfig()); + + await renderWithTestRouter( + + + , + ); + + await expect.element(page.getByText("Codex suggestions")).toBeInTheDocument(); + await expect + .element(page.getByText("Keep Claude's suggestions when you're using a lot")) + .toBeInTheDocument(); + await expect.element(page.getByText("Antigravity suggestions")).not.toBeInTheDocument(); + + // Turning Antigravity on surfaces its suggestion toggle. + const baseConfig = createBaseServerConfig(); + setServerConfigSnapshot({ + ...baseConfig, + settings: { + ...baseConfig.settings, + providers: { + ...baseConfig.settings.providers, + antigravity: { ...baseConfig.settings.providers.antigravity, enabled: true }, + }, + }, + }); + + const antigravitySwitch = page.getByRole("switch", { name: "Antigravity suggestions" }); + await expect.element(antigravitySwitch).toBeInTheDocument(); + await antigravitySwitch.click(); + await vi.waitFor(() => + expect(updateSettings).toHaveBeenCalledWith({ antigravitySuggestions: false }), + ); + }); +}); diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index d5c163213..e89298787 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -142,6 +142,7 @@ import { ArchivedThreadsSection, } from "./ArchivedThreadsSection"; import { ProviderInstanceCard, type ProviderAddAccountControls } from "./ProviderInstanceCard"; +import { ProviderSuggestionsSection } from "./ProviderSuggestionsSection"; import { addAccountMenuLabel, isThreadlinesAccountFolder } from "./providerAccounts.logic"; import { formatProviderInstanceName } from "../../providerInstances"; import { getDriverOption } from "./providerDriverMeta"; @@ -538,10 +539,13 @@ export function useSettingsRestore(onRestored?: () => void) { : []), ...(settings.claudeSuggestionsWhenUsageRunsFast !== DEFAULT_UNIFIED_SETTINGS.claudeSuggestionsWhenUsageRunsFast - ? ["Keep Claude's suggestions when you're using a lot"] + ? [placeById("providers.claudeSuggestions").title] : []), ...(settings.codexSuggestions !== DEFAULT_UNIFIED_SETTINGS.codexSuggestions - ? [placeById("threads.codexSuggestions").title] + ? [placeById("providers.codexSuggestions").title] + : []), + ...(settings.antigravitySuggestions !== DEFAULT_UNIFIED_SETTINGS.antigravitySuggestions + ? [placeById("providers.antigravitySuggestions").title] : []), ...(settings.continueAfterUsageLimits !== DEFAULT_UNIFIED_SETTINGS.continueAfterUsageLimits ? ["Continue after usage limits"] @@ -591,6 +595,7 @@ export function useSettingsRestore(onRestored?: () => void) { settings.claudeWorkflowSize, settings.claudeSuggestionsWhenUsageRunsFast, settings.codexSuggestions, + settings.antigravitySuggestions, settings.continueAfterUsageLimits, settings.continueAfterRestart, settings.enableCommandRequests, @@ -676,6 +681,7 @@ export function useSettingsRestore(onRestored?: () => void) { claudeSuggestionsWhenUsageRunsFast: DEFAULT_UNIFIED_SETTINGS.claudeSuggestionsWhenUsageRunsFast, codexSuggestions: DEFAULT_UNIFIED_SETTINGS.codexSuggestions, + antigravitySuggestions: DEFAULT_UNIFIED_SETTINGS.antigravitySuggestions, continueAfterUsageLimits: DEFAULT_UNIFIED_SETTINGS.continueAfterUsageLimits, continueAfterRestart: DEFAULT_UNIFIED_SETTINGS.continueAfterRestart, enableCommandRequests: true, @@ -2076,6 +2082,8 @@ export function ProviderSettingsPanel({ ]} + + - - @@ -668,72 +666,6 @@ export function ClaudeWorkflowSizeRow() { ); } -/** - * Claude skips suggesting the user's next message while the user is on track - * to run out of usage early; on keeps the suggestions coming. For every Claude - * account, read before each message, so running threads follow it from their - * next message. - */ -export function ClaudeSuggestionsRow() { - const on = useSettings((settings) => settings.claudeSuggestionsWhenUsageRunsFast); - const { updateSettings } = useUpdateSettings(); - return ( - updateSettings({ claudeSuggestionsWhenUsageRunsFast: false })} - /> - ) : null - } - control={ - - updateSettings({ claudeSuggestionsWhenUsageRunsFast: Boolean(checked) }) - } - aria-label="Keep Claude's suggestions when you're using a lot" - /> - } - /> - ); -} - -/** - * Codex suggests the user's next message after replying to them: one extra - * answer from the thread's cached context each time. Read by the thread's - * computer before each suggestion; off also hides Codex suggestions already - * made. - */ -export function CodexSuggestionsRow() { - const on = useSettings((settings) => settings.codexSuggestions); - const { updateSettings } = useUpdateSettings(); - return ( - updateSettings({ codexSuggestions: true })} - /> - ) - } - control={ - updateSettings({ codexSuggestions: Boolean(checked) })} - aria-label="Codex suggestions" - /> - } - /> - ); -} - /** * Turns on "Continue at reset" for every thread a Claude or Codex usage limit * stops, the switch on the limit's notice above the composer. Read by the diff --git a/apps/web/src/components/settings/settingsPlaceAvailability.tsx b/apps/web/src/components/settings/settingsPlaceAvailability.tsx index a6675c9dc..4d072e802 100644 --- a/apps/web/src/components/settings/settingsPlaceAvailability.tsx +++ b/apps/web/src/components/settings/settingsPlaceAvailability.tsx @@ -18,12 +18,14 @@ import { import { useSavedEnvironmentRegistryStore } from "../../environments/runtime"; import { isElectron } from "../../env"; import { usePrimarySessionAccess } from "../../hooks/useAuthAccess"; +import { useSettings } from "../../hooks/useSettings"; import { pushAlertsSupport, relayLinkOf, usePushAlertsStore } from "../../pushAlerts/pushAlerts"; import { canSetDesktopBackgroundOptions, useDesktopBackgroundOptions, } from "./desktopBackgroundOptions"; import { isRemotelyReachable } from "./connections/serverReach"; +import { deriveMaintainedProviderRows, isProviderRowEnabled } from "./providerEnablement"; import { selectSettingsSearchActive, useSettingsSearchStore } from "./settingsSearchStore"; /** @@ -81,6 +83,12 @@ export interface PlaceSignals { readonly projectContext: boolean; /** This computer's server has devices (capability `devices`). */ readonly devices: boolean; + /** At least one Claude Code instance is turned on. */ + readonly claudeEnabled: boolean; + /** At least one Codex instance is turned on. */ + readonly codexEnabled: boolean; + /** At least one Antigravity instance is turned on. */ + readonly antigravityEnabled: boolean; } /** @@ -131,6 +139,11 @@ const SHOWN_WHEN: Partial !s.phone && s.devices, "devices.agentAccess": (s) => !s.phone && s.devices, "devices.tools": (s) => !s.phone && s.devices, + // Providers › Suggestions: only providers the user currently has turned on. + "providers.suggestions": (s) => s.claudeEnabled || s.codexEnabled || s.antigravityEnabled, + "providers.claudeSuggestions": (s) => s.claudeEnabled, + "providers.codexSuggestions": (s) => s.codexEnabled, + "providers.antigravitySuggestions": (s) => s.antigravityEnabled, }; /** @@ -152,6 +165,9 @@ const STATIC_SIGNALS: PlaceSignals = { remotelyReachable: true, projectContext: true, devices: true, + claudeEnabled: true, + codexEnabled: true, + antigravityEnabled: true, }; const PlaceSignalsContext = createContext(null); @@ -198,6 +214,24 @@ export interface SettingsSearchHost { readonly searchSession: number; } +function useEnabledSuggestionProviders() { + const providers = useSettings((settings) => settings.providers); + const providerInstances = useSettings((settings) => settings.providerInstances); + return useMemo(() => { + const rows = deriveMaintainedProviderRows({ providers, providerInstances }); + let claudeEnabled = false; + let codexEnabled = false; + let antigravityEnabled = false; + for (const row of rows) { + if (!isProviderRowEnabled(row)) continue; + if (row.driver === "claudeAgent") claudeEnabled = true; + else if (row.driver === "codex") codexEnabled = true; + else if (row.driver === "antigravity") antigravityEnabled = true; + } + return { claudeEnabled, codexEnabled, antigravityEnabled }; + }, [providerInstances, providers]); +} + function usePlaceSignals(phone: boolean, host: SettingsSearchHost): PlaceSignals { const background = useDesktopBackgroundOptions(); const dictation = useDictationStatus(usePrimaryEnvironmentId()); @@ -218,6 +252,7 @@ function usePlaceSignals(phone: boolean, host: SettingsSearchHost): PlaceSignals const alertsSupport = pushAlertsSupport(); const alertsShown = alertsSupport !== "unsupported" && alertComputers > 0; const canSetBackground = background !== null && canSetDesktopBackgroundOptions(); + const { claudeEnabled, codexEnabled, antigravityEnabled } = useEnabledSuggestionProviders(); return useMemo( () => ({ phone, @@ -237,15 +272,21 @@ function usePlaceSignals(phone: boolean, host: SettingsSearchHost): PlaceSignals remotelyReachable: isElectron ? desktopReach : authPolicy === "remote-reachable", projectContext, devices, + claudeEnabled, + codexEnabled, + antigravityEnabled, }), [ alertsEnabled, alertsPermission, alertsShown, alertsSupport, + antigravityEnabled, authPolicy, background, canSetBackground, + claudeEnabled, + codexEnabled, desktopReach, devices, dictation, @@ -311,13 +352,15 @@ export function SettingsAvailabilityProvider({ /** Answers whether a settings place is on screen here; follows the live facts. */ export function useSettingsPlaceShown(): (id: SettingsPlaceSearchId) => boolean { - const gathered = useContext(PlaceSignalsContext) ?? STATIC_SIGNALS; + const fromProvider = useContext(PlaceSignalsContext); + const fallbackProviders = useEnabledSuggestionProviders(); // The nearest surface wins: a page drawn as the phone's says so itself. const phone = useSettingsSurface() === "phone"; - const signals = useMemo( - () => (gathered.phone === phone ? gathered : { ...gathered, phone }), - [gathered, phone], - ); + const signals = useMemo(() => { + const base = + fromProvider ?? ({ ...STATIC_SIGNALS, ...fallbackProviders } satisfies PlaceSignals); + return base.phone === phone ? base : { ...base, phone }; + }, [fallbackProviders, fromProvider, phone]); return useCallback((id) => placeShown(signals, id), [signals]); } diff --git a/apps/web/src/components/settings/settingsRowRegistry.tsx b/apps/web/src/components/settings/settingsRowRegistry.tsx index c476954d3..b46774d3b 100644 --- a/apps/web/src/components/settings/settingsRowRegistry.tsx +++ b/apps/web/src/components/settings/settingsRowRegistry.tsx @@ -48,6 +48,11 @@ import { WriterModelRow, WritingStyleRow, } from "./SourceControlSettings"; +import { + AntigravitySuggestionsRow, + ClaudeSuggestionsRow, + CodexSuggestionsRow, +} from "./ProviderSuggestionsSection"; import { AgentInvitesRow, AgentPagesRow, @@ -55,8 +60,6 @@ import { AgentThreadsShareWorktreesRow, BackupWritingModelRow, ClaudeArtifactsRow, - ClaudeSuggestionsRow, - CodexSuggestionsRow, ClaudeWorkflowSizeRow, CommandRequestsRow, ConfirmArchiveRow, @@ -146,8 +149,6 @@ export const SETTINGS_ROWS = { "threads.agentPages": live(AgentPagesRow), "threads.claudeArtifacts": live(ClaudeArtifactsRow), "threads.claudeWorkflowSize": live(ClaudeWorkflowSizeRow), - "threads.claudeSuggestions": live(ClaudeSuggestionsRow), - "threads.codexSuggestions": live(CodexSuggestionsRow), "threads.continueAfterUsageLimits": live(ContinueAfterUsageLimitsRow), "threads.continueAfterRestart": live(ContinueAfterRestartRow), "threads.commandRequests": live(CommandRequestsRow), @@ -190,4 +191,8 @@ export const SETTINGS_ROWS = { // Devices "devices.enable": live(UseDevicesRow), "devices.agentAccess": live(AgentDeviceAccessRow), + // Providers › Suggestions + "providers.claudeSuggestions": live(ClaudeSuggestionsRow), + "providers.codexSuggestions": live(CodexSuggestionsRow), + "providers.antigravitySuggestions": live(AntigravitySuggestionsRow), } as const satisfies { readonly [Id in SettingsRowPlaceId]: SettingsRowEntry }; diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 4b2c5b77d..4de24277c 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -1131,6 +1131,14 @@ export const ServerSettings = Schema.Struct({ * Never chosen: on. */ codexSuggestions: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), + /** + * After a turn a person started, Antigravity suggests their next message: + * one short isolated answer (preferring Gemini Hydrogen, then Flash, at low + * thinking) on the account's usage. Skipped while that model's usage window + * is 90% used. Read before each suggestion, and the composer hides + * Antigravity suggestions while it is off. Never chosen: on. + */ + antigravitySuggestions: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))), /** * "Continue at reset" for every thread a Claude or Codex usage limit stops, * when the limit names its reset time: the thread continues by itself once @@ -1349,6 +1357,7 @@ export const ServerSettingsPatch = Schema.Struct({ claudeWorkflowSize: Schema.optionalKey(ClaudeWorkflowSize), claudeSuggestionsWhenUsageRunsFast: Schema.optionalKey(Schema.Boolean), codexSuggestions: Schema.optionalKey(Schema.Boolean), + antigravitySuggestions: Schema.optionalKey(Schema.Boolean), continueAfterUsageLimits: Schema.optionalKey(Schema.Boolean), continueAfterRestart: Schema.optionalKey(Schema.Boolean), enableCommandRequests: Schema.optionalKey(Schema.Boolean), diff --git a/packages/shared/src/appPlaces.test.ts b/packages/shared/src/appPlaces.test.ts index 5b57ab385..8483c5ea6 100644 --- a/packages/shared/src/appPlaces.test.ts +++ b/packages/shared/src/appPlaces.test.ts @@ -46,6 +46,12 @@ describe("app places", () => { "[Settings › Threads › Rooms › Rooms](threadlines-place:threads.enableRooms)", ); expect(placeIdFromHref("threadlines-place:threads.enableRooms")).toBe("threads.enableRooms"); + expect(placeIdFromHref("threadlines-place:threads.claudeSuggestions")).toBe( + "providers.claudeSuggestions", + ); + expect(placeIdFromHref("threadlines-place:threads.codexSuggestions")).toBe( + "providers.codexSuggestions", + ); expect(placeIdFromHref("threadlines-place:nowhere.atAll")).toBeNull(); expect(placeIdFromHref("https://example.com")).toBeNull(); }); diff --git a/packages/shared/src/appPlaces.ts b/packages/shared/src/appPlaces.ts index f30065de9..4580e169d 100644 --- a/packages/shared/src/appPlaces.ts +++ b/packages/shared/src/appPlaces.ts @@ -702,6 +702,15 @@ const SECTIONS = [ about: "Every archived thread, to bring back or delete.", }, // Providers + { + id: "providers.suggestions", + kind: "section", + parent: "settings.providers", + title: "Suggestions", + about: + "Suggested next messages in the composer after a reply, for each agent you have turned on.", + keywords: ["autocomplete", "prompt suggestions", "tab"], + }, { id: "providers.community", kind: "section", @@ -1587,25 +1596,35 @@ const ROWS = [ widensAgents: true, }, { - id: "threads.claudeSuggestions", + id: "providers.claudeSuggestions", kind: "row", - parent: "threads.newThreads", + parent: "providers.suggestions", title: "Keep Claude's suggestions when you're using a lot", about: "Keep Claude suggesting your next message even when you're on track to run out of usage early.", - keywords: ["autocomplete", "prompt suggestions"], + keywords: ["autocomplete", "prompt suggestions", "claude"], ...editableServerSwitch("claudeSuggestionsWhenUsageRunsFast"), }, { - id: "threads.codexSuggestions", + id: "providers.codexSuggestions", kind: "row", - parent: "threads.newThreads", + parent: "providers.suggestions", title: "Codex suggestions", about: "After a reply to your message, Codex suggests what you might send next. Each suggestion uses a little Codex usage.", keywords: ["autocomplete", "prompt suggestions", "codex"], ...editableServerSwitch("codexSuggestions"), }, + { + id: "providers.antigravitySuggestions", + kind: "row", + parent: "providers.suggestions", + title: "Antigravity suggestions", + about: + "After a reply to your message, Antigravity suggests what you might send next using a fast Gemini model. Each suggestion uses a little Antigravity usage.", + keywords: ["autocomplete", "prompt suggestions", "antigravity", "gemini"], + ...editableServerSwitch("antigravitySuggestions"), + }, { id: "threads.continueAfterUsageLimits", kind: "row", @@ -2048,6 +2067,9 @@ const MOVED_PLACES: ReadonlyMap = new Map([ ["general.theme", "appearance.theme"], ["general.themeGlass", "appearance.glass"], ["general.themeMotion", "appearance.motion"], + // November 2026: provider suggestion toggles moved from Threads to Providers. + ["threads.claudeSuggestions", "providers.claudeSuggestions"], + ["threads.codexSuggestions", "providers.codexSuggestions"], ]); /** The place an id names now, following moves; null for an id this build doesn't know. */ diff --git a/packages/shared/src/model.ts b/packages/shared/src/model.ts index 43fa085fe..8b031bb2a 100644 --- a/packages/shared/src/model.ts +++ b/packages/shared/src/model.ts @@ -351,12 +351,13 @@ const REASONING_OPTION_IDS: ReadonlySet = new Set([ "effort", "reasoning", "variant", + "thought_level", ]); /** * A model's reasoning setting among its options: Codex calls it - * `reasoningEffort`, Claude `effort`, OpenCode `variant`. Undefined for a model - * without one. + * `reasoningEffort`, Claude `effort`, OpenCode `variant`, Antigravity + * `thought_level`. Undefined for a model without one. */ export function findReasoningOptionDescriptor( descriptors: ReadonlyArray, diff --git a/packages/shared/src/usageLimits.test.ts b/packages/shared/src/usageLimits.test.ts index af1e50233..b84add65a 100644 --- a/packages/shared/src/usageLimits.test.ts +++ b/packages/shared/src/usageLimits.test.ts @@ -3,6 +3,7 @@ import { describe, expect, it } from "vite-plus/test"; import { isAccountUsageNearLimit, + isModelUsageNearLimit, usageLimitForModel, usageScopeHoldsModel, } from "./usageLimits.ts"; @@ -100,4 +101,46 @@ describe("Antigravity's family limits", () => { // Past its reset, the reading is older than the window. expect(usageLimitForModel(usage, "Claude Opus 5.5", resetsAt + 1)).toBeUndefined(); }); + + it("checks near-limit per model pool without blocking unrelated families", () => { + const resetsAt = NOW_MS + 3_600_000; + const usage: ServerProviderAccountUsage = { + source: "grok-billing", + checkedAt: "2026-11-06T11:59:00.000Z", + limits: [ + { + limitId: "antigravity", + scoped: [ + { + scopeLabel: "Gemini", + scopeModels: ["Gemini"], + scopeExcludes: ["Hydrogen"], + usedPercent: 30, + remainingPercent: 70, + resetsAt, + }, + { + scopeLabel: "Gemini Hydrogen", + scopeModels: ["Hydrogen"], + usedPercent: 90, + remainingPercent: 10, + resetsAt, + }, + { + scopeLabel: "Claude & GPT", + scopeModels: ["Claude", "GPT"], + usedPercent: 96, + remainingPercent: 4, + resetsAt, + }, + ], + }, + ], + }; + expect(isModelUsageNearLimit(usage, "Gemini 4 Hydrogen", NOW_MS, 90)).toBe(true); + expect(isModelUsageNearLimit(usage, "Gemini 3.8 Flash", NOW_MS, 90)).toBe(false); + expect(isModelUsageNearLimit(usage, "Claude Opus 5.5", NOW_MS, 90)).toBe(true); + // Past reset, the stale reading no longer blocks. + expect(isModelUsageNearLimit(usage, "Gemini 4 Hydrogen", resetsAt + 1, 90)).toBe(false); + }); }); diff --git a/packages/shared/src/usageLimits.ts b/packages/shared/src/usageLimits.ts index 2f1927fc6..3b3564fe5 100644 --- a/packages/shared/src/usageLimits.ts +++ b/packages/shared/src/usageLimits.ts @@ -90,6 +90,36 @@ export function isAccountUsageNearLimit( return readAccountUsageBlockAt(accountUsage, nowMs, percent).state === "blocked"; } +/** + * `isAccountUsageNearLimit` for one model: checks both plan-wide windows and + * any model-scoped windows (`scoped`) covering `modelName`, so a provider with + * per-family pools (Antigravity) pauses extras only when that model's own + * pool is near its limit. + */ +export function isModelUsageNearLimit( + accountUsage: ServerProviderAccountUsage | undefined, + modelName: string, + nowMs: number, + percent: number, +): boolean { + if (isAccountUsageNearLimit(accountUsage, nowMs, percent)) return true; + if (accountUsage === undefined) return false; + for (const limit of accountUsage.limits) { + for (const window of limit.scoped ?? []) { + const scope = { + name: window.scopeLabel, + models: window.scopeModels, + excludes: window.scopeExcludes, + }; + if (!isUsedUpTo(window, percent) || !usageScopeHoldsModel(scope, modelName)) continue; + const resetsAtMs = usageResetTimeMs(window.resetsAt); + if (resetsAtMs !== undefined && resetsAtMs <= nowMs) continue; + return true; + } + } + return false; +} + function readAccountUsageBlockAt( accountUsage: ServerProviderAccountUsage | undefined, nowMs: number,