From 93fb4b7db35e511a6105fa98cf15cb028efc6ced Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Mon, 23 Nov 2026 19:16:49 -0500 Subject: [PATCH] feat: enable Antigravity steering and add global mid-turn send setting Antigravity had active-turn steering disabled because a steer could be recorded as accepted before the prompt sender wrote it to agy, and the global mid-turn send preference had no row in Settings and was overwritten whenever the composer menu changed. Wait for steer delivery before accepting (bounded so Stop cannot block), interrupt the prompt sender before shutdown drain, fail steers queued behind a failed turn setup, register ordered ACP request handlers atomically on enqueue, and enable ANTIGRAVITY_STEERS. Expose followUpDelivery under Settings -> General -> Chat & diffs defaulting to Steer now, and make the composer send menu override it per thread without mutating the global setting. --- apps/server/src/guide/topics.ts | 2 +- apps/server/src/provider/acp/AcpAdapter.ts | 58 ++++++++++- .../src/provider/acp/AcpSessionRuntime.ts | 9 +- .../antigravity/AntigravityTurns.test.ts | 97 ++++++++++++------- .../provider/antigravity/AntigravityTurns.ts | 3 +- .../components/ChatView.browser-harness.tsx | 2 + apps/web/src/components/ChatView.tsx | 31 ++++-- .../src/components/ChatView.turns.browser.tsx | 21 +++- apps/web/src/components/chat/ChatComposer.tsx | 16 ++- .../settings/SettingsPanels.browser.tsx | 37 +++++++ .../components/settings/SettingsPanels.tsx | 42 ++++++++ .../settings/settingsRowRegistry.tsx | 2 + apps/web/src/followUpDeliveryStore.ts | 54 +++++++++++ docs/providers/antigravity.md | 13 ++- packages/contracts/src/settings.ts | 5 +- packages/effect-acp/src/protocol.ts | 17 +++- packages/shared/src/appPlaces.ts | 23 +++++ 17 files changed, 365 insertions(+), 67 deletions(-) create mode 100644 apps/web/src/followUpDeliveryStore.ts diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 5aae2bc98..19ce0dbd5 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -56,7 +56,7 @@ A repository can already have worktrees that Threadlines did not make (git workt The agent and model a new thread starts with is {place:threads.agent}. You can switch model or agent at any time from the model button in the composer, which also holds the agent's effort. Beside it sit Build or Plan (one click switches, as does Shift+Tab in the message box) and the access level; on a narrow window they show just their icons, and on phones both live in the model button's panel instead. -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. +While an agent works, {place:general.followUpDelivery} sets how a message goes by default (Steer now adds it to the reply in progress, Send when done holds it for the next one), and the arrow beside the send button overrides it for the current thread. 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. diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index c748e2733..4afe68d73 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -169,6 +169,8 @@ const ACP_SESSION_COMMANDS_INTERVAL_MS = 5_000; * conversation in a fresh one. */ const ACP_CANCEL_DEADLINE = Duration.seconds(15); +/** How long a steer waits to be written to the agent before failing so Stop is never blocked. */ +const ACP_STEER_DELIVERY_TIMEOUT = Duration.seconds(15); /** How long a revert lets the agent stop its work before its session ends. */ const ACP_REVERT_WIND_DOWN = Duration.seconds(3); /** @@ -420,7 +422,7 @@ interface AcpMachinePrompt { readonly resolvedModel: string | undefined; /** The context preamble this prompt carries; back to the session if it never goes out. */ readonly preamble: string | undefined; - /** A send's: hears whether its prompt was written to the agent (`reportDelivery`). */ + /** A send's or a steer's: hears whether its prompt was written to the agent (`reportDelivery`). */ readonly delivered: Deferred.Deferred | undefined; } @@ -467,6 +469,8 @@ interface AcpMachineSession { readonly model: string | undefined; readonly resolvedModel: string | undefined; readonly planMode: AcpPromptPlanMode | undefined; + /** Set when the turn's opening prompt failed before being written to the agent. */ + setupFailed?: Cause.Cause; } >; readonly timers: Map>; @@ -478,6 +482,8 @@ interface AcpMachineSession { * every prompt the machine sent before it. */ readonly outbox: Queue.Queue; + /** Interrupted on session stop before draining `sessionStopping` so no late write slips through. */ + senderFiber?: Fiber.Fiber; } /** @@ -1454,6 +1460,9 @@ export function makeAcpAdapter( // after everything already queued (an answer and its usage, a turn's // end), and only then is it stopped. const machine = ctx.machine; + if (machine?.senderFiber !== undefined) { + yield* Fiber.interrupt(machine.senderFiber); + } const drained = machine === undefined || ctx.notificationFiber === undefined ? false @@ -2790,7 +2799,9 @@ export function makeAcpAdapter( ctx.notificationFiber = notificationFiber; if (ctx.machine !== undefined) { - yield* runPromptSender(ctx, ctx.machine).pipe(Effect.forkIn(sessionScope)); + ctx.machine.senderFiber = yield* runPromptSender(ctx, ctx.machine).pipe( + Effect.forkIn(sessionScope), + ); } sessions.set(input.threadId, ctx); // A turn the machine holds open waits on no request the exit would @@ -3180,11 +3191,25 @@ export function makeAcpAdapter( ) => Effect.gen(function* () { const sent = machine.prompts.get(prompt); - if (sent === undefined) return; + if (sent === undefined || ctx.stopped) return; + const turnData = machine.turns.get(sent.turnId); + // If the turn's opening prompt failed before reaching the agent, a + // steer queued behind it must never go out alone under the old mode. + if (sent.index > 1 && turnData?.setupFailed !== undefined) { + const setupFailure = turnData.setupFailed; + yield* ctx.acp.inOrder( + Effect.suspend(() => { + sent.exit = Exit.failCause(setupFailure); + return answerMachinePrompt(ctx, prompt); + }).pipe(Effect.asVoid), + ); + return; + } const exit = yield* Effect.exit( Effect.gen(function* () { if (sent.configure !== undefined) yield* sent.configure; yield* seam({ point: "promptSetup", prompt }); + if (ctx.stopped) return; // Where the agent's records stand as this prompt goes out. sent.watch = machineOptions?.outcome === undefined @@ -3200,6 +3225,7 @@ export function makeAcpAdapter( }).pipe(Effect.as(undefined)), ), ); + if (ctx.stopped) return; const promptMeta = descriptor.promptMeta?.(sent.turnId); yield* ctx.acp.promptInOrder( prompt, @@ -3213,6 +3239,9 @@ export function makeAcpAdapter( ); // A stopping session ends the turn itself. if (Exit.isSuccess(exit) || Cause.hasInterruptsOnly(exit.cause)) return; + if (sent.index === 1 && turnData !== undefined) { + turnData.setupFailed = exit.cause; + } yield* ctx.acp.inOrder( Effect.suspend(() => { sent.exit = Exit.failCause(exit.cause); @@ -3763,6 +3792,7 @@ export function makeAcpAdapter( "turn/steer", ); const reply = yield* Deferred.make(); + const delivered = yield* Deferred.make(); const steerId = `steer:${crypto.randomUUID()}`; machine.callers.set(steerId, { prompt: { @@ -3771,7 +3801,7 @@ export function makeAcpAdapter( model: undefined, resolvedModel: undefined, preamble: undefined, - delivered: undefined, + delivered, }, planMode: undefined, reply, @@ -3797,6 +3827,26 @@ export function makeAcpAdapter( answer.rejected, ); } + // Returns once the prompt was written to the agent: if the process + // exited or the session stopped first, the steer never reached it. + // Bounded so a stalled stdin pipe cannot block Stop behind this call. + const written = yield* Deferred.await(delivered).pipe( + Effect.timeoutOption(ACP_STEER_DELIVERY_TIMEOUT), + ); + if (Option.isNone(written)) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/steer", + detail: `${descriptor.presentation.displayName} did not accept this message in time.`, + }); + } + if (!written.value) { + return yield* new ProviderAdapterRequestError({ + provider: PROVIDER, + method: "turn/steer", + detail: `${descriptor.presentation.displayName} stopped before this message could be sent.`, + }); + } return { threadId: input.threadId, turnId: answer.accepted, diff --git a/apps/server/src/provider/acp/AcpSessionRuntime.ts b/apps/server/src/provider/acp/AcpSessionRuntime.ts index 3c07f0581..01a75abd5 100644 --- a/apps/server/src/provider/acp/AcpSessionRuntime.ts +++ b/apps/server/src/provider/acp/AcpSessionRuntime.ts @@ -1193,7 +1193,14 @@ const makeAcpSessionRuntime = ( // sent after it is handled before this is queued. const onAnswer = (answer: Exit.Exit) => Effect.gen(function* () { - yield* queueSent; + // Only a reply from the agent (success or JSON-RPC error) proves + // the prompt was written; a synthetic transport failure does not. + if ( + Exit.isSuccess(answer) || + Schema.is(EffectAcpErrors.AcpRequestError)(Cause.squash(answer.cause)) + ) { + yield* queueSent; + } yield* Ref.update(promptsInFlightRef, (count) => count - 1); // As `prompt`: the answer ends the prompt's reply, unless a turn // the agent began itself, or a newer prompt, carries one on. diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts index b04d93aa0..f5187ac7a 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.test.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.test.ts @@ -177,12 +177,6 @@ const startAgy = ( }; }); -/** Steering, which Antigravity ships without (`ANTIGRAVITY_STEERS`), on for one test. */ -const withSteering = (descriptor: AgyDescriptor): AgyDescriptor => ({ - ...descriptor, - turnMachine: { ...descriptor.turnMachine!, steer: true }, -}); - const completedTurns = (events: ReadonlyArray) => events.flatMap((event) => (event.type === "turn.completed" ? [event] : [])); @@ -414,7 +408,7 @@ describe("Antigravity turns", () => { it.live("steers a running turn with a second prompt, never cancelling it", () => Effect.gen(function* () { - const agy = yield* startAgy("steer", withSteering); + const agy = yield* startAgy("steer"); expect(agy.adapter.capabilities.activeTurnSteering).toBe("supported"); const { turnId } = yield* agy.adapter.sendTurn({ threadId: agy.threadId, @@ -732,7 +726,7 @@ describe("Antigravity turns, the hard cases", () => { it.live("steers without inheriting the error the earlier prompt left in the log", () => Effect.gen(function* () { - const agy = yield* startAgy("steer-log-error", withSteering); + const agy = yield* startAgy("steer-log-error"); const { turnId } = yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", @@ -751,7 +745,7 @@ describe("Antigravity turns, the hard cases", () => { it.live("steers without inheriting an error the earlier prompt writes late", () => Effect.gen(function* () { - const agy = yield* startAgy("steer-late-log-error", withSteering); + const agy = yield* startAgy("steer-late-log-error"); const { turnId } = yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", @@ -772,7 +766,7 @@ describe("Antigravity turns, the hard cases", () => { "fails a steer whose own error is logged before the earlier prompt answers (finding 5)", () => Effect.gen(function* () { - const agy = yield* startAgy("steer-own-log-error", withSteering); + const agy = yield* startAgy("steer-own-log-error"); const { turnId } = yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", @@ -1063,21 +1057,22 @@ describe("Antigravity turn driver, the orderings", () => { it.live("sends a steer only after the prompt it steers, whose setup ran first (finding 2)", () => Effect.gen(function* () { const gate = yield* makeGate((seam) => seam.point === "promptSetup" && seam.prompt === 1); - const agy = yield* startAgy("steer", withSteering, "full-access", gate.seams); - // The send returns once its prompt is written, so it waits on the gate too. + const agy = yield* startAgy("steer", undefined, "full-access", gate.seams); + // Both calls return once their prompts are written, so both wait on the gate. const sending = yield* agy.adapter .sendTurn({ threadId: agy.threadId, input: "first message", attachments: [] }) .pipe(Effect.forkScoped); yield* gate.reached; const started = agy.events.find((event) => event.type === "turn.started"); const turnId = started!.turnId!; - // The first prompt's setup hasn't returned; the steer is taken anyway. - yield* agy.adapter.steerTurn!({ + // The first prompt's setup hasn't returned; the steer queues behind it and waits to write. + const steering = yield* agy.adapter.steerTurn!({ threadId: agy.threadId, expectedTurnId: turnId, input: "the steer", - }); + }).pipe(Effect.forkScoped); yield* Effect.sleep("200 millis"); + expect(steering.pollUnsafe()).toBeUndefined(); const prompts = (frames: ReadonlyArray>) => frames.flatMap((frame) => frame.method === "session/prompt" ? [JSON.stringify(frame.params)] : [], @@ -1085,6 +1080,7 @@ describe("Antigravity turn driver, the orderings", () => { expect(prompts(yield* agy.frames())).toEqual([]); yield* gate.release; expect((yield* Fiber.join(sending)).turnId).toBe(turnId); + expect((yield* Fiber.join(steering)).turnId).toBe(turnId); yield* agy.waitFor((events) => completedTurns(events).length === 1); const sent = prompts(yield* agy.frames()); expect(sent).toHaveLength(2); @@ -1311,7 +1307,7 @@ describe("Antigravity turn driver, the orderings", () => { it.live("lets go of each prompt's record once its answer is in, a steered one's too", () => Effect.gen(function* () { const gate = yield* makeGate(() => false); - const agy = yield* startAgy("steer", withSteering, "full-access", gate.seams); + const agy = yield* startAgy("steer", undefined, "full-access", gate.seams); const { turnId } = yield* agy.adapter.sendTurn({ threadId: agy.threadId, input: "go", @@ -1432,29 +1428,62 @@ describe("Antigravity turn driver, the orderings", () => { }).pipe(Effect.scoped, Effect.provide(testServices)), ); - it.live("queues a message sent mid-turn, steering being off for Antigravity", () => + it.live("fails a steer when the session stops before the steer is written to the agent", () => Effect.gen(function* () { - const agy = yield* startAgy("background"); - expect(agy.adapter.steerTurn).toBeUndefined(); - expect(agy.adapter.capabilities.activeTurnSteering).toBeUndefined(); - const first = yield* agy.adapter.sendTurn({ + const gate = yield* makeGate((seam) => seam.point === "promptSetup" && seam.prompt === 1); + const agy = yield* startAgy("steer", undefined, "full-access", gate.seams); + expect(agy.adapter.capabilities.activeTurnSteering).toBe("supported"); + const sending = yield* agy.adapter + .sendTurn({ threadId: agy.threadId, input: "first message", attachments: [] }) + .pipe(Effect.forkScoped); + yield* gate.reached; + const started = agy.events.find((event) => event.type === "turn.started"); + const turnId = started!.turnId!; + const steering = yield* agy.adapter.steerTurn!({ threadId: agy.threadId, - input: "build it", - attachments: [], + expectedTurnId: turnId, + input: "never written", + }).pipe(Effect.exit, Effect.forkScoped); + yield* agy.waitFor(() => + gate.seen.some((seam) => seam.point === "stepCommitted" && seam.event === "steer"), + ); + yield* agy.adapter.stopSession(agy.threadId); + expect((yield* Fiber.join(sending)).undelivered).toBe(true); + expect(Exit.isFailure(yield* Fiber.join(steering))).toBe(true); + const prompts = (yield* agy.frames()).filter((frame) => frame.method === "session/prompt"); + expect(prompts).toHaveLength(0); + }).pipe(Effect.scoped, Effect.provide(testServices)), + ); + + it.live("does not send a steer alone when its turn's opening prompt fails mode setup first", () => + Effect.gen(function* () { + const agy = yield* startAgy("mode-fails-once", undefined, "auto-accept-edits", undefined, { + version: 1, + fromProvider: ProviderDriverKind.make("claudeAgent"), + entries: [{ kind: "message", role: "user", text: "the earlier conversation" }], }); - // Sent while the first prompt runs: it waits for that turn to end. - const second = yield* agy.adapter.sendTurn({ + const sending = yield* agy.adapter + .sendTurn({ + threadId: agy.threadId, + input: "plan it", + interactionMode: "plan", + attachments: [], + }) + .pipe(Effect.forkScoped); + yield* agy.waitFor((events) => events.some((event) => event.type === "turn.started")); + const turnId = agy.events.find((event) => event.type === "turn.started")!.turnId!; + const steering = yield* agy.adapter.steerTurn!({ threadId: agy.threadId, - input: "and then lint", - attachments: [], - }); - yield* agy.waitFor((events) => completedTurns(events).length === 2); - expect(completedTurns(agy.events).map((event) => event.turnId)).toEqual([ - first.turnId, - second.turnId, - ]); + expectedTurnId: turnId, + input: "also check tests", + }).pipe(Effect.exit, Effect.forkScoped); + const first = yield* Fiber.join(sending); + expect(first.undelivered).toBe(true); + expect(Exit.isFailure(yield* Fiber.join(steering))).toBe(true); + yield* agy.waitFor((events) => completedTurns(events).length === 1); + expect(completedTurns(agy.events)[0]?.payload.state).toBe("failed"); const prompts = (yield* agy.frames()).filter((frame) => frame.method === "session/prompt"); - expect(prompts).toHaveLength(2); + expect(prompts).toHaveLength(0); }).pipe(Effect.scoped, Effect.provide(testServices)), ); }); diff --git a/apps/server/src/provider/antigravity/AntigravityTurns.ts b/apps/server/src/provider/antigravity/AntigravityTurns.ts index 01a1cc202..3c8e16e66 100644 --- a/apps/server/src/provider/antigravity/AntigravityTurns.ts +++ b/apps/server/src/provider/antigravity/AntigravityTurns.ts @@ -50,8 +50,7 @@ export const ANTIGRAVITY_SILENT_WORK_LIMIT = Duration.minutes(30); * Whether a message sent mid-turn steers the running turn (a second * `session/prompt`, 1.5.0+). Off, it waits for the turn to end. */ -// Off until this is fixed: a steer is recorded as an accepted follow-up before the sender writes it, so a process exit then shows one the agent never got. -export const ANTIGRAVITY_STEERS = false; +export const ANTIGRAVITY_STEERS = true; const isRecord = (value: unknown): value is Record => typeof value === "object" && value !== null && !Array.isArray(value); diff --git a/apps/web/src/components/ChatView.browser-harness.tsx b/apps/web/src/components/ChatView.browser-harness.tsx index ffccaab49..71adab9aa 100644 --- a/apps/web/src/components/ChatView.browser-harness.tsx +++ b/apps/web/src/components/ChatView.browser-harness.tsx @@ -80,6 +80,7 @@ import { closeProjectSetupDialog } from "./ProjectSetupDialog"; import { closeThreadMoveDialog } from "./ThreadMoveDialog"; import { closeMoveThreadsDialog } from "./MoveThreadsDialog"; import { useComposerDraftStore, DraftId } from "../composerDraftStore"; +import { resetFollowUpDeliveryOverridesForTests } from "../followUpDeliveryStore"; import { connectEnvironmentBrowserHost } from "./browser/previewAutomationHost"; import { closeThreadBrowser, useBrowserPageWatchers } from "./browser/BrowserHostLayer"; import { @@ -3489,6 +3490,7 @@ export function registerChatViewSuiteHooks(): void { resetSavedEnvironmentRegistryStoreForTests(); resetSavedEnvironmentRuntimeStoreForTests(); resetRightPanelTabsForTests(); + resetFollowUpDeliveryOverridesForTests(); __resetComposerPullRequestDismissalsForTests(); Reflect.deleteProperty(window, "desktopBridge"); useComposerDraftStore.setState({ diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index d5ecb29c3..42c6661a3 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -88,6 +88,7 @@ import { useRoomAgentNames, useRoomRecipientStore, } from "../rooms"; +import { resolveFollowUpDelivery, useFollowUpDeliveryStore } from "../followUpDeliveryStore"; import { ELECTRON_HEADER_HEIGHT_CLASS } from "../desktopChrome"; import { useDevicesSupported } from "./device/deviceState"; import { isElectron } from "../env"; @@ -228,7 +229,7 @@ import { } from "~/projectScripts"; import { newCommandId, newMessageId, newThreadId } from "~/lib/utils"; import { formatProviderDriverKindLabel } from "../providerModels"; -import { useSettings, useUpdateSettings } from "../hooks/useSettings"; +import { getClientSettings, useSettings, useUpdateSettings } from "../hooks/useSettings"; import { roomsEnabledFor } from "../hooks/useRoomsEnabled"; import { useNewThreadComposerFocus } from "../newThreadComposerFocus"; import { @@ -5369,15 +5370,30 @@ export default function ChatView(props: ChatViewProps) { return waiting.length === 0 && !pendingUserInputsRef.current.some(isBlockingUserInput); }; - const readSendMenuChoice = () => - `${settings.followUpDelivery}:${ + const readEffectiveFollowUpDelivery = (threadRef: ScopedThreadRef | null) => { + const globalDefault = getClientSettings().followUpDelivery; + return threadRef === null + ? globalDefault + : resolveFollowUpDelivery( + useFollowUpDeliveryStore.getState().overridesByThreadKey, + threadRef, + globalDefault, + ); + }; + + const readSendMenuChoice = () => { + const threadRef = + activeThread !== undefined ? scopeThreadRef(environmentId, activeThread.id) : null; + return `${readEffectiveFollowUpDelivery(threadRef)}:${ activeThread !== undefined && + threadRef !== null && isRoomWaitChosen( useRoomRecipientStore.getState().waitChosen, - scopeThreadRef(environmentId, activeThread.id), + threadRef, activeThread.latestTurn?.turnId, ) }`; + }; const onSend = async (e?: { preventDefault: () => void }, options?: ComposerSendOptions) => { e?.preventDefault(); @@ -5781,13 +5797,16 @@ export default function ChatView(props: ChatViewProps) { const approvalDeclines = askOnTheSide || queueForAnotherAgent ? [] : pendingApprovals; // "Send when done" holds the message on the server until the turn ends; // the queue list shows it from there, so it gets no steering row. + const configuredFollowUpDelivery = readEffectiveFollowUpDelivery( + scopeThreadRef(environmentId, threadIdForSend), + ); const followUpDelivery = queueForAnotherAgent ? "queue" : approvalDeclines.length > 0 ? "steer" : oppositeDelivery - ? oppositeFollowUpDelivery(settings.followUpDelivery) - : settings.followUpDelivery; + ? oppositeFollowUpDelivery(configuredFollowUpDelivery) + : configuredFollowUpDelivery; const shouldCreateWorktree = firstWorkNeedsWorktree({ isFirstWork: isFirstMessage, envMode: sendEnvMode, diff --git a/apps/web/src/components/ChatView.turns.browser.tsx b/apps/web/src/components/ChatView.turns.browser.tsx index b75890bb1..bf0197dfa 100644 --- a/apps/web/src/components/ChatView.turns.browser.tsx +++ b/apps/web/src/components/ChatView.turns.browser.tsx @@ -1506,6 +1506,8 @@ describe("ChatView (full app): plans, questions and turn controls", () => { await waitForComposerText("and update the changelog"); await page.getByLabelText("Choose how this message is sent").click({ timeout: 5_000 }); await page.getByRole("menuitemradio", { name: "Send when done" }).click({ timeout: 5_000 }); + // Overriding in the composer does not change the global setting. + expect(getClientSettings().followUpDelivery).toBe("steer"); await page.getByLabelText("Send when this reply finishes").click({ timeout: 5_000 }); await vi.waitFor(() => { expect(dispatched("thread.follow-up.submit")).toMatchObject({ @@ -1575,11 +1577,28 @@ describe("ChatView (full app): plans, questions and turn controls", () => { await sendWith("steer this one", "{Enter}"); expect(submitted().at(-1)).toMatchObject({ delivery: "steer" }); - // The menu says "Send when done". + // The global default is "Send when done", and untouched threads follow it. updateSettings({ followUpDelivery: "queue" }); await sendWith("correct it now", "{Control>}{Enter}{/Control}"); expect(submitted().at(-1)).toMatchObject({ delivery: "steer" }); expect(getClientSettings().followUpDelivery).toBe("queue"); + + // Overriding back to "Steer now" in the composer overrides only this thread. + await page + .getByTestId("composer-editor") + .fill("override for this thread", { timeout: 5_000 }); + await waitForComposerText("override for this thread"); + await page.getByLabelText("Choose how this message is sent").click({ timeout: 5_000 }); + await page.getByRole("menuitemradio", { name: "Steer now" }).click({ timeout: 5_000 }); + await page.getByLabelText("Steer active turn").click({ timeout: 5_000 }); + await vi.waitFor(() => { + expect(submitted().at(-1)).toMatchObject({ + delivery: "steer", + message: { text: "override for this thread" }, + }); + }); + await waitForComposerText(""); + expect(getClientSettings().followUpDelivery).toBe("queue"); } finally { updateSettings({ followUpDelivery: "steer" }); await mounted.cleanup(); diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsx index d891c6727..73ec770bd 100644 --- a/apps/web/src/components/chat/ChatComposer.tsx +++ b/apps/web/src/components/chat/ChatComposer.tsx @@ -18,6 +18,7 @@ import type { TurnId, } from "@threadlines/contracts"; import { saveComposerDraftAttachments } from "../../composerDraftAttachmentSave"; +import { resolveFollowUpDelivery, useFollowUpDeliveryStore } from "../../followUpDeliveryStore"; import { publishComposerImageSupport } from "./composerImageSupport"; import { type PromptRecall, recallablePrompts, stepPromptRecall } from "./composerPromptRecall"; import { containsWorkflowKeyword } from "@threadlines/shared/workflowRuns"; @@ -134,7 +135,7 @@ import { } from "./ComposerPrimaryActions"; import { useConnectedComputerCapability } from "../../environments/computerCapabilities"; import { useEnvironmentServerSetting } from "../../hooks/useEnvironmentServerSetting"; -import { useSettings, useUpdateSettings } from "../../hooks/useSettings"; +import { useSettings } from "../../hooks/useSettings"; import { useStableHandlers } from "../../hooks/useStableIdentity"; import { useAgentWarmUp } from "../../hooks/useAgentWarmUp"; import { getThreadInFlightStatus } from "../../lib/threadSort"; @@ -1996,11 +1997,16 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) const meterShowsSlotHolder = recipientAgentId === (activeThread?.session?.participantId ?? null); const collapsedComposerPrimaryActionDisabled = isSendBusy || isConnecting || !composerSendState.hasSendableContent; - const followUpDelivery = useSettings((settings) => settings.followUpDelivery); - const { updateSettings } = useUpdateSettings(); + const defaultFollowUpDelivery = useSettings((settings) => settings.followUpDelivery); + const followUpDelivery = useFollowUpDeliveryStore((state) => + resolveFollowUpDelivery(state.overridesByThreadKey, routeThreadRef, defaultFollowUpDelivery), + ); const handleFollowUpDeliveryChange = useCallback( - (delivery: FollowUpDelivery) => updateSettings({ followUpDelivery: delivery }), - [updateSettings], + (delivery: FollowUpDelivery) => + useFollowUpDeliveryStore + .getState() + .setOverride(routeThreadRef, delivery, defaultFollowUpDelivery), + [defaultFollowUpDelivery, routeThreadRef], ); // Rooms: while another agent works, a message for this one is asked now // (answered read-only on the side) or, when picked for this message, waits diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index 5abfec466..9c60ad06c 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -1686,6 +1686,43 @@ describe("GeneralSettingsPanel observability", () => { }); }); + it("changes and resets the global mid-turn sending default in General settings", async () => { + const updateClientSettings = vi.fn(async (patch: object) => patch); + window.nativeApi = { + persistence: { + getClientSettings: vi.fn().mockResolvedValue(null), + updateClientSettings, + subscribeClientSettings: () => () => undefined, + }, + server: { + updateSettings: vi.fn(async () => undefined), + }, + } as unknown as LocalApi; + setServerConfigSnapshot(createBaseServerConfig()); + + mounted = await renderWithTestRouter( + + + , + ); + + const trigger = page.getByRole("combobox", { name: "Sending while an agent works" }); + await expect.element(trigger).toHaveTextContent("Steer now"); + + await trigger.click(); + await page.getByRole("option", { name: "Send when done" }).click(); + await expect.element(trigger).toHaveTextContent("Send when done"); + await vi.waitFor(() => { + expect(updateClientSettings).toHaveBeenCalledWith({ followUpDelivery: "queue" }); + }); + + await page.getByRole("button", { name: "Reset sending while an agent works" }).click(); + await expect.element(trigger).toHaveTextContent("Steer now"); + await vi.waitFor(() => { + expect(updateClientSettings).toHaveBeenCalledWith({ followUpDelivery: "steer" }); + }); + }); + it("creates and shows a pairing link when network access is enabled", async () => { window.desktopBridge = createDesktopBridgeStub({ serverExposureState: { diff --git a/apps/web/src/components/settings/SettingsPanels.tsx b/apps/web/src/components/settings/SettingsPanels.tsx index d5c163213..d5dfca31a 100644 --- a/apps/web/src/components/settings/SettingsPanels.tsx +++ b/apps/web/src/components/settings/SettingsPanels.tsx @@ -31,6 +31,7 @@ import { agentThreadsShareWorktrees, } from "@threadlines/shared/serverSettings"; import { + FOLLOW_UP_DELIVERY_LABELS, OPEN_LINKS_IN_LABELS, placeById, TIMESTAMP_FORMAT_LABELS, @@ -1220,6 +1221,46 @@ function UnifiedSwitchRow({ ); } +export function FollowUpDeliveryRow() { + const followUpDelivery = useSettings((settings) => settings.followUpDelivery); + const { updateSettings } = useUpdateSettings(); + return ( + + updateSettings({ + followUpDelivery: DEFAULT_UNIFIED_SETTINGS.followUpDelivery, + }) + } + /> + ) : null + } + control={ + + } + /> + ); +} + export function TimeFormatRow() { const timestampFormat = useSettings((settings) => settings.timestampFormat); const { updateSettings } = useUpdateSettings(); @@ -1393,6 +1434,7 @@ export function GeneralSettingsPanel({ surface = "full" }: { surface?: "full" | {/* On a phone this one is the paired computer's: it sits under This Computer. */} {!isPhoneSurface ? : null} + diff --git a/apps/web/src/components/settings/settingsRowRegistry.tsx b/apps/web/src/components/settings/settingsRowRegistry.tsx index c476954d3..6cefee0cf 100644 --- a/apps/web/src/components/settings/settingsRowRegistry.tsx +++ b/apps/web/src/components/settings/settingsRowRegistry.tsx @@ -28,6 +28,7 @@ import { ChangedFilesInChatRow, ClearBrowserDataRow, DiagnosticsRow, + FollowUpDeliveryRow, ReportProblemRow, HideWhitespaceRow, OpenLinksRow, @@ -104,6 +105,7 @@ export const SETTINGS_ROWS = { "general.alertFailed": live(() => ), "general.alertsQuietAtComputer": live(AlertsQuietAtComputerRow), "general.streamReplies": live(AssistantStreamingRow), + "general.followUpDelivery": live(FollowUpDeliveryRow), "general.timeFormat": live(TimeFormatRow), "general.changedFilesInChat": live(ChangedFilesInChatRow), "general.agentsPanel": live(AgentsPanelRow), diff --git a/apps/web/src/followUpDeliveryStore.ts b/apps/web/src/followUpDeliveryStore.ts new file mode 100644 index 000000000..6e876164e --- /dev/null +++ b/apps/web/src/followUpDeliveryStore.ts @@ -0,0 +1,54 @@ +import type { FollowUpDelivery, ScopedThreadRef } from "@threadlines/contracts"; +import { scopedThreadKey } from "@threadlines/client-runtime"; +import { create } from "zustand"; + +interface FollowUpDeliveryOverrideState { + /** + * Per-thread composer overrides of the global `followUpDelivery` setting. + * In memory only: a reload falls back to the global setting. + */ + readonly overridesByThreadKey: Readonly>; + readonly setOverride: ( + threadRef: ScopedThreadRef, + delivery: FollowUpDelivery, + globalDefault: FollowUpDelivery, + ) => void; + readonly clearOverride: (threadRef: ScopedThreadRef) => void; +} + +export const useFollowUpDeliveryStore = create((set) => ({ + overridesByThreadKey: {}, + setOverride: (threadRef, delivery, globalDefault) => + set((state) => { + const key = scopedThreadKey(threadRef); + if (delivery === globalDefault) { + if (!(key in state.overridesByThreadKey)) return state; + const { [key]: _previous, ...rest } = state.overridesByThreadKey; + return { overridesByThreadKey: rest }; + } + if (state.overridesByThreadKey[key] === delivery) return state; + return { + overridesByThreadKey: { ...state.overridesByThreadKey, [key]: delivery }, + }; + }), + clearOverride: (threadRef) => + set((state) => { + const key = scopedThreadKey(threadRef); + if (!(key in state.overridesByThreadKey)) return state; + const { [key]: _previous, ...rest } = state.overridesByThreadKey; + return { overridesByThreadKey: rest }; + }), +})); + +/** Effective mid-turn delivery for a thread: its composer override, else the global setting. */ +export function resolveFollowUpDelivery( + overridesByThreadKey: Readonly>, + threadRef: ScopedThreadRef, + globalDefault: FollowUpDelivery, +): FollowUpDelivery { + return overridesByThreadKey[scopedThreadKey(threadRef)] ?? globalDefault; +} + +export function resetFollowUpDeliveryOverridesForTests() { + useFollowUpDeliveryStore.setState({ overridesByThreadKey: {} }); +} diff --git a/docs/providers/antigravity.md b/docs/providers/antigravity.md index bc8947915..0c218c02a 100644 --- a/docs/providers/antigravity.md +++ b/docs/providers/antigravity.md @@ -180,13 +180,12 @@ it. If the agent exits while a turn is held, the turn fails with that reason and the next message starts it again. -A message sent while Antigravity is answering waits for that turn to end, as with other agents. One -sent while the turn only waits on work Antigravity started ends that turn, and goes at once. -Prompts reach the agent in the order they were sent, each turn's mode and model setup first. -Threadlines can also steer a running turn with a second prompt, which the CLI takes into it -(1.5.0+), but that ships off (`ANTIGRAVITY_STEERS` in -`apps/server/src/provider/antigravity/AntigravityTurns.ts`): a steer is recorded as accepted before -it is written, so an agent that exits at that moment would leave a steer shown that it never got. +A message sent while Antigravity is answering steers the running turn with a second `session/prompt` +(1.5.0+) when Steer now is active, waiting until the prompt is written to `agy` before accepting it +(so an agent exit or stop before delivery fails the steer instead of recording one Antigravity never +got). When Send when done is active, the message waits for that turn to end. A message sent while +the turn only waits on work Antigravity started ends that turn, and goes at once. Prompts reach the +agent in the order they were sent, each turn's mode and model setup first. All of this is one state machine (`apps/server/src/provider/acp/AcpTurnMachine.ts`), stepped in order with the agent's updates. A prompt's answer takes its place among those updates where the diff --git a/packages/contracts/src/settings.ts b/packages/contracts/src/settings.ts index 4b2c5b77d..139a7de93 100644 --- a/packages/contracts/src/settings.ts +++ b/packages/contracts/src/settings.ts @@ -246,8 +246,9 @@ export const ClientSettingsSchema = Schema.Struct({ .pipe(Schema.withDecodingDefault(Effect.succeed(12))), // xterm's screen reader mode: an accessible copy of the terminal's text. terminalScreenReaderMode: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))), - // What the send button does with a message typed while a turn runs: add it - // to that turn, or hold it for the next one. The last choice sticks. + // Global default for what Enter does when sending a message while a turn + // runs: add it to that turn ("steer"), or hold it for the next one ("queue"). + // Applies to all providers; the composer's send menu can override it per thread. followUpDelivery: FollowUpDelivery.pipe(Schema.withDecodingDefault(Effect.succeed("steer"))), // Model favorites. Historically keyed by provider kind, now // widened to `ProviderInstanceId` so users can favorite a specific model diff --git a/packages/effect-acp/src/protocol.ts b/packages/effect-acp/src/protocol.ts index 3a1ae1fd2..a82b350a4 100644 --- a/packages/effect-acp/src/protocol.ts +++ b/packages/effect-acp/src/protocol.ts @@ -170,6 +170,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi message: RpcMessage.FromClientEncoded | RpcMessage.FromServerEncoded, written?: Deferred.Deferred, requestId?: string | number, + registerPending?: Effect.Effect, ) { // The RPC client's own control messages (an interrupted request, a stream // ack) would go out as `@effect/rpc/*` methods no ACP agent knows. @@ -196,9 +197,17 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi payload: typeof encoded === "string" ? encoded : new TextDecoder().decode(encoded), }); - // Nothing queues behind a pipe that is gone: it would wait forever. - if (pipeDown !== undefined) return yield* Effect.fail(pipeDown); - yield* Queue.offer(outgoing, { data: encoded, written, requestId }).pipe(Effect.asVoid); + // Register the answer handler and enqueue the frame together after the + // pipe check, so termination cannot fire an answer for a frame that was + // never placed on the outgoing queue. + yield* Effect.uninterruptible( + Effect.gen(function* () { + // Nothing queues behind a pipe that is gone: it would wait forever. + if (pipeDown !== undefined) return yield* Effect.fail(pipeDown); + if (registerPending !== undefined) yield* registerPending; + yield* Queue.offer(outgoing, { data: encoded, written, requestId }).pipe(Effect.asVoid); + }), + ); } else if (written !== undefined) { yield* Deferred.succeed(written, undefined); } @@ -636,7 +645,6 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi nextRequestId, (current) => [current, current + 1] as const, ); - yield* Ref.update(orderedPending, (pending) => new Map(pending).set(requestId, onAnswer)); const written = yield* Deferred.make(); // Returns once the agent's stdin took it; a request never written was // never sent, so it fails here and `onAnswer` hears nothing. @@ -644,6 +652,7 @@ export const makeAcpPatchedProtocol = Effect.fn("makeAcpPatchedProtocol")(functi { _tag: "Request", id: requestId, tag: method, payload, headers: [] }, written, requestId, + Ref.update(orderedPending, (pending) => new Map(pending).set(requestId, onAnswer)), ).pipe( Effect.andThen(Deferred.await(written)), Effect.catch((error) => diff --git a/packages/shared/src/appPlaces.ts b/packages/shared/src/appPlaces.ts index f30065de9..a41bf5225 100644 --- a/packages/shared/src/appPlaces.ts +++ b/packages/shared/src/appPlaces.ts @@ -21,6 +21,7 @@ import type { ClientSettingsPatch, ComputerLinkAccess, BrowserSearchEngine, + FollowUpDelivery, GeneralChatsPlacement, LinkOpenTarget, ModelSelection, @@ -367,6 +368,12 @@ export const GENERAL_CHATS_PLACEMENT_LABELS: Readonly> = { + steer: "Steer now", + queue: "Send when done", +}; + /** "Motion", as its control words each choice. */ export const THEME_MOTION_LABELS = { live: "Live", still: "Still" } as const; @@ -1168,6 +1175,22 @@ const ROWS = [ keywords: ["streaming"], ...editableServerSwitch("enableAssistantStreaming"), }, + { + id: "general.followUpDelivery", + kind: "row", + parent: "general.chatAndDiffs", + title: "Sending while an agent works", + about: "Default when sending during a reply. Override per thread in the composer.", + keywords: ["steer", "steer now", "send when done", "queue", "follow-up", "composer"], + scope: "device", + edit: { + lands: "device", + control: { kind: "choice", options: FOLLOW_UP_DELIVERY_LABELS }, + leaves: ["followUpDelivery"], + read: (settings) => settings.followUpDelivery, + patch: (value) => ({ followUpDelivery: value as FollowUpDelivery }), + }, + }, { id: "general.timeFormat", kind: "row",