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
29 changes: 29 additions & 0 deletions apps/server/src/services/threads/dispatch-attempt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,12 @@ import { runThreadLifecycleInTransaction } from "./lifecycle/run.js";
import { buildExecutionOptions } from "./thread-commands.js";
import {
getActiveTurnId,
getActiveTurnInitiator,
isActiveTurnMainRunIdle,
isManualCompactionActive,
} from "./thread-events.js";
import { requireThreadCommandEnvironment } from "./thread-command-environment.js";
import { resolvePermissionEscalation } from "./thread-runtime-config.js";
import { assertThreadHostAcceptsWork } from "./thread-host-admission.js";
import {
requestThreadProvision,
Expand Down Expand Up @@ -594,6 +596,33 @@ async function runDispatchAttempt(
return;
}

if (
thread.status === "active" &&
attempt === "join-turn" &&
!isActiveTurnMainRunIdle(deps, currentThread)
) {
const runningTurnInitiator = getActiveTurnInitiator(deps, currentThread);
if (
runningTurnInitiator !== null &&
resolvePermissionEscalation({ initiator: author.initiator }) ===
"deny" &&
resolvePermissionEscalation({ initiator: runningTurnInitiator }) ===
"ask"
) {
deps.logger.info(
{
threadId: thread.id,
initiator: author.initiator,
runningTurnInitiator,
senderThreadId: author.senderThreadId,
},
"Queued a message behind the running turn instead of steering it in: its approval policy is deny and would revoke the running turn's approvals",
);
continued.outcome = waitOn({ kind: "thread-busy" });
return;
}
}

if (
dispatchEnvironment !== null &&
goneThreadEnvironmentDetails(dispatchEnvironment) === null &&
Expand Down
20 changes: 20 additions & 0 deletions apps/server/src/services/threads/thread-events.ts
Original file line number Diff line number Diff line change
Expand Up @@ -919,6 +919,26 @@ export function isManualCompactionActive(
);
}

export function getActiveTurnInitiator(
deps: ThreadEventReadDeps,
thread: Pick<Thread, "id" | "status">,
): ThreadTurnInitiator | null {
if (thread.status !== "active") {
return null;
}
const activeTurnId = getActiveStoredTurnId(deps.db, thread.id);
const requestRow =
(activeTurnId === null
? null
: getStoredTurnRequestEventForTurn(deps.db, {
threadId: thread.id,
turnId: activeTurnId,
})) ?? getLastStoredTurnRequestEvent(deps.db, thread.id);
return requestRow === null
? null
: parseStoredTurnRequestEvent(requestRow).initiator;
}

export function getLastProviderThreadId(
deps: ThreadEventReadDeps,
threadId: string,
Expand Down
4 changes: 3 additions & 1 deletion apps/server/test/helpers/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import type {
ThreadOriginKind,
ThreadStatus,
ThreadParentNotifications,
ThreadTurnInitiator,
ThreadVisibility,
} from "@bb/domain";
import type { AppDeps } from "../../src/types.js";
Expand Down Expand Up @@ -382,6 +383,7 @@ export function seedThreadRuntimeState(
deps: Pick<AppDeps, "db" | "hub">,
args: {
environmentId: string | null;
initiator?: ThreadTurnInitiator;
inputText?: string;
model?: string;
providerThreadId: string;
Expand Down Expand Up @@ -426,7 +428,7 @@ export function seedThreadRuntimeState(
permissionMode: args.permissionMode ?? "full",
source: "client/turn/requested",
},
initiator: "user",
initiator: args.initiator ?? "user",
senderThreadId: null,
request: {
method: "turn/start",
Expand Down
127 changes: 127 additions & 0 deletions apps/server/test/threads/dispatcher-paths.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {
getQueuedThreadMessage,
getThread,
listQueuedThreadMessages,
setQueuedThreadMessageGroupBoundary,
} from "@bb/db";
Expand Down Expand Up @@ -531,3 +532,129 @@ describe("queue intent after the dispatch hook", () => {
});
});
});

describe("an agent message sent while a turn runs", () => {
async function sendFromSender(
harness: TestAppHarness,
args: { threadId: string; senderThreadId: string; text: string },
) {
const thread = getThread(harness.db, args.threadId);
if (thread === null) throw new Error("expected a thread");
return acceptThreadSendRequest(harness.deps, {
payload: {
input: textInput(args.text),
mode: "auto",
senderThreadId: args.senderThreadId,
},
thread,
});
}

function runDispatchedTurn(
harness: TestAppHarness,
fixture: ReturnType<typeof seedRunnableThread>,
turnId: string,
) {
moveThreadStatus(harness.deps, {
move: "run.started",
threadId: fixture.thread.id,
});
seedTurnStarted(harness.deps, {
environmentId: fixture.environment.id,
threadId: fixture.thread.id,
turnId,
providerThreadId: `provider-${fixture.host.id}`,
});
}

it("waits behind a turn the user is running, then runs every message in order", async () => {
await withTestHarness(async (harness) => {
const fixture = seedRunnableThread(harness, {
hostId: "host-agent-behind-user-turn",
status: "active",
});
const { thread } = fixture;
const sender = seedThread(harness.deps, {
projectId: fixture.project.id,
title: "Sender",
});

for (const text of ["Notice 1", "Notice 2", "Notice 3"]) {
const response = await sendFromSender(harness, {
threadId: thread.id,
senderThreadId: sender.id,
text,
});
expect(response).toMatchObject({
delivery: "queued",
queuedMessage: { waitingOn: { kind: "thread-busy" } },
});
}
expect(
listQueuedThreadCommands(harness, "turn.submit", thread.id),
).toHaveLength(0);

for (let turn = 1; queuedRows(harness, thread.id).length > 0; turn += 1) {
if (turn > 3) throw new Error("the queue did not drain");
moveThreadStatus(harness.deps, {
move: "run.succeeded",
threadId: thread.id,
});
await runQueuedMessageDispatch(harness.deps, {
kind: "thread-ready",
threadId: thread.id,
});
runDispatchedTurn(harness, fixture, `turn-notice-${turn}`);
}

const agentRequests = turnRequests(harness, thread.id).filter(
(request) => request.initiator === "agent",
);
expect(
agentRequests.flatMap((request) => [
request.target.kind,
...(firstText(request).match(/Notice \d/gu) ?? []),
]),
).toEqual([
"new-turn",
"Notice 1",
"new-turn",
"Notice 2",
"new-turn",
"Notice 3",
]);
});
});

it("still steers into a turn an agent message started", async () => {
await withTestHarness(async (harness) => {
const fixture = seedRunnableThread(harness, {
hostId: "host-agent-into-agent-turn",
status: "idle",
});
const sender = seedThread(harness.deps, {
projectId: fixture.project.id,
title: "Sender",
});
await sendFromSender(harness, {
threadId: fixture.thread.id,
senderThreadId: sender.id,
text: "First notice",
});
runDispatchedTurn(harness, fixture, "turn-first-notice");

const response = await sendFromSender(harness, {
threadId: fixture.thread.id,
senderThreadId: sender.id,
text: "Second notice",
});

expect(response).toMatchObject({ delivery: "sent" });
expect(
turnRequests(harness, fixture.thread.id).map(
(request) => request.target.kind,
),
).toEqual(["new-turn", "new-turn", "auto"]);
});
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ describe("parent system message dispatch", () => {
});
seedThreadRuntimeState(harness.deps, {
environmentId: environment.id,
initiator: "agent",
providerThreadId: "provider-parent-notice",
threadId: thread.id,
});
Expand Down
60 changes: 59 additions & 1 deletion apps/server/test/threads/system-notice-dispatch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from "@bb/db";
import {
turnRequestEventDataSchema,
type ThreadTurnInitiator,
type TurnRequestEventData,
} from "@bb/domain";
import type {
Expand Down Expand Up @@ -41,6 +42,7 @@ import {
createUserQuestionPayload,
} from "../helpers/pending-interactions.js";
import { textInput } from "../helpers/prompt-input.js";
import { moveThreadStatus } from "../helpers/thread-status.js";
import {
seedEnvironment,
seedHostSession,
Expand Down Expand Up @@ -85,7 +87,12 @@ afterEach(() => {

function seedRunnableThread(
harness: TestAppHarness,
args: { hostId: string; status: "idle" | "active"; title?: string },
args: {
hostId: string;
status: "idle" | "active";
title?: string;
runningTurnInitiator?: ThreadTurnInitiator;
},
) {
const { host, session } = seedHostSession(harness.deps, {
id: args.hostId,
Expand All @@ -107,6 +114,9 @@ function seedRunnableThread(
});
seedThreadRuntimeState(harness.deps, {
environmentId: environment.id,
...(args.runningTurnInitiator !== undefined
? { initiator: args.runningTurnInitiator }
: {}),
providerThreadId: `provider-${args.hostId}`,
threadId: thread.id,
});
Expand Down Expand Up @@ -440,6 +450,7 @@ describe("coalesced notices", () => {
const { project, thread: parent } = seedRunnableThread(harness, {
hostId: "host-waiting-notice",
status: "active",
runningTurnInitiator: "agent",
});
const registered =
harness.deps.pendingInteractions.registerPendingInteraction({
Expand Down Expand Up @@ -553,6 +564,7 @@ describe("notice recovery", () => {
const { thread: parent } = seedRunnableThread(harness, {
hostId: "host-notice-recovery",
status: "active",
runningTurnInitiator: "agent",
});
const blocker = await createQueuedMessageForThread(harness.deps, {
thread: parent,
Expand Down Expand Up @@ -604,6 +616,7 @@ describe("notices to a parent mid-turn", () => {
const { thread: parent } = seedRunnableThread(harness, {
hostId: "host-steer-running",
status: "active",
runningTurnInitiator: "agent",
});

await expect(queueChildCompletedNotice(harness, parent.id)).resolves.toBe(
Expand All @@ -617,6 +630,47 @@ describe("notices to a parent mid-turn", () => {
});
});

it("wait behind a turn the user started, then run as their own turn", async () => {
await withTestHarness(async (harness) => {
const { thread: parent } = seedRunnableThread(harness, {
hostId: "host-behind-user-turn",
status: "active",
runningTurnInitiator: "user",
});

await expect(queueChildCompletedNotice(harness, parent.id)).resolves.toBe(
true,
);
expect(turnSubmitTargets(harness, parent.id)).toEqual([]);
expect(queuedRows(harness, parent.id)).toEqual([
expect.objectContaining({ waitingOn: { kind: "thread-busy" } }),
]);

moveThreadStatus(harness.deps, {
move: "run.succeeded",
threadId: parent.id,
});
await runQueuedMessageDispatch(harness.deps, {
kind: "thread-ready",
threadId: parent.id,
});

expect(turnSubmitTargets(harness, parent.id)).toEqual([
{ mode: "auto", expectedTurnId: null },
]);
expect(
turnRequests(harness, parent.id).map((request) => [
request.initiator,
request.target.kind,
]),
).toEqual([
["user", "new-turn"],
["system", "new-turn"],
]);
expect(queuedRows(harness, parent.id)).toEqual([]);
});
});

it("pass a limiter at its cap as a join-turn attempt", async () => {
await withTestHarness(async (harness) => {
const attempts: MessageDispatchHookContext["attempt"][] = [];
Expand All @@ -629,6 +683,7 @@ describe("notices to a parent mid-turn", () => {
const { thread: parent } = seedRunnableThread(harness, {
hostId: "host-steer-at-cap",
status: "active",
runningTurnInitiator: "agent",
});

await queueChildCompletedNotice(harness, parent.id);
Expand All @@ -650,6 +705,7 @@ describe("notices to a parent mid-turn", () => {
const { thread: parent } = seedRunnableThread(harness, {
hostId: "host-steer-held",
status: "active",
runningTurnInitiator: "agent",
});

await queueChildCompletedNotice(harness, parent.id);
Expand All @@ -675,6 +731,7 @@ describe("notices to a parent mid-turn", () => {
const { thread: parent } = seedRunnableThread(harness, {
hostId: "host-steer-question",
status: "active",
runningTurnInitiator: "agent",
});
const registered =
harness.deps.pendingInteractions.registerPendingInteraction({
Expand Down Expand Up @@ -728,6 +785,7 @@ describe("notices to a parent mid-turn", () => {
} = seedRunnableThread(harness, {
hostId: "host-steer-offline",
status: "active",
runningTurnInitiator: "agent",
});
handleDaemonSocketClosed(harness.deps, { sessionId: session.id });
harness.hub.cancelPendingDaemonDisconnect(session.id);
Expand Down
Loading