Skip to content

Commit bb49562

Browse files
committed
fix(server): cancel pending questions on stop
1 parent 2433f4c commit bb49562

2 files changed

Lines changed: 149 additions & 1 deletion

File tree

‎apps/server/src/orchestration/Layers/ProviderCommandReactor.test.ts‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2449,7 +2449,7 @@ describe("ProviderCommandReactor", () => {
24492449
});
24502450
});
24512451

2452-
it("reacts to thread.turn.interrupt-requested by calling provider interrupt", async () => {
2452+
it("interrupts the provider and cancels pending user input", async () => {
24532453
const harness = await createHarness();
24542454
const now = "2026-01-01T00:00:00.000Z";
24552455

@@ -2471,6 +2471,35 @@ describe("ProviderCommandReactor", () => {
24712471
}),
24722472
);
24732473

2474+
await Effect.runPromise(
2475+
harness.engine.dispatch({
2476+
type: "thread.activity.append",
2477+
commandId: CommandId.make("cmd-user-input-requested"),
2478+
threadId: ThreadId.make("thread-1"),
2479+
activity: {
2480+
id: EventId.make("activity-user-input-requested-before-interrupt"),
2481+
tone: "info",
2482+
kind: "user-input.requested",
2483+
summary: "User input requested",
2484+
payload: {
2485+
requestId: "user-input-request-1",
2486+
questions: [
2487+
{
2488+
id: "continue",
2489+
header: "Continue",
2490+
question: "Continue?",
2491+
options: [{ label: "Yes", description: "Continue the turn." }],
2492+
multiSelect: false,
2493+
},
2494+
],
2495+
},
2496+
turnId: asTurnId("turn-1"),
2497+
createdAt: "2025-12-31T23:59:59.000Z",
2498+
},
2499+
createdAt: "2025-12-31T23:59:59.000Z",
2500+
}),
2501+
);
2502+
24742503
await Effect.runPromise(
24752504
harness.engine.dispatch({
24762505
type: "thread.turn.interrupt",
@@ -2485,6 +2514,30 @@ describe("ProviderCommandReactor", () => {
24852514
expect(harness.interruptTurn.mock.calls[0]?.[0]).toEqual({
24862515
threadId: "thread-1",
24872516
});
2517+
await waitFor(async () => {
2518+
const readModel = await harness.readModel();
2519+
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
2520+
return (
2521+
thread?.activities.some(
2522+
(activity) =>
2523+
activity.kind === "user-input.resolved" &&
2524+
(activity.payload as { requestId?: unknown }).requestId === "user-input-request-1",
2525+
) ?? false
2526+
);
2527+
});
2528+
2529+
const readModel = await harness.readModel();
2530+
const thread = readModel.threads.find((entry) => entry.id === ThreadId.make("thread-1"));
2531+
expect(
2532+
thread?.activities.find((activity) => activity.kind === "user-input.resolved"),
2533+
).toMatchObject({
2534+
summary: "User input cancelled",
2535+
payload: {
2536+
requestId: "user-input-request-1",
2537+
cancelled: true,
2538+
},
2539+
turnId: "turn-1",
2540+
});
24882541
});
24892542

24902543
it("starts a fresh session when only projected session state exists", async () => {

‎apps/server/src/orchestration/Layers/ProviderCommandReactor.ts‎

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
EventId,
55
type ModelSelection,
66
type OrchestrationEvent,
7+
type OrchestrationThread,
78
ProviderDriverKind,
89
type ProjectId,
910
type OrchestrationSession,
@@ -16,6 +17,7 @@ import { isTemporaryWorktreeBranch, WORKTREE_BRANCH_PREFIX } from "@t3tools/shar
1617
import * as Cache from "effect/Cache";
1718
import * as Cause from "effect/Cause";
1819
import * as Crypto from "effect/Crypto";
20+
import * as DateTime from "effect/DateTime";
1921
import * as Duration from "effect/Duration";
2022
import * as Effect from "effect/Effect";
2123
import * as Equal from "effect/Equal";
@@ -49,6 +51,10 @@ import { GitWorkflowService } from "../../git/GitWorkflowService.ts";
4951
const isProviderAdapterRequestError = Schema.is(ProviderAdapterRequestError);
5052
const isProviderDriverKind = Schema.is(ProviderDriverKind);
5153

54+
// Server-side timestamps for reactor-appended activities. Client-supplied
55+
// command timestamps can predate the thread activity they must follow.
56+
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
57+
5258
type ProviderIntentEvent = Extract<
5359
OrchestrationEvent,
5460
{
@@ -275,6 +281,43 @@ function stalePendingRequestDetail(
275281
return `Stale pending ${requestKind} request: ${requestId}. Provider callback state does not survive app restarts or recovered sessions. Restart the turn to continue.`;
276282
}
277283

284+
function pendingUserInputRequests(
285+
activities: OrchestrationThread["activities"],
286+
): ReadonlyArray<{ readonly requestId: string; readonly turnId: TurnId | null }> {
287+
const openRequests = new Map<string, TurnId | null>();
288+
const ordered = [...activities].toSorted(
289+
(left, right) =>
290+
left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id),
291+
);
292+
293+
for (const activity of ordered) {
294+
const payload =
295+
typeof activity.payload === "object" && activity.payload !== null
296+
? (activity.payload as Record<string, unknown>)
297+
: null;
298+
const requestId = typeof payload?.requestId === "string" ? payload.requestId : null;
299+
if (requestId === null) continue;
300+
301+
if (activity.kind === "user-input.requested") {
302+
openRequests.set(requestId, activity.turnId);
303+
} else if (activity.kind === "user-input.resolved") {
304+
openRequests.delete(requestId);
305+
} else if (activity.kind === "provider.user-input.respond.failed") {
306+
const detail = typeof payload?.detail === "string" ? payload.detail.toLowerCase() : "";
307+
if (
308+
detail.includes("stale pending user-input request") ||
309+
detail.includes("unknown pending user-input request") ||
310+
detail.includes("unknown pending user input request") ||
311+
detail.includes("unknown pending codex user input request")
312+
) {
313+
openRequests.delete(requestId);
314+
}
315+
}
316+
}
317+
318+
return [...openRequests].map(([requestId, turnId]) => ({ requestId, turnId }));
319+
}
320+
278321
function buildGeneratedWorktreeBranchName(raw: string): string {
279322
const normalized = raw
280323
.trim()
@@ -366,6 +409,36 @@ const make = Effect.gen(function* () {
366409
),
367410
);
368411

412+
const appendCancelledUserInputActivity = Effect.fn(
413+
"ProviderCommandReactor.appendCancelledUserInputActivity",
414+
)(function* (input: {
415+
readonly threadId: ThreadId;
416+
readonly requestId: string;
417+
readonly turnId: TurnId | null;
418+
readonly createdAt: string;
419+
}) {
420+
const commandId = yield* serverCommandId("user-input-cancelled");
421+
const eventId = yield* serverEventId();
422+
yield* orchestrationEngine.dispatch({
423+
type: "thread.activity.append",
424+
commandId,
425+
threadId: input.threadId,
426+
activity: {
427+
id: eventId,
428+
tone: "info",
429+
kind: "user-input.resolved",
430+
summary: "User input cancelled",
431+
payload: {
432+
requestId: input.requestId,
433+
cancelled: true,
434+
},
435+
turnId: input.turnId,
436+
createdAt: input.createdAt,
437+
},
438+
createdAt: input.createdAt,
439+
});
440+
});
441+
369442
const formatFailureDetail = (cause: Cause.Cause<unknown>): string => {
370443
const failReason = cause.reasons.find(Cause.isFailReason);
371444
const providerError = isProviderAdapterRequestError(failReason?.error)
@@ -1194,6 +1267,28 @@ const make = Effect.gen(function* () {
11941267

11951268
// Orchestration turn ids are not provider turn ids, so interrupt by session.
11961269
yield* providerService.interruptTurn({ threadId: event.payload.threadId });
1270+
// Some providers discard their callbacks without emitting a matching
1271+
// resolution event. Close those requests once the interrupt succeeds,
1272+
// deriving from a fresh read: the provider can append real resolutions
1273+
// while handling the interrupt. Cancellations get server-side timestamps
1274+
// so they order after the request activity even when the interrupt
1275+
// command predates it.
1276+
const postInterruptThread = yield* resolveThread(event.payload.threadId);
1277+
if (!postInterruptThread) {
1278+
return;
1279+
}
1280+
yield* Effect.forEach(
1281+
pendingUserInputRequests(postInterruptThread.activities),
1282+
({ requestId, turnId }) =>
1283+
Effect.flatMap(nowIso, (cancelledAt) =>
1284+
appendCancelledUserInputActivity({
1285+
threadId: event.payload.threadId,
1286+
requestId,
1287+
turnId,
1288+
createdAt: cancelledAt,
1289+
}),
1290+
),
1291+
);
11971292
});
11981293

11991294
const processApprovalResponseRequested = Effect.fn("processApprovalResponseRequested")(function* (

0 commit comments

Comments
 (0)