Skip to content

Commit 9789e3a

Browse files
fix(client-runtime): do not offer Send now into a stopping turn (#45390)
Co-authored-by: SAPHID <saphid@users.noreply.github.com> Co-authored-by: Julius Marminge <julius0216@outlook.com>
1 parent dc8b340 commit 9789e3a

9 files changed

Lines changed: 142 additions & 5 deletions

File tree

‎apps/mobile/src/features/threads/ThreadQueueControl.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -285,6 +285,7 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
285285
// A fresh message starts its own turn: it may skip compaction, but not steer into a turn.
286286
canPromoteToSteer:
287287
(workflow?.canPromoteToSteer ?? false) &&
288+
!queuedRuns[index]!.stopBlocksPromotion &&
288289
(run.freshContext !== true || workflow?.promoteSkipsCompaction === true),
289290
canSendNow: workflow?.canSendNow ?? false,
290291
editBlocked: editBlockedReason !== null,

‎apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx‎

Lines changed: 30 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,15 @@ import * as Cause from "effect/Cause";
1616
import * as DateTime from "effect/DateTime";
1717
import * as Option from "effect/Option";
1818
import { AsyncResult, type Atom, AtomRegistry } from "effect/reactivity";
19-
import { Profiler, useState, type ComponentProps } from "react";
19+
import { createRef, Profiler, useState, type ComponentProps } from "react";
2020
import { expect, it, vi } from "vite-plus/test";
2121
import { page, userEvent } from "vite-plus/test/browser";
2222

2323
const state = vi.hoisted(() => ({
2424
threadState: null as unknown as Atom.Writable<AsyncResult.AsyncResult<EnvironmentThreadState>>,
2525
workflow: null as unknown,
2626
commandResult: undefined as unknown,
27+
commandCalls: 0,
2728
}));
2829

2930
vi.mock(import("@t3tools/client-runtime/state/thread-workflows"), async (importOriginal) => ({
@@ -74,7 +75,10 @@ vi.mock(import("../../state/threads"), async (importOriginal) => {
7475

7576
vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({
7677
...(await importOriginal()),
77-
useAtomCommand: (() => async () => state.commandResult) as never,
78+
useAtomCommand: (() => async () => {
79+
state.commandCalls += 1;
80+
return state.commandResult;
81+
}) as never,
7882
}));
7983

8084
vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({
@@ -90,13 +94,14 @@ import { act, fakeTimers, render as renderUi } from "../../../test/render";
9094
import { makeStreamingTimelineFixture, makeThreadProjectionFixture } from "../../test-fixtures";
9195
import { SharedTooltipProvider } from "../ui/shared-tooltip";
9296
import { ToastProvider } from "../ui/toast";
93-
import { QueuedRunsControl } from "./QueuedRunsControl";
97+
import { QueuedRunsControl, type QueuedRunsControlHandle } from "./QueuedRunsControl";
9498
import { ExpandedImageDialog } from "./ExpandedImageDialog";
9599
import type { ExpandedImagePreview } from "./ExpandedImagePreview";
96100

97101
function setup() {
98102
state.workflow = null;
99103
state.commandResult = undefined;
104+
state.commandCalls = 0;
100105
}
101106

102107
const baseProps = {
@@ -445,6 +450,28 @@ it("tells the user why Send now was rejected", async () => {
445450
await vi.waitFor(() => expect(page.getByText(reason).element()).toBeVisible());
446451
});
447452

453+
it("keeps the send shortcut from the composer while Stop blocks the queued message", async () => {
454+
setup();
455+
state.workflow = {
456+
activeRun: { id: "run:active" },
457+
canPromoteToSteer: true,
458+
queuedRuns: [
459+
{
460+
run: { id: "run:queued", userMessageId: "message:queued" },
461+
text: "Follow up",
462+
attachments: [],
463+
stopBlocksPromotion: true,
464+
},
465+
],
466+
};
467+
const ref = createRef<QueuedRunsControlHandle>();
468+
await using _screen = await renderQueue({ ref });
469+
470+
await expect.element(page.getByText("Follow up", { exact: true })).toBeVisible();
471+
expect(ref.current?.steerNext(false)).toBe(true);
472+
expect(state.commandCalls).toBe(0);
473+
});
474+
448475
it("shares the hover tooltip between Remove and Edit and keeps it when Edit is disabled", async () => {
449476
setup();
450477
const reason = "Answer the question to edit queued messages";

‎apps/web/src/components/chat/QueuedRunsControl.tsx‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -124,9 +124,10 @@ export function QueuedRunsControl({
124124
const queued = workflow?.queuedRuns ?? [];
125125
const activeRun = workflow?.activeRun ?? null;
126126
// A fresh message starts its own turn: it may skip compaction, but not steer into a turn.
127-
const canSendRun = (freshContext: boolean) =>
127+
const canSendRun = (freshContext: boolean, stopBlocksPromotion = false) =>
128128
workflow?.canSendNow === true ||
129129
(workflow?.canPromoteToSteer === true &&
130+
!stopBlocksPromotion &&
130131
(!freshContext || workflow.promoteSkipsCompaction === true));
131132
const queuedImageUrlById = new Map(
132133
queuedImageAttachmentUrls.flatMap((url, index) => {
@@ -144,6 +145,7 @@ export function QueuedRunsControl({
144145
runId: run.id,
145146
messageId: run.userMessageId,
146147
freshContext: run.freshContext === true,
148+
stopBlocksPromotion: queued[serverIndex]!.stopBlocksPromotion,
147149
serverIndex,
148150
text,
149151
// A guest's message keeps the guest's words; the owner can cancel it, not rewrite it.
@@ -165,6 +167,7 @@ export function QueuedRunsControl({
165167
runId: null,
166168
messageId: null,
167169
freshContext: false,
170+
stopBlocksPromotion: false,
168171
serverIndex: null,
169172
text: message.text,
170173
editable: true,
@@ -211,6 +214,8 @@ export function QueuedRunsControl({
211214
steerNext(repeat) {
212215
const next = queued[0];
213216
if (!next || !canSendRun(next.run.freshContext === true)) return false;
217+
// Keep the chord while Stop settles, or the composer takes it as a line break.
218+
if (!canSendRun(next.run.freshContext === true, next.stopBlocksPromotion)) return true;
214219
if (!repeat && busyRunId === null) void sendQueuedMessage(next.run.id);
215220
return true;
216221
},
@@ -303,7 +308,7 @@ export function QueuedRunsControl({
303308
onOpenThread={props.onOpenThread}
304309
onImageExpand={props.onImageExpand}
305310
>
306-
{canSendRun(item.freshContext) && !isEditing ? (
311+
{canSendRun(item.freshContext, item.stopBlocksPromotion) && !isEditing ? (
307312
<>
308313
<SharedTooltipTrigger
309314
render={<span className="flex shrink-0" />}

‎apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,6 +94,7 @@ vi.mock("../../state/threads", async () => {
9494
thread: { id: ref.threadId, activeProviderThreadId: null },
9595
runs,
9696
messages: [],
97+
turnItems: [],
9798
providerThreads: [],
9899
providerSessions: [
99100
{

‎apps/web/src/components/chat/useQueuedRunEdit.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -463,6 +463,7 @@ export function useQueuedRunEdit(input: {
463463
queued === undefined ||
464464
workflow.activeRun === null ||
465465
!workflow.canPromoteToSteer ||
466+
queued.stopBlocksPromotion ||
466467
(queued.run.freshContext === true && !workflow.promoteSkipsCompaction)
467468
) {
468469
return;

‎packages/client-runtime/src/state/threadDetail.test.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -445,6 +445,42 @@ describe("derived thread state through a streamed message", () => {
445445
});
446446
});
447447

448+
it("blocks promoting a queued message when only the Stop marker arrives", () => {
449+
const ref = { environmentId: EnvironmentId.make("environment-1"), threadId: v2ThreadId };
450+
const running = {
451+
...v2Projection,
452+
thread: { ...v2Projection.thread, activeProviderThreadId: "provider-thread" },
453+
runs: [
454+
{ id: "active", ordinal: 1, status: "running", userMessageId: "first", activeAttemptId: "a" },
455+
{ id: "queued", ordinal: 2, status: "queued", userMessageId: "second" },
456+
],
457+
providerThreads: [{ id: "provider-thread", providerSessionId: "session" }],
458+
providerSessions: [
459+
{
460+
id: "session",
461+
status: "running",
462+
capabilities: { turns: { supportsActiveSteering: true } },
463+
},
464+
],
465+
providerTurns: [{ runAttemptId: "a", status: "running" }],
466+
} as unknown as OrchestrationV2ThreadProjection;
467+
const state = (projection: OrchestrationV2ThreadProjection) =>
468+
AsyncResult.success({ ...EMPTY_ENVIRONMENT_THREAD_STATE, data: Option.some(projection) });
469+
const stateAtom = Atom.make(state(running));
470+
const queue = createEnvironmentThreadDetailAtoms(() => stateAtom).queueWorkflowAtom(ref);
471+
const registry = AtomRegistry.make();
472+
registry.mount(queue);
473+
expect(registry.get(queue)?.queuedRuns[0]?.stopBlocksPromotion).toBe(false);
474+
475+
const stop = {
476+
runId: "active",
477+
type: "run_interrupt_request",
478+
} as unknown as OrchestrationV2TurnItem;
479+
registry.set(stateAtom, state({ ...running, turnItems: [stop] }));
480+
expect(registry.get(queue)?.queuedRuns[0]?.stopBlocksPromotion).toBe(true);
481+
registry.dispose();
482+
});
483+
448484
function replaceItem(projection: OrchestrationV2ThreadProjection, item: OrchestrationV2TurnItem) {
449485
return applyOrchestrationV2ProjectionEvent(projection, {
450486
id: EventId.make(`event-${item.id}`),

‎packages/client-runtime/src/state/threadDetail.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,8 @@ import { AsyncResult, Atom } from "effect/reactivity";
1212
import {
1313
deriveThreadQueueWorkflowState,
1414
getUserQueuedThreadRuns,
15+
resolveActiveThreadRun,
16+
runStopRequested,
1517
type ThreadQueueWorkflowState,
1618
} from "./threadWorkflows.ts";
1719
import { deriveThreadTurnSubagents, type ThreadTurnSubagents } from "./threadSubagents.ts";
@@ -106,6 +108,7 @@ function queueWorkflowStatesEqual(
106108
left.queuedRuns.every(
107109
(queued, index) =>
108110
queued.run === right.queuedRuns[index]!.run &&
111+
queued.stopBlocksPromotion === right.queuedRuns[index]!.stopBlocksPromotion &&
109112
queued.message === right.queuedRuns[index]!.message,
110113
)
111114
);
@@ -417,14 +420,26 @@ export function createEnvironmentThreadDetailAtoms<E>(
417420
OrchestrationV2ThreadProjection,
418421
"thread" | "runs" | "messages" | "providerThreads" | "providerSessions" | "providerTurns"
419422
> | null = null;
423+
let previousStopRequested = false;
424+
let previousStructure: EnvironmentThreadStructure | null = null;
425+
let stopRequested = false;
420426
let value: ThreadQueueWorkflowState | null = null;
421427
return Atom.make((get) => {
422428
const projection = Option.getOrNull(get(threadStateValueAtomFamily(key)).data);
429+
// The structure holds through streamed text, so Stop is checked without a scan per chunk.
430+
const structure = get(quietThreadAtomFamily(key));
431+
if (structure !== previousStructure) {
432+
previousStructure = structure;
433+
stopRequested =
434+
structure !== null &&
435+
runStopRequested(structure.projection, resolveActiveThreadRun(structure.projection)?.id);
436+
}
423437
if (projection === null) {
424438
previous = null;
425439
value = null;
426440
} else if (
427441
previous === null ||
442+
stopRequested !== previousStopRequested ||
428443
projection.thread !== previous.thread ||
429444
projection.runs !== previous.runs ||
430445
projection.messages !== previous.messages ||
@@ -437,6 +452,7 @@ export function createEnvironmentThreadDetailAtoms<E>(
437452
const { thread, runs, messages, providerThreads, providerSessions, providerTurns } =
438453
projection;
439454
previous = { thread, runs, messages, providerThreads, providerSessions, providerTurns };
455+
previousStopRequested = stopRequested;
440456
}
441457
return value;
442458
}).pipe(Atom.setIdleTTL(0), Atom.withLabel(`environment-thread-queue:${key}`));

‎packages/client-runtime/src/state/threadWorkflows.test.ts‎

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ describe("thread workflows", () => {
125125
it("sorts queued messages and gates promotion from capabilities", () => {
126126
const state = deriveThreadQueueWorkflowState({
127127
thread: { id: "thread", activeProviderThreadId: "provider-thread" },
128+
turnItems: [],
128129
runs: [
129130
{
130131
id: "active",
@@ -194,11 +195,49 @@ describe("thread workflows", () => {
194195
expect(state.canSendNow).toBe(false);
195196
});
196197

198+
it.each([
199+
["a message before Stop", "Follow up", false, false],
200+
["a message once Stop reaches the run", "Follow up", true, true],
201+
["a command once Stop reaches the run", "/review", true, false],
202+
] as const)("gates promoting %s", (_, text, stopped, blocked) => {
203+
const state = deriveThreadQueueWorkflowState({
204+
thread: { id: "thread", activeProviderThreadId: "provider-thread" },
205+
runs: [
206+
{
207+
id: "active",
208+
ordinal: 1,
209+
status: "running",
210+
userMessageId: "first",
211+
activeAttemptId: "attempt",
212+
},
213+
{ id: "queued", ordinal: 2, status: "queued", userMessageId: "second" },
214+
],
215+
messages: [
216+
{ id: "first", text: "First" },
217+
{ id: "second", text, attachments: [] },
218+
],
219+
providerThreads: [
220+
{ id: "provider-thread", appThreadId: "thread", providerSessionId: "session" },
221+
],
222+
providerSessions: [
223+
{ id: "session", status: "running", capabilities: capabilities({ steer: true }) },
224+
],
225+
providerTurns: [{ runAttemptId: "attempt", status: "running" }],
226+
turnItems: stopped ? [{ runId: "active", type: "run_interrupt_request" }] : [],
227+
} as never);
228+
229+
expect(state.canPromoteToSteer).toBe(true);
230+
expect(
231+
state.queuedRuns.map(({ run, stopBlocksPromotion }) => [run.id, stopBlocksPromotion]),
232+
).toEqual([["queued", blocked]]);
233+
});
234+
197235
it.each(["completed", "interrupted", "cancelled", "failed"])(
198236
"allows sending a held message after a %s turn without a live session",
199237
(status) => {
200238
const state = deriveThreadQueueWorkflowState({
201239
thread: { id: "thread", activeProviderThreadId: null },
240+
turnItems: [],
202241
runs: [
203242
{ id: "previous", status, ordinal: 1 },
204243
{ id: "queued", status: "queued", userMessageId: "message", ordinal: 2, queueHeld: true },
@@ -220,6 +259,7 @@ describe("thread workflows", () => {
220259
(status) => {
221260
const state = deriveThreadQueueWorkflowState({
222261
thread: { id: "thread", activeProviderThreadId: null },
262+
turnItems: [],
223263
runs: [{ id: "active", status, ordinal: 1 }],
224264
messages: [],
225265
providerThreads: [],
@@ -234,6 +274,7 @@ describe("thread workflows", () => {
234274
it("offers to skip a running compaction even when the provider cannot steer", () => {
235275
const state = deriveThreadQueueWorkflowState({
236276
thread: { id: "thread", activeProviderThreadId: null },
277+
turnItems: [],
237278
runs: [
238279
{ id: "compact", status: "running", userMessageId: "message-compact", ordinal: 1 },
239280
{ id: "queued", status: "queued", userMessageId: "message-queued", ordinal: 2 },
@@ -255,6 +296,7 @@ describe("thread workflows", () => {
255296
for (const status of ["queued", "cancelled", "starting"] as const) {
256297
const state = deriveThreadQueueWorkflowState({
257298
thread: { id: "thread", activeProviderThreadId: null },
299+
turnItems: [],
258300
runs: [{ id: "held", status, userMessageId: "message", ordinal: 1, queueHeld: true }],
259301
messages: [{ id: "message", text: "Saved message" }],
260302
providerThreads: [],
@@ -271,6 +313,7 @@ describe("thread workflows", () => {
271313
it("hides automatic completion delivery from the visible queue", () => {
272314
const state = deriveThreadQueueWorkflowState({
273315
thread: { id: "thread", activeProviderThreadId: null },
316+
turnItems: [],
274317
runs: [
275318
{
276319
id: "provider-wake",
@@ -328,6 +371,7 @@ describe("thread workflows", () => {
328371
it("removes only the promoted head from the visible queue", () => {
329372
const state = deriveThreadQueueWorkflowState({
330373
thread: { id: "thread", activeProviderThreadId: "provider-thread" },
374+
turnItems: [],
331375
runs: [
332376
{
333377
id: "promoted",
@@ -366,6 +410,7 @@ describe("thread workflows", () => {
366410
(status) => {
367411
const state = deriveThreadQueueWorkflowState({
368412
thread: { id: "thread", activeProviderThreadId: "provider-thread" },
413+
turnItems: [],
369414
runs: [
370415
{
371416
id: "active",

‎packages/client-runtime/src/state/threadWorkflows.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import {
55
type OrchestrationV2ProviderCapabilities,
66
} from "@t3tools/contracts";
77
import { copySorted } from "@t3tools/shared/Array";
8+
import { isSlashCommand } from "@t3tools/shared/composerTrigger";
89
import { mFallback, msg } from "gt-i18n";
910
import type { MFunctionType } from "gt-i18n/types";
1011

@@ -30,6 +31,8 @@ export interface QueuedThreadRun {
3031
readonly attachments: ReadonlyArray<ChatAttachment>;
3132
readonly messageId: Message["id"];
3233
readonly context?: Message["context"];
34+
/** After Stop the server still moves a queued command first, but rejects a steer. */
35+
readonly stopBlocksPromotion: boolean;
3336
/** Carries the attribution a sent message shows: automation, agent sender, or guest. */
3437
readonly message?: Message;
3538
}
@@ -199,6 +202,7 @@ export function deriveThreadQueueWorkflowState(
199202
projection.providerTurns.some(
200203
(turn) => turn.runAttemptId === activeRun.activeAttemptId && turn.status === "running",
201204
);
205+
const stopRequested = runStopRequested(projection, activeRun?.id) && !promoteSkipsCompaction;
202206
const queuedRuns = copySorted(
203207
getUserQueuedThreadRuns(projection),
204208
(left, right) =>
@@ -212,6 +216,7 @@ export function deriveThreadQueueWorkflowState(
212216
text: message?.context?.guest?.text ?? message?.text ?? resolve(msg("Queued message")),
213217
attachments: message?.attachments ?? [],
214218
messageId: run.userMessageId,
219+
stopBlocksPromotion: stopRequested && !(message !== undefined && isSlashCommand(message)),
215220
...(message?.context ? { context: message.context } : {}),
216221
...(message ? { message } : {}),
217222
};

0 commit comments

Comments
 (0)