Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion apps/mobile/src/features/threads/ThreadQueueControl.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,8 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
No messages waiting in this queue.
</Text>
) : null}
{queuedRuns.map(({ run, text, attachments, context, message }, index) => {
{queuedRuns.map((item, index) => {
const { run, text, attachments, context, message, steerRejectionReason } = item;
const controls = resolveThreadQueueRowControls({
busy: busyRunId !== null,
// A fresh message starts its own turn: it may skip compaction, but not steer into a turn.
Expand All @@ -263,6 +264,8 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
editBlocked: editBlockedReason !== null,
isEditing: editing?.runId === run.id,
isGuestMessage: context?.guest !== undefined,
steerRejectionReason,
promoteSkipsCompaction: workflow?.promoteSkipsCompaction ?? false,
text,
});
const title =
Expand All @@ -285,6 +288,11 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
{
id: "steer",
title: "Send now",
...(!workflow?.canSendNow &&
!workflow?.promoteSkipsCompaction &&
steerRejectionReason
? { subtitle: steerRejectionReason }
: {}),
attributes: { disabled: !controls.canSend },
image: "arrow.up",
},
Expand Down Expand Up @@ -354,6 +362,11 @@ export function ThreadQueueSheet({ route }: StaticScreenProps<QueueTarget>) {
<Pressable
accessibilityRole="button"
accessibilityLabel={`Send now, queued message ${index + 1}`}
{...(!workflow?.canSendNow &&
!workflow?.promoteSkipsCompaction &&
steerRejectionReason
? { accessibilityHint: steerRejectionReason }
: {})}
disabled={!controls.canSend}
onPress={() => void act(run.id, "steer")}
className="shrink-0 justify-center self-stretch pl-4 active:opacity-70 disabled:opacity-40"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,29 @@ describe("threadQueueControlPresentation", () => {
isEditing,
canPromoteToSteer: false,
canSendNow: true,
text: "Queued message",
steerRejectionReason: "Context compaction must run as a separate turn.",
text: "/compact",
});

expect(controls.canSend).toBe(expected);
},
);

it.each([false, true])(
"gates a queued /compact with compaction skip %s",
(promoteSkipsCompaction) => {
const controls = resolveThreadQueueRowControls({
busy: false,
canPromoteToSteer: true,
canSendNow: false,
steerRejectionReason: "Context compaction must run as a separate turn.",
text: "/compact",
promoteSkipsCompaction,
});
expect(controls.canSend).toBe(promoteSkipsCompaction);
},
);

it("shows an assistant quote as its quoted text", () => {
const href = formatAssistantCitationHref({
version: 1,
Expand All @@ -39,6 +55,7 @@ describe("threadQueueControlPresentation", () => {
busy: false,
canPromoteToSteer: true,
canSendNow: false,
steerRejectionReason: null,
text: `[Assistant quote](${href}) Can we add a backoff here?`,
});

Expand All @@ -53,6 +70,7 @@ describe("threadQueueControlPresentation", () => {
canPromoteToSteer: true,
canSendNow: false,
isEditing: true,
steerRejectionReason: null,
text: "Being edited",
});

Expand All @@ -68,6 +86,7 @@ describe("threadQueueControlPresentation", () => {
canPromoteToSteer: true,
canSendNow: false,
isGuestMessage: true,
steerRejectionReason: null,
text: "Why?",
});

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,13 @@ export function resolveThreadQueueRowControls(input: {
readonly busy: boolean;
readonly canPromoteToSteer: boolean;
readonly canSendNow: boolean;
readonly promoteSkipsCompaction?: boolean;
/** Something else holds the composer, such as an open question. */
readonly editBlocked?: boolean;
readonly isEditing?: boolean;
/** A guest's message keeps the guest's words; the owner can cancel it, not rewrite it. */
readonly isGuestMessage?: boolean;
readonly steerRejectionReason: string | null;
readonly text: string;
}): ThreadQueueRowControls {
const mutationEnabled = !input.busy;
Expand All @@ -33,7 +35,12 @@ export function resolveThreadQueueRowControls(input: {
// away whatever has been typed since.
canEdit:
mutationEnabled && !isEditing && input.isGuestMessage !== true && input.editBlocked !== true,
canSend: mutationEnabled && (input.canPromoteToSteer || input.canSendNow) && !isEditing,
canSend:
mutationEnabled &&
!isEditing &&
(input.canSendNow ||
(input.canPromoteToSteer &&
(input.promoteSkipsCompaction === true || input.steerRejectionReason === null))),
dismissAccessibilityLabel: REMOVE_QUEUED_MESSAGE_ACCESSIBILITY_LABEL,
// Editing and sending keep the original text so quoted citations stay linked.
displayText: isAttachmentOnlyBootstrapPrompt(input.text)
Expand Down
13 changes: 1 addition & 12 deletions apps/server/src/orchestration-v2/CommandPolicy.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {
type ChatAttachment,
CommandId,
isNativeMaintenanceCommand,
type OrchestrationV2Command,
OrchestrationV2ProviderCapabilities,
type OrchestrationV2GoalCommand,
Expand Down Expand Up @@ -59,17 +59,6 @@ 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())
);
}

/**
* A goal command sent into active work stops that work when it starts or
* replaces goal work, or ends a goal that is driving the run.
Expand Down
11 changes: 5 additions & 6 deletions apps/server/src/orchestration-v2/Orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
type ChatAttachment,
CommandId,
type GuestMessageId,
isNativeMaintenanceCommand,
isCompactionCommandMessage,
isOrchestrationV2WorkActive,
isProviderNativeSubagentThread,
Expand Down Expand Up @@ -65,6 +66,7 @@ import {
latestProviderTurnForAttempt,
parseGoalCommand,
orchestrationV2RunWorkStartedAt,
orchestrationV2SteerRejectionReason,
ProviderInstanceId,
ProviderInteractionMode,
isRuntimeModeAbove,
Expand Down Expand Up @@ -113,7 +115,6 @@ import {
followUpOwnerRun,
goalCommandStopsActiveRun,
isActiveRun,
isNativeMaintenanceCommand,
resolveMessageDispatchIntent,
} from "./CommandPolicy.ts";
import { CommandReceiptStoreV2, type CommandReceiptV2 } from "./CommandReceiptStore.ts";
Expand Down Expand Up @@ -5811,14 +5812,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
>,
message: Pick<OrchestrationV2ConversationMessage, "text" | "attachments" | "context">,
) {
if (isNativeMaintenanceCommand(message)) {
const rejectionReason = orchestrationV2SteerRejectionReason(message);
if (rejectionReason !== null) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause:
message.text.trim().toLowerCase() === "/compact"
? "Context compaction must run as a separate turn. Queue it or wait for the active turn to finish."
: "Signing out must run as a separate turn. Queue it or wait for the active turn to finish.",
cause: `${rejectionReason} Queue it or wait for the active turn to finish.`,
});
}
if (parseGoalCommand(message) !== null) {
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/orchestration-v2/RestartContinuation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import {
CommandId,
isNativeMaintenanceCommand,
isOrchestrationV2WorkActive,
latestProviderTurnForAttempt,
MessageId,
Expand All @@ -14,7 +15,6 @@ import * as Effect from "effect/Effect";
import type { ProjectionRuntimeRecoveryState } from "./ProjectionStore.ts";

import * as ServerSettings from "../serverSettings.ts";
import { isNativeMaintenanceCommand } from "./CommandPolicy.ts";
import * as ThreadManagementService from "./ThreadManagementService.ts";
import {
awaitingProviderThreadId,
Expand Down
61 changes: 58 additions & 3 deletions apps/web/src/components/chat/QueuedRunsControl.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,14 @@ import {
import * as DateTime from "effect/DateTime";
import * as Option from "effect/Option";
import { AsyncResult, type Atom, AtomRegistry } from "effect/reactivity";
import { Profiler, type ComponentProps } from "react";
import { createRef, Profiler, type ComponentProps } from "react";
import { expect, it, vi } from "vite-plus/test";
import { page } from "vite-plus/test/browser";

const state = vi.hoisted(() => ({
threadState: null as unknown as Atom.Writable<AsyncResult.AsyncResult<EnvironmentThreadState>>,
workflow: null as unknown,
runCommand: vi.fn(async (_input: unknown) => undefined),
}));

vi.mock(import("@t3tools/client-runtime/state/thread-workflows"), async (importOriginal) => ({
Expand Down Expand Up @@ -66,7 +67,7 @@ vi.mock(import("../../state/threads"), async (importOriginal) => {

vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({
...(await importOriginal()),
useAtomCommand: (() => async () => undefined) as never,
useAtomCommand: (() => state.runCommand) as never,
}));

vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({
Expand All @@ -80,10 +81,11 @@ import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/th

import { act, render as renderUi } from "../../../test/render";
import { makeStreamingTimelineFixture, makeThreadProjectionFixture } from "../../test-fixtures";
import { QueuedRunsControl } from "./QueuedRunsControl";
import { QueuedRunsControl, type QueuedRunsControlHandle } from "./QueuedRunsControl";

function setup() {
state.workflow = null;
state.runCommand.mockClear();
}

const baseProps = {
Expand Down Expand Up @@ -331,3 +333,56 @@ it("does not re-render while assistant text streams into the thread", async () =
await act(() => registry.set(state.threadState, thread("Hello there", true)));
expect(renders).toBeGreaterThan(settled);
});

it.each([
{ canSendNow: false, promoteSkipsCompaction: false },
{ canSendNow: true, promoteSkipsCompaction: false },
{ canSendNow: false, promoteSkipsCompaction: true },
])("gates queued command sending with %j", async ({ canSendNow, promoteSkipsCompaction }) => {
setup();
state.workflow = {
activeRun: { id: "run:active" },
canSendNow,
promoteSkipsCompaction,
canPromoteToSteer: !canSendNow,
canReorder: true,
queuedRuns: [
{
run: { id: "run:compact", userMessageId: "message:compact" },
text: "/compact",
attachments: [],
steerRejectionReason: "Context compaction must run as a separate turn.",
},
{
run: { id: "run:plain", userMessageId: "message:plain" },
text: "Also update the docs",
attachments: [],
steerRejectionReason: null,
},
],
};
const ref = createRef<QueuedRunsControlHandle>();
await using _screen = await renderQueue({ ref });

const steerButtons = page.getByRole("button", {
name: "Send now",
exact: true,
});
if (canSendNow || promoteSkipsCompaction) await expect.element(steerButtons.nth(0)).toBeEnabled();
else await expect.element(steerButtons.nth(0)).toBeDisabled();
await expect.element(steerButtons.nth(1)).toBeEnabled();

expect(ref.current?.steerNext(false)).toBe(true);
expect(state.runCommand).toHaveBeenCalledExactlyOnceWith(
expect.objectContaining({
input: expect.objectContaining(
canSendNow
? { runId: "run:compact" }
: {
queuedRunId: promoteSkipsCompaction ? "run:compact" : "run:plain",
targetRunId: "run:active",
},
),
}),
);
});
Loading
Loading