Skip to content
Merged
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
91 changes: 83 additions & 8 deletions apps/host-daemon/src/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import {
import {
hostDaemonEventBatchRequestSchema,
hostDaemonInteractiveInterruptRequestSchema,
hostDaemonInteractiveWithdrawRequestSchema,
type HostDaemonInteractiveRequestKey,
type HostDaemonInteractiveRequestResponse,
type HostDaemonContributedEnvEntry,
Expand Down Expand Up @@ -191,6 +192,9 @@ function createFetchRecorder(
};
return Response.json(response);
}
if (url.pathname === "/internal/session/interactive-request/withdraw") {
return Response.json({ ok: true, interactionId: "pint_app_test" });
}
if (url.pathname === "/internal/session/interactive-request/interrupt") {
const scripted = args.interruptResponses?.[interruptCount];
interruptCount += 1;
Expand Down Expand Up @@ -1213,7 +1217,10 @@ describe("createHostDaemonApp", () => {
if (!options?.onInteractiveRequest) {
throw new Error("Expected runtime callbacks to be captured");
}
const pending = options.onInteractiveRequest(request);
const pending = options.onInteractiveRequest(
request,
new AbortController().signal,
);
const rejection = expect(pending).rejects.toMatchObject({
code: "interactive_request_ended",
});
Expand Down Expand Up @@ -1441,7 +1448,10 @@ describe("createHostDaemonApp", () => {
}

const request = createCommandApprovalRequest();
const pending = options.onInteractiveRequest(request);
const pending = options.onInteractiveRequest(
request,
new AbortController().signal,
);
await vi.waitFor(() => {
expect(
fetchRecorder.requests.filter(
Expand Down Expand Up @@ -1501,6 +1511,71 @@ describe("createHostDaemonApp", () => {
}
});

it("tells the server to close an interactive request the provider withdraws", async () => {
const { app, fetchRecorder, runtimeOptions } = await createAppFixture();
try {
const workspacePath = await makeTempDir("bb-host-daemon-app-workspace-");
await app.connection.start();
await app.runtimeManager.ensureEnvironment({
environmentId: "env-app-interactive",
workspacePath,
});
const options = runtimeOptions.current;
if (!options?.onInteractiveRequest) {
throw new Error("Expected runtime callbacks to be captured");
}

const request = createCommandApprovalRequest();
const provider = new AbortController();
const pending = options.onInteractiveRequest(request, provider.signal);
await vi.waitFor(() => {
expect(
fetchRecorder.requests.filter(
(record) =>
record.pathname === "/internal/session/interactive-request",
),
).toHaveLength(1);
});

provider.abort();
await expect(pending).rejects.toMatchObject({
code: "interactive_request_withdrawn",
});
await vi.waitFor(() => {
expect(
fetchRecorder.requests.filter(
(record) =>
record.pathname ===
"/internal/session/interactive-request/withdraw",
),
).toHaveLength(1);
});
const withdrawRequest = fetchRecorder.requests.find(
(record) =>
record.pathname === "/internal/session/interactive-request/withdraw",
);
if (!withdrawRequest?.body) {
throw new Error("Expected interactive withdraw request body");
}
expect(
hostDaemonInteractiveWithdrawRequestSchema.parse(
JSON.parse(withdrawRequest.body),
),
).toEqual({
sessionId: "session-app-test",
request: {
threadId: request.threadId,
providerId: request.providerId,
providerThreadId: request.providerThreadId,
providerRequestId: request.providerRequestId,
},
reason: "The agent stopped waiting for this answer",
});
} finally {
await app.daemon.shutdown("test", 0);
}
});

it("drops an interactive interrupt the server rejects instead of retrying it ahead of later interrupts", async () => {
const { app, fetchRecorder, logger, runtimeOptions } =
await createAppFixture({
Expand Down Expand Up @@ -1718,9 +1793,9 @@ describe("createHostDaemonApp", () => {
}

const request = createCommandApprovalRequest();
await expect(options.onInteractiveRequest(request)).rejects.toThrow(
"registration transport failed",
);
await expect(
options.onInteractiveRequest(request, new AbortController().signal),
).rejects.toThrow("registration transport failed");

expect(logger.error).toHaveBeenCalledWith(
expect.objectContaining({
Expand Down Expand Up @@ -1760,9 +1835,9 @@ describe("createHostDaemonApp", () => {
}

const request = createCommandApprovalRequest();
await expect(options.onInteractiveRequest(request)).rejects.toThrow(
"Ask User Question feature is disabled",
);
await expect(
options.onInteractiveRequest(request, new AbortController().signal),
).rejects.toThrow("Ask User Question feature is disabled");

expect(logger.warn).toHaveBeenCalledWith(
expect.objectContaining({
Expand Down
106 changes: 88 additions & 18 deletions apps/host-daemon/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -189,11 +189,21 @@ export interface HostDaemonApp {
connection: ServerConnection;
}

interface PendingInteractiveInterruptRequest {
providerId: string;
reason: string;
threadIds: readonly string[];
}
type PendingInteractiveInterruptRequest =
| {
kind: "threads";
providerId: string;
reason: string;
threadIds: readonly string[];
}
| {
kind: "withdrawn";
reason: string;
request: HostDaemonInteractiveRequestKey;
};

const WITHDRAWN_INTERACTIVE_REQUEST_REASON =
"The agent stopped waiting for this answer";

export function startIdleProviderSessionReaper(
args: StartIdleProviderSessionReaperArgs,
Expand Down Expand Up @@ -352,11 +362,40 @@ export async function createHostDaemonApp(
function buildInteractiveInterruptKey(
request: PendingInteractiveInterruptRequest,
): string {
return [
request.providerId,
request.reason,
[...request.threadIds].sort().join(","),
].join("|");
switch (request.kind) {
case "threads":
return [
request.kind,
request.providerId,
request.reason,
[...request.threadIds].sort().join(","),
].join("|");
case "withdrawn":
return [
request.kind,
request.request.threadId,
request.request.providerId,
request.request.providerThreadId,
request.request.providerRequestId,
].join("|");
}
}

function sendInteractiveInterrupt(
request: PendingInteractiveInterruptRequest,
): Promise<unknown> {
switch (request.kind) {
case "threads":
return runSessionRequest({
source: "interruptInteractiveRequests",
request: () => serverClient.interruptInteractiveRequests(request),
});
case "withdrawn":
return runSessionRequest({
source: "withdrawInteractiveRequest",
request: () => serverClient.withdrawInteractiveRequest(request),
});
}
}

function clearInteractiveInterruptRetry(): void {
Expand Down Expand Up @@ -411,17 +450,15 @@ export async function createHostDaemonApp(

const [key, request] = nextEntry;
try {
await runSessionRequest({
source: "interruptInteractiveRequests",
request: () => serverClient.interruptInteractiveRequests(request),
});
await sendInteractiveInterrupt(request);
pendingInteractiveInterrupts.delete(key);
interactiveInterruptRetryDelayMs =
INTERACTIVE_INTERRUPT_RETRY_DELAY_MS;
} catch (error) {
const logFields = {
providerId: request.providerId,
threadIds: request.threadIds,
...(request.kind === "threads"
? { providerId: request.providerId, threadIds: request.threadIds }
: request.request),
...runtimeErrorLogFields(error),
};
if (isRejectedInteractiveInterrupt(error)) {
Expand Down Expand Up @@ -479,11 +516,24 @@ export async function createHostDaemonApp(
}),
onRegistrationFailure: ({ error, request }) => {
enqueueInteractiveInterrupt({
kind: "threads",
providerId: request.providerId,
reason: `Failed to register interactive request while provider was waiting: ${error.message}`,
threadIds: [request.threadId],
});
},
onRequestWithdrawn: (request) => {
enqueueInteractiveInterrupt({
kind: "withdrawn",
reason: WITHDRAWN_INTERACTIVE_REQUEST_REASON,
request: {
threadId: request.threadId,
providerId: request.providerId,
providerThreadId: request.providerThreadId,
providerRequestId: request.providerRequestId,
},
});
},
});

let sendServerMessage = (_message: HostDaemonDaemonWsMessage) => false;
Expand Down Expand Up @@ -661,10 +711,29 @@ export async function createHostDaemonApp(
throw error;
}
},
onInteractiveRequest: async (request) => {
onInteractiveRequest: async (request, signal) => {
try {
return await interactiveRequestRegistry.registerAndWait(request);
return await interactiveRequestRegistry.registerAndWait(
request,
signal,
);
} catch (error) {
if (
error instanceof InteractiveRequestRegistryError &&
error.code === "interactive_request_withdrawn"
) {
options.logger.info(
{
threadId: request.threadId,
providerThreadId: request.providerThreadId,
turnId: request.turnId,
providerRequestId: request.providerRequestId,
kind: request.payload.kind,
},
"Interactive provider request withdrawn by the provider",
);
throw error;
}
if (
error instanceof InteractiveRequestRegistryError &&
(error.code === "interactive_request_rejected" ||
Expand Down Expand Up @@ -723,6 +792,7 @@ export async function createHostDaemonApp(
});

enqueueInteractiveInterrupt({
kind: "threads",
providerId: info.providerId,
threadIds,
reason,
Expand Down
Loading
Loading