Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Composer: steer, queue or restart a message sent while a bot works (#4069)
Milind Soni6d32b86b285b
diff --git a/server/admission-golden.test.ts b/server/admission-golden.test.tsindex 51712faa02..76376f829f 100644--- a/server/admission-golden.test.ts+++ b/server/admission-golden.test.ts@@ -12,6 +12,13 @@ describe("admission golden tables", () => {expect(admit("direct-busy", { ...plain, pendingComputerSelection: true })).toEqual({ action: "queue" });expect(admit("direct-busy", { ...plain, engineCanSteer: false })).toEqual({ action: "queue" });expect(admit("direct-busy", {})).toEqual({ action: "queue" });+ expect(admit("direct-busy", { ...plain, followUp: "steer" })).toEqual({ action: "steer" });+ expect(admit("direct-busy", { ...plain, followUp: "queue" })).toEqual({ action: "queue", chose: "queue" });+ expect(admit("direct-busy", { ...plain, followUp: "restart" })).toEqual({ action: "queue", chose: "restart" });+ // A turn that cannot be steered queues whatever was asked; only restart still ends it.+ expect(admit("direct-busy", { ...plain, engineCanSteer: false, followUp: "steer" })).toEqual({ action: "queue" });+ expect(admit("direct-busy", { ...plain, engineCanSteer: false, followUp: "queue" })).toEqual({ action: "queue" });+ expect(admit("direct-busy", { ...plain, engineCanSteer: false, followUp: "restart" })).toEqual({ action: "queue", chose: "restart" });});it("direct-busy: attachments steer into an engine that takes images mid-turn", () => {diff --git a/server/admission.ts b/server/admission.tsindex 8a5a6b7090..d9e962f4f9 100644--- a/server/admission.ts+++ b/server/admission.ts@@ -1,5 +1,7 @@// Purity is the contract: no IO, no store reads, no adapter calls. Callers gather state, call admit(), and apply the decision.+import type { FollowUp } from "../shared/follow-up.ts";+export type AdmissionSurface =| "direct-busy" // 1:1 send to a thread whose turn is live: steer-first| "direct" // 1:1 send on a settled thread: start now or park@@ -52,6 +54,8 @@ export interface AdmissionMessage {/** Steering into a turn waiting on a person's surface choice would race the choice. */pendingComputerSelection?: boolean;engineCanSteer?: boolean;+ /** What the person chose for a message sent while the turn runs; absent means steer where the turn can take it. */+ followUp?: FollowUp;/** Room queues drain one item per turn, so only the head may jump into the live speaker's turn. */isQueueHead?: boolean;speakerPresent?: boolean;@@ -73,7 +77,7 @@ export type AdmissionSteerBlock = "images";export type AdmissionDecision =| { action: "steer" }- | { action: "queue"; reason?: AdmissionQueueReason; blockedBy?: AdmissionSteerBlock }+ | { action: "queue"; reason?: AdmissionQueueReason; blockedBy?: AdmissionSteerBlock; chose?: Exclude<FollowUp, "steer"> }| { action: "start" }| { action: "refuse"; code: AdmissionRefusalCode };@@ -94,6 +98,10 @@ export function admit(): AdmissionDecision {switch (surface) {case "direct-busy": {+ // Restart waits for the Stop it asks for. A chosen queue counts only where the turn could take steering: one that+ // cannot queues anyway, as it always has (person-first may still stop it for the person's message).+ if (message.followUp === "restart") return { action: "queue", chose: "restart" };+ if (message.engineCanSteer === true && message.followUp === "queue") return { action: "queue", chose: "queue" };if (message.engineCanSteer !== true || message.pendingComputerSelection) return { action: "queue" };if (imagesBlockSteer(message)) return { action: "queue", blockedBy: "images" };return { action: "steer" };diff --git a/server/direct-send.ts b/server/direct-send.tsnew file mode 100644index 0000000000..c1fe4b33d9--- /dev/null+++ b/server/direct-send.ts@@ -0,0 +1,27 @@+// What a one-to-one send carries into acceptDirectSend (server/index.ts), and the receipt it answers with.+import type { FollowUp } from "../shared/follow-up.ts";+import type { ResolvedSender, SteerQueueReason } from "../shared/wire.ts";+import type { DataContext } from "./data-context.ts";+import type { Message } from "./store.ts";+import type { UsageTrigger } from "./usage-ledger.ts";++export interface DirectSendInput {+ botId: string;+ threadId: string;+ text: string;+ sendId?: string;+ replyTo?: Message;+ sender?: ResolvedSender;+ trigger: UsageTrigger;+ via?: "call";+ callId?: string;+ dataContext?: DataContext;+ personPresent: boolean;+ app?: { context?: string; fromApp?: Message["fromApp"]; pointed?: Message["pointed"] };+ /** Sent while the bot works: steer into the running turn, queue after it, or restart it (shared/follow-up.ts). */+ followUp?: FollowUp;+}++export type DirectSendReceipt =+ | { ok: true; threadId: string; message: Message; steered?: true }+ | { ok: true; queued: true; queueId: string; threadId: string; reason?: SteerQueueReason };diff --git a/server/host/person-stop.ts b/server/host/person-stop.tsindex f13cec5faf..d450ec51b9 100644--- a/server/host/person-stop.ts+++ b/server/host/person-stop.ts@@ -1,5 +1,5 @@// What a person's Stop does to a direct thread: the Stop button (POST /api/bots/:id/interrupt), a typed "stop"-// while the bot works (acceptDirectSend), and the pills for teammates a stop leaves running.+// while the bot works (acceptDirectSend), "Restart turn" from the send menu, and the pills for teammates a stop leaves running.import type { HandoffView } from "../coordinator.ts";import type { Handoffs } from "../delta-context.ts";import { isStopCommand } from "../room-holds.ts";@@ -57,6 +57,14 @@ export function createPersonStop(deps: PersonStopDeps) {return { ok: true as const, threadId, message };}+ /** "Restart turn": the message already waits in the queue, ahead of all but the person's own earlier messages, and the+ * queue survives Stop, so stopping the running turn starts it over with that message. Like a typed stop, only a+ * person's own send may end the turn. */+ async function restartForPerson(botId: string, threadId: string, trigger: UsageTrigger): Promise<void> {+ if (trigger.kind !== "user" && trigger.kind !== "owner") return;+ await stopThreadForPerson(botId, threadId);+ }+/** Stop left teammates mid-turn: one pill each links to the conversation where Stop reaches that turn. */function noteTeammatesLeftRunning(threadId: string, running: HandoffView[]): void {if (!store.botByThread(threadId) && !store.groupByThread(threadId)) return;@@ -72,5 +80,5 @@ export function createPersonStop(deps: PersonStopDeps) {}}- return { stopThreadForPerson, stopOnTypedCommand, noteTeammatesLeftRunning };+ return { stopThreadForPerson, stopOnTypedCommand, restartForPerson, noteTeammatesLeftRunning };}diff --git a/server/index.ts b/server/index.tsindex 7910ae5821..e307900092 100644--- a/server/index.ts+++ b/server/index.ts@@ -84,7 +84,7 @@ import { groupTurnCwd } from "./room-cwd.ts";import { RoomTurnDeadline, RoomTurnStallRegistry, effectiveRoomTurnTimeoutMinutes, parseConversationTurnTimeout, roomTurnTimeoutMessage } from "./room-turn-timeout.ts";import { roomTurnEnd, type RoomClaimEnd } from "./room-turn-end.ts";import { applyHoldDirective, classifyHoldDirective, heldMemberLine, rememberHeldMessage, stopWordPlacement } from "./room-holds.ts";-import { createPersonStop } from "./host/person-stop.ts";+import { createPersonStop } from "./host/person-stop.ts"; import type { DirectSendInput, DirectSendReceipt } from "./direct-send.ts";import { finishedWithoutSummaryLine, ROOM_SUMMARY_REASK, roomTurnNarrationIds, roomTurnReply } from "./room-reply.ts";import { pickComputer } from "./computer-selection.ts";import * as boat from "./boat.ts"; import { keyHint, keyStatus, nestedKeyStatus, withoutKeyHints } from "./key-hint.ts";@@ -104,7 +104,7 @@ import { createDataRoutes } from "./data/routes.ts";import { DataSheetRegistry } from "./data/sheet.ts";import { DataFailure } from "./data/types.ts";import { TeamComputers, teamComputerOwner, type TeamComputerRecord } from "./team-computers.ts";-import { isEffortLevel, type CardAnswerer, type ResolvedSender, type SignInRequestCardData, type SteerQueueReason, type WireBot, type WireGroup, type WireTask } from "../shared/wire.ts";+import { isEffortLevel, type CardAnswerer, type ResolvedSender, type SignInRequestCardData, type WireBot, type WireGroup, type WireTask } from "../shared/wire.ts";import { isPersistentQuestionCard, shouldSettleRequestCard } from "../shared/ask-question.ts";import { parseToolScope } from "../shared/tool-scope.ts";import type { TeamComputersPayload } from "../shared/team-computer.ts";@@ -2849,7 +2849,7 @@ const { cloudLendingTurn, cloudLendingRefusalNotice, cloudLendingRefusal, cloudTconst actingPeople = createActingPeople({ store, direct: (threadId) => directRequestOwners.get(threadId), roomRun, handed: new HandedPeople(join(DATA_DIR, HANDED_PEOPLE_FILE)) });const computerAsks = CLOUD_PERSONAL ? createComputerAsksHost({ store, notify, lending: sharedComputers, principal: CLOUD_HOME_LENDER, threadBusy, queued: hasQueuedSteeredMessages, continueRequest: startTurn,refusal: (turn) => sharedComputerPrincipal(turn) ? null : cloudLendingRefusalNotice(turn) ?? "This conversation can't use your computer.", request: (threadId) => directRequestOwners.get(threadId), active: (turn) => internalCapabilityIsActive(turn as InternalCapability) }) : null;-const { stopThreadForPerson, stopOnTypedCommand, noteTeammatesLeftRunning } = createPersonStop({+const { stopThreadForPerson, stopOnTypedCommand, restartForPerson, noteTeammatesLeftRunning } = createPersonStop({store, routines: () => routines, handoffs: () => handoffs, interruptDirectThread, clearUnattended,stopGoal: (threadId) => oneOnOneGoals.stop(threadId), markStopped: (threadId) => personStops.stop(threadId, liveTurns.running(threadId), directTurnDispatchClaims.has(threadId)),}); const teamMessages = createTeamMessages({ team: CLOUD_TEAM, dataDir: DATA_DIR, store, people: teamOwners.people, personName: teamHost.personName, audienceOf: teamHost.audienceOf, starters: threadStarters, notify, sees: (person) => visibleTo(person.role === "member" ? { kind: "member", email: person.email } : { kind: "all", email: person.email }), inbox: { askedPerson: teamOwners.routing.askedPerson, changed: (threadId) => { const bot = store.botByThread(threadId); if (bot) broadcast({ kind: "bot", bot: wireBot(bot) }); }, ensureOwnBot: (email) => { ensureDefaultBot(store, { dataDir: DATA_DIR, person: email, team: CLOUD_TEAM?.name ?? null }); }, handedFrom: (threadId) => { const from = delegatorOf(threadId); return from && from.threadId !== threadId ? from.threadId : null; }, continueTurn: relayedTurn({ store, startTurn, state: (botId, threadId) => ({ atCapacity: botAtThreadCapacity(botId, threadId), threadBusy: threadBusy(botId, threadId), groupTurn: roomTurnHolds(activeGroupTurnForBot(botId), threadId, false), parksBehindCoordination: parksBehindCoordination(botId, threadId) }) }), representative: { generate: async (botId, prompt) => (await sideJobs.text("representative", botId)?.generateText(prompt, { timeoutMs: 60_000 })) ?? null, busy: createPersonCalendar({ access: (person) => teamConnections.personApps().includes("googlecalendar") ? teamConnections.people.appsAccess(person) : null, connected: async (access) => (await composio.connectedServices(cfg, access)).googlecalendar?.connected === true, relay: (payload, session, signal, access) => composio.relayMcp(cfg, payload as never, session, undefined, signal, access) }).busy } } });@@ -7321,10 +7321,6 @@ async function startOrQueueDirectMessage(botId: string, threadId: string, text:return { ok: true as const, threadId, message };}-type DirectSendReceipt =- | { ok: true; threadId: string; message: Message; steered?: true }- | { ok: true; queued: true; queueId: string; threadId: string; reason?: SteerQueueReason };-class DirectSendRefused extends Error {readonly status: number;readonly body: Record<string, unknown>;@@ -7348,23 +7344,10 @@ function directSendRefusal(botId: string, threadId: string): DirectSendRefused |}async function acceptDirectSend(- input: {- botId: string;- threadId: string;- text: string;- sendId?: string;- replyTo?: Message;- sender?: ResolvedSender;- trigger: UsageTrigger;- via?: "call";- callId?: string;- dataContext?: DataContext;- personPresent: boolean;- app?: { context?: string; fromApp?: Message["fromApp"]; pointed?: Message["pointed"] };- },+ input: DirectSendInput,guardedStart?: (currentAtStart: BotRecord) => Promise<DirectSendReceipt>,): Promise<DirectSendReceipt> {- const { botId, threadId, text, sendId, replyTo, sender, trigger, via, callId, dataContext, personPresent, app } = input;+ const { botId, threadId, text, sendId, replyTo, sender, trigger, via, callId, dataContext, personPresent, app, followUp } = input;const refused = directSendRefusal(botId, threadId);if (refused) throw refused;return sendSequencer.run(@@ -7429,7 +7412,10 @@ async function acceptDirectSend(engineCanSteerImages: engineSteersImages(instance),pendingComputerSelection: Boolean(computerSelectionTurns.get(threadId)?.selected),engineCanSteer: Boolean(instance?.adapter.capabilities.queueing && instance.adapter.steer),+ followUp,});+ // A chosen wait (queue, or restart's Stop) is never cut short by person-first.+ const chose = busyAdmission.action === "queue" ? busyAdmission.chose : undefined;if (busyAdmission.action === "steer" && instance?.adapter.steer) {const prompt = (app?.context ?? "") + promptWithReply(promptWithDataContext(steerInput.text, dataContext), replyTo, userNameFor(threadId));steered = await (steerInput.images.length > 0@@ -7482,9 +7468,10 @@ async function acceptDirectSend(trigger,via,callId,- first: personsOwn,+ first: personsOwn || chose === "restart",});- if (personsOwn) personFirst.wait(threadId, {});+ if (personsOwn && !chose) personFirst.wait(threadId, {});+ if (chose === "restart") await restartForPerson(botId, threadId, trigger);return { ok: true as const, queued: true as const, queueId: queued.id, threadId };}return startOrQueueDirectMessage(botId, threadId, text, replyTo, sendId, sender, trigger, via, callId, dataContext, app);diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.tsindex 588b51ff3a..748527e64c 100644--- a/server/routes/bot-messages.ts+++ b/server/routes/bot-messages.ts@@ -6,7 +6,8 @@ import { approvalModeFor } from "../../shared/approval-mode.ts";import { isPersistentQuestionCard } from "../../shared/ask-question.ts";import { normalizeReaction, reactionAnswer } from "../../shared/reactions.ts";import type { WidgetAction } from "../../shared/widget.ts";-import type { ResolvedSender, SteerQueueReason } from "../../shared/wire.ts";+import { parseFollowUp } from "../../shared/follow-up.ts";+import type { ResolvedSender } from "../../shared/wire.ts";import { admit } from "../admission.ts";import { dismissQuestionCard } from "../card-dismissal.ts";import { AppMessageRate, appContextBlock, prepareAppMessage } from "../chat-apps.ts";@@ -25,6 +26,7 @@ import type { ReplyTarget } from "../replies.ts";import type { RequestAuth } from "../request-auth.ts";import type { RoutineManager } from "../routines.ts";import { acceptedSendMatch, parseSendId } from "../send-idempotency.ts";+import type { DirectSendInput, DirectSendReceipt } from "../direct-send.ts";import { cancelSteeredMessage, holdSteeredQueue, queuedSteeredMessage, restoreHeldSteeredQueue, settleHeldSteeredQueue } from "../steer-queue.ts";import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";import { extractSteerImages } from "../turn-images.ts";@@ -35,10 +37,6 @@ import { PASS, type RouteHandler } from "./table.ts";type RunningInstance = ReturnType<ProviderRegistry["get"]>;-type DirectSendReceipt =- | { ok: true; threadId: string; message: Message; steered?: true }- | { ok: true; queued: true; queueId: string; threadId: string; reason?: SteerQueueReason };-type SkillResolution =| { claimed: false }| { claimed: true; status: number; error: string }@@ -63,14 +61,7 @@ export interface BotMessageRouteDeps {desktopManaged: boolean;cloudHome: boolean;DirectSendRefused: abstract new (...args: never[]) => { readonly status: number; readonly body: Record<string, unknown> };- acceptDirectSend(- input: {- botId: string; threadId: string; text: string; sendId?: string; replyTo?: Message; sender?: ResolvedSender;- trigger: UsageTrigger; dataContext?: DataContext; personPresent: boolean;- app?: { context?: string; fromApp?: Message["fromApp"]; pointed?: Message["pointed"] };- },- guardedStart?: (currentAtStart: BotRecord) => Promise<DirectSendReceipt>,- ): Promise<DirectSendReceipt>;+ acceptDirectSend(input: DirectSendInput, guardedStart?: (currentAtStart: BotRecord) => Promise<DirectSendReceipt>): Promise<DirectSendReceipt>;directSendRefusal(botId: string, threadId: string): { status: number; body: Record<string, unknown> } | null;startTurn(botId: string, text: string, opts?: {threadId?: string; replyTo?: Message; sendId?: string; sender?: ResolvedSender; trigger?: UsageTrigger; relayed?: boolean;@@ -193,6 +184,9 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerif (pressed && fromAnApp) return json(res, 400, { error: "send widgetAction or appMessage, not both" });const pointing = body.pointed !== undefined && body.pointed !== null;if (pointing && (guarded || pressed || fromAnApp)) return json(res, 400, { error: "only a typed message can carry what the person pointed at" });+ const followUp = parseFollowUp(body.followUp);+ if (followUp === null) return json(res, 400, { error: "followUp must be steer, queue or restart" });+ if (followUp && (guarded || pressed || fromAnApp)) return json(res, 400, { error: "only a typed message can choose how it meets the running turn" });// A distinct route, so an older server answers 404 instead of ignoring the safety preconditions.const guardedBody = guarded ? guardedSendSchema.safeParse(body) : null;if (guardedBody && !guardedBody.success) {@@ -317,7 +311,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerbotId: bot.id, threadId, text, sendId, replyTo, sender, trigger, dataContext, ...(app ? { app } : {}),// The bot's own shell reaches this route on a headless server (loopback is the owner), so only a// paired session or the desktop capability proves a person and lifts the webhook block.- personPresent: auth.kind === "session" || DESKTOP_MANAGED,+ personPresent: auth.kind === "session" || DESKTOP_MANAGED, ...(followUp ? { followUp } : {}),}, guardedStart);press?.settle("queueId" in receipt ? receipt.queueId : undefined);appContext?.deliver();diff --git a/server/steer-e2e.test.ts b/server/steer-e2e.test.tsindex 50c05a92bd..a79340b3bf 100644--- a/server/steer-e2e.test.ts+++ b/server/steer-e2e.test.ts@@ -191,6 +191,82 @@ posixOnly("mid-turn steering e2e", () => {40_000,);+ it("a message sent with followUp: queue during a Claude turn waits for it instead of steering, then runs as its own turn", async () => {+ rmSync(steerFinishGate, { force: true });+ let queued: Awaited<ReturnType<typeof api>>;+ const created = (await api("POST", "/api/bots")).body.bot;+ try {+ await api("PATCH", `/api/bots/${created.id}`, { modelSelection: { instanceId: "claudeSteer", model: "claude-fake" } });+ expect((await api("POST", `/api/bots/${created.id}/messages`, { text: "first" })).status).toBe(202);+ await waitFor(async () => (await getBot(created.id)).messages.some((m: any) => m.kind === "activity"), "the tool chip");+ queued = await api("POST", `/api/bots/${created.id}/messages`, { text: "a new task for later", followUp: "queue" });+ expect((await getBot(created.id)).busy).toBe(true);+ } finally {+ writeFileSync(steerFinishGate, "finish");+ }+ expect(queued.status).toBe(202);+ expect(queued.body).toMatchObject({ ok: true, queued: true, queueId: expect.any(String) });+ expect(queued.body.steered).toBeUndefined();++ await waitFor(async () => {+ const bot = await getBot(created.id);+ return !bot.busy && bot.messages.some((m: any) => m.role === "bot" && m.kind === "text" && withoutTurnClock(m.text).startsWith("reply to: a new task for later"));+ }, "the queued message to run after the first turn");+ const bot = await getBot(created.id);+ expect(bot.messages.find((m: any) => m.role === "user" && m.text === "a new task for later").steered).toBeUndefined();+ expect(bot.messages.some((m: any) => m.role === "bot" && m.kind === "text" && m.text.includes("steered: a new task for later"))).toBe(false);+ expect(bot.messages.some((m: any) => m.role === "bot" && m.kind === "text" && withoutTurnClock(m.text).startsWith("reply to: first"))).toBe(true);+ expect(bot.messages.filter((m: any) => m.role === "user" && m.kind === "text").map((m: any) => m.text)).toEqual(["first", "a new task for later"]);+ }, 40_000);++ it("a message sent with followUp: restart during a Claude turn stops that turn and runs as the next one, never steered", async () => {+ rmSync(steerFinishGate, { force: true });+ const created = (await api("POST", "/api/bots")).body.bot;+ try {+ await api("PATCH", `/api/bots/${created.id}`, { modelSelection: { instanceId: "claudeSteer", model: "claude-fake" } });+ expect((await api("POST", `/api/bots/${created.id}/messages`, { text: "first" })).status).toBe(202);+ await waitFor(async () => (await getBot(created.id)).messages.some((m: any) => m.kind === "activity"), "the tool chip");+ const restarted = await api("POST", `/api/bots/${created.id}/messages`, { text: "start over with this", followUp: "restart" });+ expect(restarted.status).toBe(202);+ expect(restarted.body).toMatchObject({ ok: true, queued: true, queueId: expect.any(String) });+ await waitFor(async () => (await getBot(created.id)).messages.some((m: any) => m.role === "user" && m.text === "start over with this"),+ "the restarted turn to begin with the message");+ } finally {+ writeFileSync(steerFinishGate, "finish");+ }+ await waitFor(async () => (await getBot(created.id)).messages.some((m: any) => m.role === "bot" && m.kind === "text" && withoutTurnClock(m.text).startsWith("reply to: start over with this")),+ "the restarted turn's reply");+ await waitFor(async () => (await getBot(created.id)).busy === false, "the restarted turn to settle");+ const bot = await getBot(created.id);+ expect(bot.messages.find((m: any) => m.role === "user" && m.text === "start over with this").steered).toBeUndefined();+ expect(bot.messages.some((m: any) => m.role === "bot" && m.kind === "text" && withoutTurnClock(m.text).startsWith("reply to: first"))).toBe(false);+ expect(bot.messages.filter((m: any) => m.role === "user" && m.kind === "text").map((m: any) => m.text)).toEqual(["first", "start over with this"]);+ }, 40_000);++ it("a message sent with followUp: restart to an engine that cannot steer stops the turn and runs next", async () => {+ const created = (await api("POST", "/api/bots")).body.bot;+ await api("PATCH", `/api/bots/${created.id}`, { modelSelection: { instanceId: "acp", model: "fake-model" } });+ expect((await api("POST", `/api/bots/${created.id}/messages`, { text: "first" })).status).toBe(202);+ await waitFor(async () => (await getBot(created.id)).busy === true, "the hung turn to start");+ const restarted = await api("POST", `/api/bots/${created.id}/messages`, { text: "second", followUp: "restart" });+ expect(restarted.body).toMatchObject({ ok: true, queued: true });+ await waitFor(async () => (await getBot(created.id)).messages.some((m: any) => m.text === "second"), "the message to begin its own turn");+ await api("POST", `/api/bots/${created.id}/interrupt`);+ await waitFor(async () => (await getBot(created.id)).busy === false, "the restarted turn to settle");+ }, 30_000);++ it("refuses a followUp that is not steer, queue or restart, and one on a message that is not typed", async () => {+ const created = (await api("POST", "/api/bots")).body.bot;+ for (const followUp of ["later", true]) {+ const refused = await api("POST", `/api/bots/${created.id}/messages`, { text: "hi", followUp });+ expect(refused.status).toBe(400);+ expect(refused.body.error).toBe("followUp must be steer, queue or restart");+ }+ const pressed = await api("POST", `/api/bots/${created.id}/messages`, { text: "hi", followUp: "queue", widgetAction: { messageId: "m", action: "a" } });+ expect(pressed.status).toBe(400);+ expect(pressed.body.error).toBe("only a typed message can choose how it meets the running turn");+ });+it("a typed stop during a Claude turn ends it like Stop, and a longer message that starts with stop is still steered", async () => {rmSync(steerFinishGate, { force: true });try {diff --git a/shared/follow-up.test.ts b/shared/follow-up.test.tsnew file mode 100644index 0000000000..526984f651--- /dev/null+++ b/shared/follow-up.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from "vitest";++import { followUpChoices, parseFollowUp, resolveFollowUp } from "./follow-up.ts";++describe("a message sent while a bot works", () => {+ it("is an ordinary send when nothing runs, whatever key or setting", () => {+ for (const alternate of [false, true]) {+ for (const preferred of ["steer", "queue"] as const) {+ expect(resolveFollowUp({ running: false, alternate, preferred, canSteer: true })).toBeNull();+ expect(resolveFollowUp({ running: false, alternate, preferred, canSteer: false })).toBeNull();+ }+ }+ });++ it("does the setting on Enter and the other one with Ctrl/⌘, steering by default", () => {+ expect(resolveFollowUp({ running: true, alternate: false, canSteer: true })).toBe("steer");+ expect(resolveFollowUp({ running: true, alternate: true, canSteer: true })).toBe("queue");+ expect(resolveFollowUp({ running: true, alternate: false, preferred: "steer", canSteer: true })).toBe("steer");+ expect(resolveFollowUp({ running: true, alternate: true, preferred: "steer", canSteer: true })).toBe("queue");+ expect(resolveFollowUp({ running: true, alternate: false, preferred: "queue", canSteer: true })).toBe("queue");+ expect(resolveFollowUp({ running: true, alternate: true, preferred: "queue", canSteer: true })).toBe("steer");+ });++ it("always queues when the running turn cannot take steering", () => {+ for (const alternate of [false, true]) {+ for (const preferred of ["steer", "queue"] as const) {+ expect(resolveFollowUp({ running: true, alternate, preferred, canSteer: false })).toBe("queue");+ }+ }+ });++ it("offers what Enter does first, then the other one where steering works, then restart", () => {+ expect(followUpChoices("steer", true)).toEqual(["steer", "queue", "restart"]);+ expect(followUpChoices("queue", true)).toEqual(["queue", "steer", "restart"]);+ expect(followUpChoices("steer", false)).toEqual(["queue", "restart"]);+ expect(followUpChoices("queue", false)).toEqual(["queue", "restart"]);+ });++ it("reads the wire value: absent, one of the three, or refused", () => {+ expect(parseFollowUp(undefined)).toBeUndefined();+ expect(parseFollowUp(null)).toBeUndefined();+ for (const value of ["steer", "queue", "restart"]) expect(parseFollowUp(value)).toBe(value);+ for (const value of ["auto", "", true, 1, "Queue"]) expect(parseFollowUp(value)).toBeNull();+ });+});diff --git a/shared/follow-up.ts b/shared/follow-up.tsnew file mode 100644index 0000000000..7798b62ddd--- /dev/null+++ b/shared/follow-up.ts@@ -0,0 +1,37 @@+// A message a person sends while their bot works: steer it into the running turn, queue it for after that turn, or+// restart the turn with it. The composer resolves the choice; the server's direct-busy admission applies it.++export const FOLLOW_UPS = ["steer", "queue", "restart"] as const;+export type FollowUp = (typeof FOLLOW_UPS)[number];+/** What Enter does while a turn runs (the person's setting); Ctrl/⌘+Enter does the other one. */+export type FollowUpDefault = Exclude<FollowUp, "restart">;++export const DEFAULT_FOLLOW_UP: FollowUpDefault = "steer";++/** undefined when absent, null when present but not a follow-up. */+export function parseFollowUp(value: unknown): FollowUp | null | undefined {+ if (value === undefined || value === null) return undefined;+ return FOLLOW_UPS.find((followUp) => followUp === value) ?? null;+}++/** null: nothing is running, so it is an ordinary send. A turn that cannot take steering input always queues. */+export function resolveFollowUp(input: {+ running: boolean;+ /** Ctrl/⌘ held with the send key, or with the click. */+ alternate: boolean;+ preferred?: FollowUpDefault;+ canSteer: boolean;+}): FollowUp | null {+ if (!input.running) return null;+ if (!input.canSteer) return "queue";+ const preferred = input.preferred ?? DEFAULT_FOLLOW_UP;+ if (input.alternate) return preferred === "queue" ? "steer" : "queue";+ return preferred;+}++/** The send menu while a turn runs: what Enter does first, then the other one where the turn can be steered, then restart. */+export function followUpChoices(preferred: FollowUpDefault, canSteer: boolean): FollowUp[] {+ const first = resolveFollowUp({ running: true, alternate: false, preferred, canSteer })!;+ const other = resolveFollowUp({ running: true, alternate: true, preferred, canSteer })!;+ return [...new Set<FollowUp>([first, other, "restart"])];+}diff --git a/src/components/AppSettingsRows.tsx b/src/components/AppSettingsRows.tsxindex 18766e0910..55ea853b9c 100644--- a/src/components/AppSettingsRows.tsx+++ b/src/components/AppSettingsRows.tsx@@ -19,6 +19,7 @@ import { setAdvancedMode, useAdvancedMode } from "@/lib/interface-mode";import { setPinnedCircles, setUniversalPins, usePinnedCircles, useUniversalPins } from "@/lib/sidebar-preferences";import { setShowRunCard, useShowRunCard } from "@/lib/run-card-preferences";import { parseSendKey, SEND_KEYS, sendKeyLabel, setSendKey, useSendKey } from "@/lib/send-key";+import { alternateSendLabel, parseFollowUpDefault, setFollowUpDefault, useFollowUpDefault } from "@/lib/follow-up";import { effectiveLanguage, setLanguageChoice, useLanguageChoice } from "@/lib/language-preference";import { Select } from "./Select";@@ -220,6 +221,24 @@ export function SendKeyRow({ simple = false }: { simple?: boolean }) {);}+/** What Enter does with a message sent while a bot works. A setting, not a smart default: both are right, for different people. */+export function FollowUpRow({ simple = false }: { simple?: boolean }) {+ const followUp = useFollowUpDefault();+ const key = alternateSendLabel(useSendKey());+ return (+ <SettingRow title={t("settings.followUp.title")} subtitle={t(simple ? "settings.simple.followUp" : "settings.followUp.subtitle", { key })}>+ <Select size="sm" variant={simple ? "ghost" : "field"} className={simple ? undefined : "w-full max-w-[240px]"}+ value={followUp}+ aria-label={t("settings.followUp.title")}+ onChange={(event) => setFollowUpDefault(parseFollowUpDefault(event.target.value))}+ >+ <option value="steer">{t("settings.followUp.steer")}</option>+ <option value="queue">{t("settings.followUp.queue")}</option>+ </Select>+ </SettingRow>+ );+}+export function ColorUserBubblesRow({ simple = false }: { simple?: boolean }) {const enabled = useColorUserBubbles();return (diff --git a/src/components/Composer.tsx b/src/components/Composer.tsxindex 23b699dbcf..e5a2cb2051 100644--- a/src/components/Composer.tsx+++ b/src/components/Composer.tsx@@ -1,7 +1,7 @@import { directMessageSent, roomMessageSent } from "@/lib/product-events";import { useComposerDictation } from "@/lib/use-composer-dictation";import { useCallback, useEffect, useMemo, useRef, useState, type SetStateAction } from "react";-import { ArrowUp, Clock, Mic, Paperclip, Square, X } from "lucide-react";+import { Mic, Paperclip, Square, X } from "lucide-react";import { useStore, visibleMessages, currentTaskBot, type Bot, type Group, type InstanceInfo, type Message } from "@/state/store";import { cn } from "@/lib/cn";import { PHONE_LAYOUT, useMediaQuery } from "@/lib/use-media-query";@@ -10,6 +10,7 @@ import { ELEVATED_CARD, ELEVATED_FLOAT } from "./elevated";import { activeLocale, t } from "@/lib/i18n";import { useAdvancedMode } from "@/lib/interface-mode";import { imeComposing, sendKeyLabel, sendsMessage, useSendKey } from "@/lib/send-key";+import { alternateSend, alternateSendLabel, useFollowUpDefault } from "@/lib/follow-up"; import { followUpChoices, resolveFollowUp, type FollowUp } from "../../shared/follow-up";import {draftRevision,appendDraftAttachments,@@ -64,7 +65,7 @@ import {type PasteAttachment,} from "@/lib/composer-attachments";import { goalCoordinatorForComposer, jevRoomRoutingOn, openTaskWorking, roomRespondersForComposer } from "@/lib/group-routing";-import { composerPlaceholder, sendLabels, SIMPLE_COMPOSER, SIMPLE_CONTROL, slotColors } from "./composer-simple";+import { composerPlaceholder, sendLabels, SIMPLE_COMPOSER, SIMPLE_CONTROL, slotColors } from "./composer-simple"; import { ComposerSendButton } from "./ComposerSendButton";import { PendingApprovalActions, PendingApprovalPanel, pendingApprovals } from "./PendingApproval";import { CallButton } from "./CallView";import { GroupCallButton } from "./GroupCallView";@@ -133,7 +134,7 @@ export function Composer({const singleRow = useMediaQuery(PHONE_LAYOUT);// Simple mode on a wider screen: one pill holding a round +, the field, the mic and one round button in the bot's colour.const simpleDock = !advanced && !singleRow;- const sendKey = useSendKey();+ const sendKey = useSendKey(); const followUpDefault = useFollowUpDefault();const sendLabel = sendKeyLabel(sendKey);const remoteClient = window.ogb?.remoteClient?.active === true;const threadId = group?.threadId ?? bot?.threadId ?? "";@@ -531,7 +532,10 @@ export function Composer({const stopInSlot = simpleDock && stoppable && !locked && !hasContent && !calling;const callShown = !simpleDock || (!hasContent && !stopInSlot);const slot = slotColors(bot?.color, Boolean(group));- const sendNames = sendLabels({ simple: !advanced, busy, canSteer, name: busyName, sendLabel });+ // A one-to-one bot at work: Enter does the chosen follow-up and Ctrl/⌘ with it the other one. Rooms keep their own queue.+ const followUpFor = (alternate: boolean) => resolveFollowUp({ running: busy && !group && Boolean(bot), alternate, preferred: followUpDefault, canSteer }) ?? undefined;+ const steersNow = group ? canSteer : followUpFor(false) === "steer";+ const sendNames = sendLabels({ simple: !advanced, busy, canSteer: steersNow, name: busyName, sendLabel });const retryFailedSend = (failed: FailedComposerSend) => {const failedMode = failed.channelMode ?? "chat";if (failed.requestText.includes("<attached-image ") && !imageTargetsSupport(failed.requestText, failedMode)) {@@ -561,7 +565,7 @@ export function Composer({dispatch({ type: "send", botId: bot.id, mode: failedMode, ...retry });}};- const send = () => {+ const send = (followUp: FollowUp | undefined = followUpFor(false)) => {if (locked || attachmentPending) return;if (attachments.some((attachment) => attachment.kind === "image") &&@@ -603,10 +607,10 @@ export function Composer({const points = effectiveChannelMode === "goal" ? null : takePointedChips(threadId);dispatch({type: "send", botId: bot.id, text: body, sendId: sentDraft.sendId, replyToId: replyTo?.id, threadId, dataContext, mode: effectiveChannelMode,- ...(points ? { pointed: points.pointed } : {}),+ ...(points ? { pointed: points.pointed } : {}), ...(followUp ? { followUp } : {}),onError: () => { points?.restore(); restoreDraft(sentDraft); },});- directMessageSent(state.instances, bot.modelSelection?.instanceId, busy && !canSteer);+ directMessageSent(state.instances, bot.modelSelection?.instanceId, busy && followUp !== "steer");}setText("");setAttachments([]);@@ -918,7 +922,7 @@ export function Composer({steerQueued();return;}- send();+ send(followUpFor(alternateSend(e.nativeEvent, sendKey)));}if (e.key === "Escape" && recording) stopDictation();}}@@ -928,7 +932,7 @@ export function Composer({aria-busy={bot?.awaitingThreadSnapshot || undefined}placeholder={composerPlaceholder({simple: !advanced, locked: setupLocked, approval: blocking, attaching: attachmentPending, listening: recording,- replying: Boolean(replyTo), busy, canSteer, queued: pendingCount > 0, busyName, sendLabel, group, members: members ?? [],+ replying: Boolean(replyTo), busy, canSteer: steersNow, queued: pendingCount > 0, busyName, sendLabel, group, members: members ?? [],jevOn: jevRoomRoutingOn(state.config), goal: channelMode === "goal", botName: bot?.name ?? "",setupHint: group ? null : setupRequestPlaceholder(bot, threadId),})}@@ -976,20 +980,9 @@ export function Composer({{callShown && bot && !group && <CallButton bot={bot} placement="composer" fill={advanced || singleRow ? undefined : slot.fill} ink={slot.ink} inverse={singleRow} />}{callShown && group && !advanced && <GroupCallButton group={group} members={members ?? []} placement="composer" fill={slot.fill} ink={slot.ink} />}{hasContent && !locked && (- <button- onClick={send}- disabled={attachmentPending}- aria-label={sendNames.label}- title={sendNames.title}- style={busy && !canSteer ? undefined : slot.button.style}- className={cn(- "flex shrink-0 items-center justify-center rounded-full disabled:cursor-default",- simpleDock ? "size-7 animate-[slot-fade-in_120ms_ease-out]" : "size-8",- busy && !canSteer ? "bg-raised text-ink-secondary hover:bg-raised-hover" : slot.button.className,- )}- >- {busy && !canSteer ? <Clock size={simpleDock ? 14 : 15} /> : <ArrowUp size={16} strokeWidth={1.75} absoluteStrokeWidth />}- </button>+ <ComposerSendButton compact={simpleDock} waits={busy && !steersNow} label={sendNames.label} title={sendNames.title} look={slot.button}+ disabled={attachmentPending} onSend={(alternate) => send(followUpFor(alternate))} onChoose={send}+ menu={followUpFor(false) && { choices: followUpChoices(followUpDefault, canSteer), name: busyName, sendKey: sendLabel, alternateKey: alternateSendLabel(sendKey) }} />)}</div></div>diff --git a/src/components/ComposerSendButton.tsx b/src/components/ComposerSendButton.tsxnew file mode 100644index 0000000000..d5f159a1ee--- /dev/null+++ b/src/components/ComposerSendButton.tsx@@ -0,0 +1,79 @@+import type { CSSProperties } from "react";+import { ArrowUp, ChevronUp, Clock, CornerDownRight, RotateCcw } from "lucide-react";++import type { FollowUp } from "../../shared/follow-up";+import { cn } from "@/lib/cn";+import { t } from "@/lib/i18n";+import { SidebarPopoverMenu, type SidebarMenuItem } from "./SidebarPopoverMenu";++const FOLLOW_UP_ICON = { steer: CornerDownRight, queue: Clock, restart: RotateCcw } as const;++export interface FollowUpMenu {+ /** What Enter does first, then the other one where the turn can be steered, then restart. */+ choices: FollowUp[];+ name: string;+ sendKey: string;+ alternateKey: string;+}++/** The composer's round Send button. While a one-to-one bot works, a click does what Enter does and a Ctrl/⌘-click the+ * other one; the chevron beside it lists every way this message can meet the running turn. */+export function ComposerSendButton({ compact, waits, label, title, look, disabled, onSend, menu, onChoose }: {+ compact: boolean;+ /** The message will wait for the running turn: a clock on a quiet button instead of the bot's colour. */+ waits: boolean;+ label: string;+ title: string;+ look: { className: string; style?: CSSProperties };+ disabled: boolean;+ onSend: (alternate: boolean) => void;+ menu?: FollowUpMenu;+ onChoose: (followUp: FollowUp) => void;+}) {+ const alternate = menu?.choices[1] !== "restart" ? menu?.choices[1] : undefined;+ const button = (+ <button+ onClick={(event) => onSend(event.metaKey || event.ctrlKey)}+ disabled={disabled}+ aria-label={label}+ title={menu && alternate ? t("composer.followUp.buttonTitle", { title, key: menu.alternateKey, alternate: t(`composer.followUp.${alternate}`) }) : title}+ style={waits ? undefined : look.style}+ className={cn(+ "flex shrink-0 items-center justify-center rounded-full disabled:cursor-default",+ compact ? "size-7 animate-[slot-fade-in_120ms_ease-out]" : "size-8",+ waits ? "bg-raised text-ink-secondary hover:bg-raised-hover" : look.className,+ )}+ >+ {waits ? <Clock size={compact ? 14 : 15} /> : <ArrowUp size={16} strokeWidth={1.75} absoluteStrokeWidth />}+ </button>+ );+ if (!menu) return button;+ const items = menu.choices.map((choice, index): SidebarMenuItem => {+ const Icon = FOLLOW_UP_ICON[choice];+ return {+ key: choice,+ label: t(`composer.followUp.${choice}`),+ subtitle: t(`composer.followUp.${choice}Hint`, { name: menu.name }),+ icon: <Icon size={16} aria-hidden="true" />,+ active: index === 0,+ value: index === 0 ? menu.sendKey : choice === alternate ? menu.alternateKey : undefined,+ disabled,+ onSelect: () => onChoose(choice),+ };+ });+ return (+ <div data-composer-follow-up className="flex shrink-0 items-center">+ <SidebarPopoverMenu+ items={items}+ ariaLabel={t("composer.followUp.menu")}+ triggerTitle={t("composer.followUp.menu")}+ triggerClassName={cn(+ "flex shrink-0 items-center justify-center rounded-full text-ink-secondary hover:bg-raised hover:text-ink",+ compact ? "h-7 w-5" : "h-8 w-6",+ )}+ renderTrigger={() => <ChevronUp size={14} aria-hidden="true" />}+ />+ {button}+ </div>+ );+}diff --git a/src/components/SettingsModal.tsx b/src/components/SettingsModal.tsxindex daa3caf855..907ea8ea38 100644--- a/src/components/SettingsModal.tsx+++ b/src/components/SettingsModal.tsx@@ -63,7 +63,7 @@ import { NotificationRows } from "./NotificationSettingsRows";import { useAdvancedMode } from "@/lib/interface-mode";import { Select } from "./Select";import { SavedStepsRow } from "./SavedStepsRow";-import { BrowserProfilesRow, ColorUserBubblesRow, AdvancedModeRow, ExperimentalFeaturesRow, LanguageRow, NewBotEffortRow, PinnedCirclesRow, ReplayTourRow, RunCardRow, SendKeyRow, ShowThreadsRow, ToolCallsRow, UniversalPinsRow, UpdatesRow } from "./AppSettingsRows";+import { BrowserProfilesRow, ColorUserBubblesRow, AdvancedModeRow, ExperimentalFeaturesRow, LanguageRow, NewBotEffortRow, PinnedCirclesRow, ReplayTourRow, RunCardRow, FollowUpRow, SendKeyRow, ShowThreadsRow, ToolCallsRow, UniversalPinsRow, UpdatesRow } from "./AppSettingsRows";import { SIMPLE_ADVANCED_ONLY, SimpleAiPage, SimpleBillingPage, SimpleComputerPage, SimpleGeneralPage, SimpleLooksPage, SimpleUpdatesPage, type Disclose, type SimpleDisclosureId } from "./SettingsSimplePages";// labelKey, not a label: t() reads the active pack when called, so a label resolved at module scope would freeze the@@ -382,6 +382,7 @@ export function SettingsModal() {<ChatWidthRow /><ColorUserBubblesRow /><SendKeyRow />+ <FollowUpRow /><SidebarToolsLayoutRow /><ChromeRailRow /><WindowFrameRow />diff --git a/src/components/SettingsSimplePages.tsx b/src/components/SettingsSimplePages.tsxindex 121e6b61ae..78000e2c51 100644--- a/src/components/SettingsSimplePages.tsx+++ b/src/components/SettingsSimplePages.tsx@@ -31,7 +31,7 @@ import { ProfileSummaryRow } from "./ProfileSettings";import { ImportSettings } from "./ImportSettings";import { NotificationRows } from "./NotificationSettingsRows";import { useServerUpdateItem } from "./SidebarProfileMenu";-import { AdvancedModeRow, BrowserProfilesRow, ColorUserBubblesRow, LanguageRow, ReplayTourRow, SendKeyRow, UpdatesRow } from "./AppSettingsRows";+import { AdvancedModeRow, BrowserProfilesRow, ColorUserBubblesRow, FollowUpRow, LanguageRow, ReplayTourRow, SendKeyRow, UpdatesRow } from "./AppSettingsRows";import { ThemeRow } from "./ThemeRow";import { AdminOnly } from "./AdminOnly";@@ -69,6 +69,7 @@ export function SimpleGeneralPage({ has, peopleOpen, onLooks }: { has: Has; peop<ColorUserBubblesRow simple /><LanguageRow simple /><SendKeyRow simple />+ <FollowUpRow simple /><SettingRow title={t("settings.simple.looks.title")}><button type="button" className="ui-button" onClick={onLooks}>{t("settings.simple.looks.change")}</button></SettingRow>diff --git a/src/components/send-key.test.ts b/src/components/send-key.test.tsindex 0d626f9a14..0780861881 100644--- a/src/components/send-key.test.ts+++ b/src/components/send-key.test.ts@@ -43,6 +43,7 @@ const { CitationBadge } = await import("./CitationUI");const { CloudIntent } = await import("./CloudIntent");const { GuidedTour } = await import("./onboarding/GuidedTour");const { setSendKey } = await import("@/lib/send-key");+const { setFollowUpDefault } = await import("@/lib/follow-up");const { setPendingIntent } = await import("@/lib/cloud-intent");const { setLocale } = await import("@/lib/i18n");const { api } = await import("@/state/store");@@ -105,6 +106,7 @@ beforeEach(() => {fixture.config = undefined;fixture.tourOpen = false;setSendKey("enter");+ setFollowUpDefault("steer");vi.stubGlobal("fetch", vi.fn(async () => new Response("{}", { status: 200, headers: { "content-type": "application/json" } })));host = document.createElement("div");document.body.append(host);@@ -253,3 +255,99 @@ describe("the send key in hints", () => {expect(host.querySelector('button[aria-label="Start setting it up"]')?.getAttribute("title")).toBe("Start setting it up (Ctrl+Enter)");});});++describe("a message sent while a one-to-one bot works", () => {+ const steers = { instanceId: "test", driverKind: "codex", displayName: "Test", capabilities: { queueing: true } } as unknown as InstanceInfo;+ const cannotSteer = { ...steers, capabilities: { queueing: false } } as unknown as InstanceInfo;+ const working = { ...bot, busy: true, tasks: [{ ...bot.tasks![0]!, busy: true }] };+ const followUps = () => sends().map((action) => action.followUp);+ const sendButton = () => host.querySelector<HTMLButtonElement>("[data-composer-follow-up] > button")!;+ const chooser = () => host.querySelector<HTMLButtonElement>('button[aria-label="Choose how to send this message"]');+ const openChoices = () => {+ flushSync(() => chooser()!.click());+ return [...document.querySelectorAll<HTMLButtonElement>('[role="menu"] [role="menuitem"]')];+ };++ it("steers on Enter and queues with Ctrl/⌘, by key or by click", () => {+ fixture.instances = [steers];+ render(createElement(Composer, { bot: working }));+ for (const [init, followUp] of [[{}, "steer"], [{ ctrlKey: true }, "queue"], [{ metaKey: true }, "queue"]] as const) {+ type(textarea(), "words");+ expect(press(textarea(), init).defaultPrevented).toBe(true);+ expect(sends().at(-1), JSON.stringify(init)).toMatchObject({ type: "send", text: "words", followUp });+ }+ type(textarea(), "clicked");+ expect(sendButton().getAttribute("title")).toBe("Send into the running turn · Ctrl+Enter: Queue");+ flushSync(() => sendButton().click());+ type(textarea(), "ctrl-clicked");+ flushSync(() => sendButton().dispatchEvent(new MouseEvent("click", { bubbles: true, ctrlKey: true })));+ expect(sends().slice(-2).map((action) => [action.text, action.followUp])).toEqual([["clicked", "steer"], ["ctrl-clicked", "queue"]]);+ });++ it("follows the setting: Enter queues and Ctrl/⌘ steers once the person picks queue", () => {+ fixture.instances = [steers];+ setFollowUpDefault("queue");+ render(createElement(Composer, { bot: working }));+ expect(textarea().placeholder).toBe("Pepper is working. Sends when this turn finishes");+ type(textarea(), "later");+ press(textarea());+ type(textarea(), "now");+ press(textarea(), { ctrlKey: true });+ expect(followUps()).toEqual(["queue", "steer"]);+ });++ it("needs Shift too when Ctrl/⌘+Enter is the send key", () => {+ fixture.instances = [steers];+ setSendKey("mod-enter");+ render(createElement(Composer, { bot: working }));+ type(textarea(), "one");+ expect(press(textarea()).defaultPrevented).toBe(false);+ press(textarea(), { ctrlKey: true });+ type(textarea(), "two");+ press(textarea(), { ctrlKey: true, shiftKey: true });+ expect(followUps()).toEqual(["steer", "queue"]);+ });++ it("offers steer, queue and restart beside Send, each saying what it does", () => {+ fixture.instances = [steers];+ render(createElement(Composer, { bot: working }));+ expect(chooser()).toBeNull();+ type(textarea(), "start again with this");+ const choices = openChoices();+ expect(choices.map((choice) => choice.textContent)).toEqual([+ "Steer nowInterrupt what Pepper is doingEnter",+ "QueueRun after the current turnCtrl+Enter",+ "Restart turnStart the turn over with this message",+ ]);+ flushSync(() => choices[2]!.click());+ expect(sends().at(-1)).toMatchObject({ type: "send", text: "start again with this", followUp: "restart" });+ });++ it("always queues for a bot whose turn cannot be steered, and still offers restart", () => {+ fixture.instances = [cannotSteer];+ render(createElement(Composer, { bot: working }));+ type(textarea(), "a");+ press(textarea());+ type(textarea(), "b");+ press(textarea(), { ctrlKey: true });+ expect(followUps()).toEqual(["queue", "queue"]);+ type(textarea(), "c");+ expect(openChoices().map((choice) => choice.textContent)).toEqual([+ "QueueRun after the current turnEnter",+ "Restart turnStart the turn over with this message",+ ]);+ });++ it("leaves an idle bot and a room's queue as they were", () => {+ fixture.instances = [steers];+ render(createElement(Composer, { bot }));+ type(textarea(), "idle");+ press(textarea(), { ctrlKey: true });+ expect(chooser()).toBeNull();+ render(createElement(Composer, { group: { ...room, busyBotId: "bot" }, members: [bot] }));+ type(textarea(), "room");+ press(textarea(), { ctrlKey: true });+ expect(chooser()).toBeNull();+ expect(sends().map((action) => [action.type, "followUp" in action])).toEqual([["send", false], ["sendGroup", false]]);+ });+});diff --git a/src/lib/follow-up.test.ts b/src/lib/follow-up.test.tsnew file mode 100644index 0000000000..ec53714261--- /dev/null+++ b/src/lib/follow-up.test.ts@@ -0,0 +1,80 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { SEND_KEYS } from "./send-key";++vi.mock("react", () => ({+ useSyncExternalStore: (_subscribe: unknown, snapshot: () => unknown) => snapshot(),+}));++function memoryStorage() {+ const values = new Map<string, string>();+ return {+ getItem: (key: string) => values.get(key) ?? null,+ setItem: (key: string, value: string) => values.set(key, value),+ };+}++let local: ReturnType<typeof memoryStorage>;++beforeEach(() => {+ vi.resetModules();+ local = memoryStorage();+ vi.stubGlobal("localStorage", local);+ vi.stubGlobal("window", new EventTarget());+});++afterEach(() => {+ vi.unstubAllGlobals();+});++const keys = (init: Partial<Record<"ctrlKey" | "metaKey" | "shiftKey", boolean>> = {}) => ({ ctrlKey: false, metaKey: false, shiftKey: false, ...init });++describe("the other follow-up's key", () => {+ it("is Ctrl/⌘ with the send key, and Shift too when Ctrl/⌘+Enter already sends", async () => {+ const { alternateSend } = await import("./follow-up");+ for (const mode of SEND_KEYS) {+ expect(alternateSend(keys(), mode), mode).toBe(false);+ expect(alternateSend(keys({ shiftKey: true }), mode), mode).toBe(false);+ }+ for (const mode of ["enter", "shift-enter"] as const) {+ expect(alternateSend(keys({ ctrlKey: true }), mode)).toBe(true);+ expect(alternateSend(keys({ metaKey: true }), mode)).toBe(true);+ }+ expect(alternateSend(keys({ ctrlKey: true }), "mod-enter")).toBe(false);+ expect(alternateSend(keys({ metaKey: true }), "mod-enter")).toBe(false);+ expect(alternateSend(keys({ ctrlKey: true, shiftKey: true }), "mod-enter")).toBe(true);+ expect(alternateSend(keys({ metaKey: true, shiftKey: true }), "mod-enter")).toBe(true);+ });++ it("is named for the platform", async () => {+ const { alternateSendLabel } = await import("./follow-up");+ expect(alternateSendLabel("enter", true)).toBe("⌘+Enter");+ expect(alternateSendLabel("shift-enter", false)).toBe("Ctrl+Enter");+ expect(alternateSendLabel("mod-enter", true)).toBe("⌘+Shift+Enter");+ expect(alternateSendLabel("mod-enter", false)).toBe("Ctrl+Shift+Enter");+ });+});++describe("the follow-up setting", () => {+ it("steers until the person picks queue, and remembers the pick on this device", async () => {+ let setting = await import("./follow-up");+ expect(setting.useFollowUpDefault()).toBe("steer");+ setting.setFollowUpDefault("queue");+ expect(local.getItem(setting.FOLLOW_UP_KEY)).toBe("queue");+ expect(setting.useFollowUpDefault()).toBe("queue");+ vi.resetModules();+ setting = await import("./follow-up");+ expect(setting.readFollowUpDefault()).toBe("queue");+ setting.setFollowUpDefault("steer");+ expect(setting.readFollowUpDefault()).toBe("steer");+ });++ it("falls back to steering on a stored value it does not know, or storage it cannot read", async () => {+ local.setItem("omb-follow-up", "restart");+ const setting = await import("./follow-up");+ expect(setting.readFollowUpDefault()).toBe("steer");+ vi.resetModules();+ vi.stubGlobal("localStorage", { getItem: () => { throw new Error("blocked"); }, setItem: () => {} });+ expect((await import("./follow-up")).readFollowUpDefault()).toBe("steer");+ });+});diff --git a/src/lib/follow-up.ts b/src/lib/follow-up.tsnew file mode 100644index 0000000000..3ea6251241--- /dev/null+++ b/src/lib/follow-up.ts@@ -0,0 +1,72 @@+import { useSyncExternalStore } from "react";++import { DEFAULT_FOLLOW_UP, type FollowUpDefault } from "../../shared/follow-up";+import { isMacPlatform } from "./keyboard-shortcuts";+import type { SendKey } from "./send-key";++/** What Enter does while a bot works: steer the message into the running turn, or queue it. On this device only. */+export const FOLLOW_UP_KEY = "omb-follow-up";++export function parseFollowUpDefault(value: string | null | undefined): FollowUpDefault {+ return value === "queue" || value === "steer" ? value : DEFAULT_FOLLOW_UP;+}++/** Ctrl/⌘ with the send key does the other one; when Ctrl/⌘+Enter is the send key, Shift joins it. */+export function alternateSend(event: Pick<KeyboardEvent, "ctrlKey" | "metaKey" | "shiftKey">, mode: SendKey): boolean {+ const mod = event.ctrlKey || event.metaKey;+ return mode === "mod-enter" ? mod && event.shiftKey : mod;+}++export function alternateSendLabel(mode: SendKey, mac: boolean = isMacPlatform()): string {+ const mod = mac ? "⌘" : "Ctrl";+ return mode === "mod-enter" ? `${mod}+Shift+Enter` : `${mod}+Enter`;+}++let sessionChoice: FollowUpDefault | undefined;+const listeners = new Set<() => void>();++function storage(): Storage | undefined {+ try {+ return globalThis.localStorage;+ } catch {+ return undefined;+ }+}++export function readFollowUpDefault(): FollowUpDefault {+ if (sessionChoice !== undefined) return sessionChoice;+ try {+ return parseFollowUpDefault(storage()?.getItem(FOLLOW_UP_KEY));+ } catch {+ return DEFAULT_FOLLOW_UP;+ }+}++function onStorage(event: StorageEvent) {+ if (event.key !== FOLLOW_UP_KEY && event.key !== null) return;+ if (event.storageArea && event.storageArea !== storage()) return;+ sessionChoice = undefined;+ for (const listener of listeners) listener();+}++function subscribe(listener: () => void): () => void {+ listeners.add(listener);+ if (listeners.size === 1 && typeof window !== "undefined") window.addEventListener("storage", onStorage);+ return () => {+ listeners.delete(listener);+ if (listeners.size === 0 && typeof window !== "undefined") window.removeEventListener("storage", onStorage);+ };+}++export function setFollowUpDefault(choice: FollowUpDefault): void {+ sessionChoice = choice;+ try {+ storage()?.setItem(FOLLOW_UP_KEY, choice);+ } catch {+ }+ for (const listener of listeners) listener();+}++export function useFollowUpDefault(): FollowUpDefault {+ return useSyncExternalStore(subscribe, readFollowUpDefault, () => DEFAULT_FOLLOW_UP);+}diff --git a/src/lib/keyboard-shortcuts.test.ts b/src/lib/keyboard-shortcuts.test.tsindex 53f3abede5..d858abec90 100644--- a/src/lib/keyboard-shortcuts.test.ts+++ b/src/lib/keyboard-shortcuts.test.ts@@ -83,6 +83,10 @@ describe("keyboard-shortcuts", () => {const mod = shortcutGroupsFor("mod-enter");expect(row(mod, "send-message")).toMatchObject({ macKeys: ["⌘", "Return"], winKeys: ["Ctrl", "Enter"] });expect(row(mod, "new-line")).toMatchObject({ macKeys: ["Return"], winKeys: ["Enter"] });+ // The other of steer and queue: Ctrl/⌘ with the send key, so Shift joins it when Ctrl/⌘+Enter already sends.+ expect(row(SHORTCUT_GROUPS, "send-follow-up")).toMatchObject({ macKeys: ["⌘", "Return"], winKeys: ["Ctrl", "Enter"] });+ expect(row(shift, "send-follow-up")).toMatchObject({ macKeys: ["⌘", "Return"], winKeys: ["Ctrl", "Enter"] });+ expect(row(mod, "send-follow-up")).toMatchObject({ macKeys: ["⌘", "⇧", "Return"], winKeys: ["Ctrl", "Shift", "Enter"] });for (const groups of [shift, mod]) {expect(row(groups, "save-bulletin")).toBe(row(SHORTCUT_GROUPS, "save-bulletin"));expect(row(groups, "send-message").description).toBe("Send message");diff --git a/src/lib/keyboard-shortcuts.ts b/src/lib/keyboard-shortcuts.tsindex 955717cb40..96a0d19d05 100644--- a/src/lib/keyboard-shortcuts.ts+++ b/src/lib/keyboard-shortcuts.ts@@ -69,6 +69,12 @@ export const SHORTCUT_GROUPS: readonly ShortcutGroup[] = [macKeys: ["⇧", "Return"],winKeys: ["Shift", "Enter"],},+ {+ id: "send-follow-up",+ description: "While a bot works: queue instead of steering, or the other way round",+ macKeys: ["⌘", "Return"],+ winKeys: ["Ctrl", "Enter"],+ },{id: "edit-last-message",description: "Edit last message (when composer is empty)",@@ -128,20 +134,22 @@ export const SHORTCUT_GROUPS: readonly ShortcutGroup[] = [type Keys = Pick<ShortcutItem, "macKeys" | "winKeys">;const ENTER: Keys = { macKeys: ["Return"], winKeys: ["Enter"] };const SHIFT_ENTER: Keys = { macKeys: ["⇧", "Return"], winKeys: ["Shift", "Enter"] };-const SEND_ROWS: Record<Exclude<SendKey, "enter">, [Keys, Keys]> = {- "shift-enter": [SHIFT_ENTER, ENTER],- "mod-enter": [{ macKeys: ["⌘", "Return"], winKeys: ["Ctrl", "Enter"] }, ENTER],+const MOD_ENTER: Keys = { macKeys: ["⌘", "Return"], winKeys: ["Ctrl", "Enter"] };+const SEND_ROWS: Record<Exclude<SendKey, "enter">, [Keys, Keys, Keys]> = {+ "shift-enter": [SHIFT_ENTER, ENTER, MOD_ENTER],+ "mod-enter": [MOD_ENTER, ENTER, { macKeys: ["⌘", "⇧", "Return"], winKeys: ["Ctrl", "Shift", "Enter"] }],};export function shortcutGroupsFor(sendKey: SendKey): readonly ShortcutGroup[] {if (sendKey === "enter") return SHORTCUT_GROUPS;- const [send, newLine] = SEND_ROWS[sendKey];+ const [send, newLine, followUp] = SEND_ROWS[sendKey];return SHORTCUT_GROUPS.map((group) => ({...group,items: group.items.map((item) =>item.id === "send-message" ? { ...item, ...send }: item.id === "new-line" ? { ...item, ...newLine }- : item),+ : item.id === "send-follow-up" ? { ...item, ...followUp }+ : item),}));}diff --git a/src/locales/en.json b/src/locales/en.jsonindex d48f2b8b31..d7cdcc2a3c 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -1509,6 +1509,10 @@"settings.font.serif": "Serif","settings.sendKey.title": "Send messages with","settings.sendKey.subtitle": "Choose Shift+Enter or {key} so Enter starts a new line instead, handy when your input method confirms text with Enter, as Japanese input does. {key} sends whichever you choose. On this device only.",+ "settings.followUp.title": "Sending while a bot works",+ "settings.followUp.steer": "Steer it into the running turn",+ "settings.followUp.queue": "Queue it for after the turn",+ "settings.followUp.subtitle": "Steering adds your message to what the bot is doing now; queueing runs it once the turn ends. {key} does the other one for a single message, and the arrow beside Send can also restart the turn. On this device only.","settings.userBubbles.title": "Color my messages","settings.userBubbles.subtitle": "In a one-to-one chat, your messages are filled with a gradient of that bot's color. Rooms keep the neutral bubble.","settings.userBubbles.aria": "Color my messages with the bot's color",@@ -2656,6 +2660,14 @@"composer.send.queueHint": "Sends when the current turn finishes","composer.send.steerSimple": "Add this to what {name} is doing","composer.send.queueSimple": "Sends when {name} is done",+ "composer.followUp.menu": "Choose how to send this message",+ "composer.followUp.steer": "Steer now",+ "composer.followUp.queue": "Queue",+ "composer.followUp.restart": "Restart turn",+ "composer.followUp.steerHint": "Interrupt what {name} is doing",+ "composer.followUp.queueHint": "Run after the current turn",+ "composer.followUp.restartHint": "Start the turn over with this message",+ "composer.followUp.buttonTitle": "{title} · {key}: {alternate}","attach.unavailableOld": "This older file reference is no longer available to download","attach.downloadFailed": "Couldn't download that file. Try again.","attach.saveFailed": "That file could not be saved",@@ -6162,6 +6174,7 @@"settings.simple.language.system": "Follow system","settings.simple.language.partial": "Only part of the app is translated so far.","settings.simple.sendKey": "Pick Shift+Enter or {key} if Enter confirms typed text, as in Japanese input.",+ "settings.simple.followUp": "{key} does the other one for a single message.","settings.simple.deviceNotifications": "Only while the app is open. Questions, approvals and warnings always show.","settings.simple.notificationSounds": "Plays a sound when a bot finishes or needs you.","settings.simple.notificationFeed": "A bell on the right that keeps your last 500 notifications.",diff --git a/src/state/store.tsx b/src/state/store.tsxindex cf2b0f3cf3..f253b8c82a 100644--- a/src/state/store.tsx+++ b/src/state/store.tsx@@ -725,7 +725,7 @@ export type Action =replyToId?: string;threadId?: string;dataContext?: import("../../shared/data-context").DataContext; pointed?: import("../../shared/app-frame/point").PointedElement[]; mode?: "chat" | "goal";- onError?: () => void;+ followUp?: import("../../shared/follow-up").FollowUp; onError?: () => void;}| { type: "pendingQueued"; threadId: string; queueId: string; text: string; reason?: SteerQueueReason }| { type: "consumePendingQueued"; threadId: string; queueId: string }@@ -2461,7 +2461,7 @@ export function StoreProvider({ children }: { children: ReactNode }) {void waitForExecutionSettings(botBeforeSend ? [botBeforeSend] : [], threadId).then(() => sendReconciled(() => api(`/api/bots/${action.botId}/messages`, {method: "POST",- body: JSON.stringify({ text: action.text, replyToId: action.replyToId, threadId, sendId, ...(action.dataContext ? { dataContext: action.dataContext } : {}), ...(action.pointed?.length ? { pointed: action.pointed } : {}), ...(action.mode === "goal" ? { mode: "goal" } : {}) }),+ body: JSON.stringify({ text: action.text, replyToId: action.replyToId, threadId, sendId, ...(action.dataContext ? { dataContext: action.dataContext } : {}), ...(action.pointed?.length ? { pointed: action.pointed } : {}), ...(action.mode === "goal" ? { mode: "goal" } : {}), ...(action.followUp ? { followUp: action.followUp } : {}) }),}), arrived)).then((sent) => {if (!("body" in sent)) return;