TypeScript
fix(orchestration): queue follow-ups sent while a thread compacts (#20184)
mariaa54a44c66934
diff --git a/apps/mobile/src/state/use-thread-composer-state.ts b/apps/mobile/src/state/use-thread-composer-state.tsindex 438b419672b..d0866906f43 100644--- a/apps/mobile/src/state/use-thread-composer-state.ts+++ b/apps/mobile/src/state/use-thread-composer-state.ts@@ -307,7 +307,6 @@ export function useThreadComposerState() {? EMPTY_QUEUE_WORKFLOW_ATOM: environmentThreadDetails.queueWorkflowAtom(selectedThreadDetailRef),);- const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true;const queuedRunEdit = useQueuedRunEdit(selectedThreadKey);const composerDraftKey =selectedThreadKey === null@@ -394,6 +393,8 @@ export function useThreadComposerState() {selectedThreadRuntime,selectedThreadVisibleTurnItems,]);+ // A compacting turn cannot take steering input, so follow-ups queue meanwhile.+ const canSteerActiveTurn = queueWorkflow?.canPromoteToSteer === true && !isCompacting;const runlessWorkStartedAt = useMemo(() =>diff --git a/apps/server/src/orchestration-v2/CommandPolicy.test.ts b/apps/server/src/orchestration-v2/CommandPolicy.test.tsindex 70f9a7e3fa5..d3c9f38a495 100644--- a/apps/server/src/orchestration-v2/CommandPolicy.test.ts+++ b/apps/server/src/orchestration-v2/CommandPolicy.test.ts@@ -1,6 +1,7 @@import { assert, it } from "@effect/vitest";import {CommandId,+ MessageId,type OrchestrationV2ProviderCapabilities,type OrchestrationV2ThreadProjection,ProviderInstanceId,@@ -19,6 +20,7 @@ import * as CommandPolicy from "./CommandPolicy.ts";const commandId = CommandId.make("command-policy-test");const threadId = ThreadId.make("command-policy-thread");const activeRunId = RunId.make("command-policy-active-run");+const userMessageId = MessageId.make("command-policy-user-message");const baseCapabilities: OrchestrationV2ProviderCapabilities = CodexProviderCapabilitiesV2;@@ -37,7 +39,8 @@ function dispatchProjection(runs:sessionCapabilities === undefined? []- : [{ id: activeRunId, status: "running", providerThreadId }],+ : [{ id: activeRunId, status: "running", providerThreadId, userMessageId }],+ messages: [{ id: userMessageId, text: "first", attachments: [] }],providerThreads:sessionCapabilities === undefined ? [] : [{ id: providerThreadId, providerSessionId }],providerSessions:@@ -141,6 +144,39 @@ it("targets the latest active run for explicit steer and restart intent", () =>);});+it.each(["/compact", " /LOGOUT "])("queues a steer sent while %s runs", (text) => {+ const projection = dispatchProjection(baseCapabilities);+ const maintenance = {+ ...projection,+ messages: [{ id: userMessageId, text, attachments: [] }],+ } as unknown as OrchestrationV2ThreadProjection;+ for (const deliveryIntent of ["auto", "steer"] as const) {+ assert.deepEqual(+ CommandPolicy.resolveMessageDispatchIntent(+ maintenance,+ { type: "start_immediately" },+ deliveryIntent,+ ),+ { type: "queue_after_active" },+ );+ }+ assert.deepEqual(+ CommandPolicy.resolveMessageDispatchIntent(maintenance, {+ type: "steer_active",+ targetRunId: activeRunId,+ }),+ { type: "queue_after_active" },+ );+ assert.deepEqual(+ CommandPolicy.resolveMessageDispatchIntent(+ maintenance,+ { type: "start_immediately" },+ "restart",+ ),+ { type: "restart_active", targetRunId: activeRunId },+ );+});+const layer = it.layer(CommandPolicy.layer);layer("CommandPolicyV2", (it) => {diff --git a/apps/server/src/orchestration-v2/CommandPolicy.ts b/apps/server/src/orchestration-v2/CommandPolicy.tsindex 1098c72c307..751ce08f72e 100644--- a/apps/server/src/orchestration-v2/CommandPolicy.ts+++ b/apps/server/src/orchestration-v2/CommandPolicy.ts@@ -1,4 +1,5 @@import {+ type ChatAttachment,CommandId,ModelSelection,type OrchestrationV2Command,@@ -116,10 +117,37 @@ type MessageDispatchMode = Extract<{ readonly type: "message.dispatch" }>["dispatchMode"];+export function isNativeMaintenanceCommand(message: {+ readonly text: string;+ readonly attachments: ReadonlyArray<ChatAttachment>;+ readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;+}): boolean {+ return (+ message.attachments.length === 0 &&+ ["/compact", "/logout"].includes(message.text.trim().toLowerCase())+ );+}+export function resolveMessageDispatchIntent(projection: OrchestrationV2ThreadProjection,requestedMode: MessageDispatchMode,deliveryIntent?: "auto" | "steer" | "restart",+): MessageDispatchMode {+ const mode = resolveDeliveryIntent(projection, requestedMode, deliveryIntent);+ if (mode.type !== "steer_active") return mode;+ // Compaction and sign-out turns cannot take steering input. A message sent+ // while one runs waits in the queue like any other follow-up.+ const target = projection.runs.find((run) => run.id === mode.targetRunId);+ const targetMessage = projection.messages.find((message) => message.id === target?.userMessageId);+ return targetMessage !== undefined && isNativeMaintenanceCommand(targetMessage)+ ? { type: "queue_after_active" }+ : mode;+}++function resolveDeliveryIntent(+ projection: OrchestrationV2ThreadProjection,+ requestedMode: MessageDispatchMode,+ deliveryIntent?: "auto" | "steer" | "restart",): MessageDispatchMode {if (deliveryIntent === undefined) return requestedMode;diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.tsindex 8369af77fdb..491ddff3a72 100644--- a/apps/server/src/orchestration-v2/Orchestrator.ts+++ b/apps/server/src/orchestration-v2/Orchestrator.ts@@ -84,7 +84,11 @@ import {SHARED_WORKSPACE_RESTORE_MESSAGE,} from "./CheckpointRestoreSafety.ts";import { CheckpointServiceV2 } from "./CheckpointService.ts";-import { CommandPolicyV2, resolveMessageDispatchIntent } from "./CommandPolicy.ts";+import {+ CommandPolicyV2,+ isNativeMaintenanceCommand,+ resolveMessageDispatchIntent,+} from "./CommandPolicy.ts";import { CommandReceiptStoreV2 } from "./CommandReceiptStore.ts";import { ContextHandoffServiceV2 } from "./ContextHandoffService.ts";import { notificationTurnItem } from "@t3tools/provider-core/server/notification";@@ -404,17 +408,6 @@ function wakeWorkStartedAt(return previous === undefined ? {} : { workStartedAt: orchestrationV2RunWorkStartedAt(previous) };}-export function isNativeMaintenanceCommand(message: {- readonly text: string;- readonly attachments: ReadonlyArray<ChatAttachment>;- readonly context?: import("@t3tools/contracts").OrchestrationMessageContext | undefined;-}): boolean {- return (- message.attachments.length === 0 &&- ["/compact", "/logout"].includes(message.text.trim().toLowerCase())- );-}-function isGoalCommand(message: {readonly text: string;readonly attachments: ReadonlyArray<ChatAttachment>;diff --git a/apps/server/src/orchestration-v2/RestartContinuation.ts b/apps/server/src/orchestration-v2/RestartContinuation.tsindex 152252233c1..59eee330c1d 100644--- a/apps/server/src/orchestration-v2/RestartContinuation.ts+++ b/apps/server/src/orchestration-v2/RestartContinuation.ts@@ -13,7 +13,7 @@ import * as Effect from "effect/Effect";import type { ProjectionRuntimeRecoveryState } from "./ProjectionStore.ts";import * as ServerSettings from "../serverSettings.ts";-import { isNativeMaintenanceCommand } from "./Orchestrator.ts";+import { isNativeMaintenanceCommand } from "./CommandPolicy.ts";import * as ThreadManagementService from "./ThreadManagementService.ts";import {cancelledRosterTaskWork,diff --git a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts b/apps/server/src/orchestration-v2/ThreadLaunchService.test.tsindex f462c6f88a3..6df98b9809e 100644--- a/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts+++ b/apps/server/src/orchestration-v2/ThreadLaunchService.test.ts@@ -755,19 +755,26 @@ it.effect("keeps native maintenance commands out of steering and restart messageconst targetRun = before.runs[0];if (targetRun === undefined) return yield* Effect.die("Launch must create a run");const commandId = CommandId.make(`${scenario.name}:message`);- const failure = yield* threads- .dispatch({- type: "message.dispatch",- commandId,- threadId: launched.threadId,- messageId: MessageId.make(`${scenario.name}:message`),- createdBy: "user",- creationSource: "web",- text: scenario.next,- attachments: [],- dispatchMode: { type: scenario.mode, targetRunId: targetRun.id },- })- .pipe(Effect.flip);+ const dispatch = threads.dispatch({+ type: "message.dispatch",+ commandId,+ threadId: launched.threadId,+ messageId: MessageId.make(`${scenario.name}:message`),+ createdBy: "user",+ creationSource: "web",+ text: scenario.next,+ attachments: [],+ dispatchMode: { type: scenario.mode, targetRunId: targetRun.id },+ });+ // A steer sent while a maintenance turn runs waits as a queued follow-up.+ if (scenario.name.startsWith("steer-")) {+ yield* dispatch;+ const queued = (yield* threads.getThreadProjection(launched.threadId)).runs[1];+ assert.equal(queued?.status, "queued");+ assert.equal(queued?.userMessageId, MessageId.make(`${scenario.name}:message`));+ continue;+ }+ const failure = yield* dispatch.pipe(Effect.flip);assert.include(String(failure.cause).toLowerCase(),scenario.name.includes("logout") ? "sign" : "context compaction",diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsxindex d5599f8c46a..3e76a11c45b 100644--- a/apps/web/src/components/ChatView.tsx+++ b/apps/web/src/components/ChatView.tsx@@ -11192,6 +11192,7 @@ export default function ChatView(props: ChatViewProps) {isLocalDraftThread && activeProject === null}phase={phase}+ isCompacting={isCompacting}canInterrupt={canInterruptRunningThread}isConnecting={isConnecting}isSendBusy={diff --git a/apps/web/src/components/chat/ChatComposer.tsx b/apps/web/src/components/chat/ChatComposer.tsxindex 017705a864b..41648e526e3 100644--- a/apps/web/src/components/chat/ChatComposer.tsx+++ b/apps/web/src/components/chat/ChatComposer.tsx@@ -1354,6 +1354,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(isRunning: boolean;canInterrupt: boolean;followUpBehavior: "queue" | "steer";+ canSteer: boolean;alternateShortcutLabel: string | null;showPlanFollowUpPrompt: boolean;promptHasText: boolean;@@ -1397,6 +1398,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(isRunning={props.isRunning}canInterrupt={props.canInterrupt}followUpBehavior={props.followUpBehavior}+ canSteer={props.canSteer}alternateShortcutLabel={props.alternateShortcutLabel}showPlanFollowUpPrompt={props.showPlanFollowUpPrompt}promptHasText={props.promptHasText}@@ -1516,6 +1518,7 @@ export interface ChatComposerProps {isRevertingCheckpoint?: boolean;sendDisabledReason: string | null;isPreparingWorktree: boolean;+ isCompacting: boolean;bannerItems: readonly ComposerBannerStackItem[];resumeCompactionTokens: number | null;keepFullHistory: boolean;@@ -1676,6 +1679,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)isRevertingCheckpoint = false,sendDisabledReason: externalSendDisabledReason,isPreparingWorktree,+ isCompacting,environmentUnavailable,activePendingApproval: incomingPendingApproval,pendingApprovals,@@ -4023,6 +4027,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)running: phase === "running",alternateModifier: false,activeTurnDefault: settings.followUpBehavior,+ canSteer: !isCompacting,}),submissionIntent,);@@ -4045,6 +4050,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)running: phase === "running",alternateModifier: event.metaKey || event.ctrlKey,activeTurnDefault: settings.followUpBehavior,+ canSteer: !isCompacting,}),);};@@ -4056,6 +4062,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)running: phase === "running",alternateModifier: false,activeTurnDefault: settings.followUpBehavior,+ canSteer: !isCompacting,}),);};@@ -4216,6 +4223,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)running: phase === "running",alternateModifier: submissionIntent === "alternate",activeTurnDefault: settings.followUpBehavior,+ canSteer: !isCompacting,}),submissionIntent,);@@ -7282,6 +7290,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)isRunning={phase === "running"}canInterrupt={canInterrupt}followUpBehavior={settings.followUpBehavior}+ canSteer={!isCompacting}alternateShortcutLabel={shortcutLabelForCommand(keybindings,"composer.sendAlternate",diff --git a/apps/web/src/components/chat/ComposerPrimaryActions.tsx b/apps/web/src/components/chat/ComposerPrimaryActions.tsxindex 6317a090dce..d74c5a694dc 100644--- a/apps/web/src/components/chat/ComposerPrimaryActions.tsx+++ b/apps/web/src/components/chat/ComposerPrimaryActions.tsx@@ -32,6 +32,7 @@ interface ComposerPrimaryActionsProps {isRunning: boolean;canInterrupt: boolean;followUpBehavior?: "queue" | "steer";+ canSteer?: boolean;alternateShortcutLabel?: string | null;showPlanFollowUpPrompt: boolean;promptHasText: boolean;@@ -86,6 +87,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({isRunning,canInterrupt,followUpBehavior = "steer",+ canSteer = true,alternateShortcutLabel = null,showPlanFollowUpPrompt,promptHasText,@@ -117,6 +119,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({resolveComposerDispatchMode({running: isRunning,activeTurnDefault: followUpBehavior,+ canSteer,alternateModifier: shortcutModifiers.metaKey || shortcutModifiers.ctrlKey,}) === "queue";const alternateAction = alternateComposerDispatchAction(followUpBehavior);@@ -297,7 +300,7 @@ export const ComposerPrimaryActions = memo(function ComposerPrimaryActions({submitStatus ??(compactsBeforeSend? `Summarize ${compactTokens} tokens of history, then send`- : isRunning && !isEditingQueuedMessage+ : isRunning && !isEditingQueuedMessage && canSteer? `Click to ${followUpBehavior}, Ctrl/⌘-click${alternateShortcutLabel ? ` or ${alternateShortcutLabel}` : ""} to ${alternateAction}`: submitLabel);diff --git a/packages/client-runtime/src/state/composerDispatch.test.ts b/packages/client-runtime/src/state/composerDispatch.test.tsindex c2d7cfb1269..e635066c86c 100644--- a/packages/client-runtime/src/state/composerDispatch.test.ts+++ b/packages/client-runtime/src/state/composerDispatch.test.ts@@ -64,6 +64,19 @@ describe("resolveComposerDispatchMode", () => {},);+ it("queues with or without the modifier while steering is unavailable", () => {+ for (const alternateModifier of [false, true]) {+ expect(+ resolveComposerDispatchMode({+ running: true,+ alternateModifier,+ activeTurnDefault: "steer",+ canSteer: false,+ }),+ ).toBe("queue");+ }+ });+it("names the alternate action so the affordance can be labelled", () => {expect(alternateComposerDispatchAction("queue")).toBe("steer");expect(alternateComposerDispatchAction("steer")).toBe("queue");diff --git a/packages/client-runtime/src/state/composerDispatch.ts b/packages/client-runtime/src/state/composerDispatch.tsindex b6f76499a33..145b1ba5081 100644--- a/packages/client-runtime/src/state/composerDispatch.ts+++ b/packages/client-runtime/src/state/composerDispatch.ts@@ -5,8 +5,11 @@ export function resolveComposerDispatchMode(input: {readonly running: boolean;readonly alternateModifier: boolean;readonly activeTurnDefault?: ActiveTurnComposerAction;+ /** False while the active turn cannot take steering input, such as during compaction. */+ readonly canSteer?: boolean;}): ComposerDispatchMode {if (!input.running) return "auto";+ if (input.canSteer === false) return "queue";const defaultAction = input.activeTurnDefault ?? "steer";if (input.alternateModifier) return defaultAction === "queue" ? "steer" : "queue";return defaultAction;