TypeScript
fix(server): allow settling threads with unanswered async questions (#10400)
Theo Browne7ac93e300ee1
diff --git a/apps/server/src/orchestration/decider.settled.test.ts b/apps/server/src/orchestration/decider.settled.test.tsindex ebca8434c34..abc5cff37e3 100644--- a/apps/server/src/orchestration/decider.settled.test.ts+++ b/apps/server/src/orchestration/decider.settled.test.ts@@ -322,6 +322,112 @@ it.layer(NodeServices.layer)("settled thread decider", (it) => {}),);+ it.effect("manual settlement dismisses async questions without starting a turn", () =>+ Effect.gen(function* () {+ const question = (requestId: string): OrchestrationThread["activities"][number] => ({+ id: EventId.make(requestId),+ kind: "user-input.requested",+ summary: "Question",+ tone: "approval",+ turnId: null,+ createdAt: "1969-12-31T00:00:00.000Z",+ payload: { requestId, responseMode: "message" },+ });+ const readModel = makeReadModel(null, null, makeSession("ready"), [+ question("first"),+ question("second"),+ question("answered"),+ {+ ...question("answered"),+ id: EventId.make("answer"),+ createdAt: "1969-12-31T01:00:00.000Z",+ kind: "user-input.resolved",+ },+ ]);+ const command = {+ type: "thread.settle" as const,+ commandId: CommandId.make("settle-async"),+ threadId: ThreadId.make("thread-1"),+ };+ const result = yield* decideOrchestrationCommand({ command, readModel });+ const events = Array.isArray(result) ? result : [result];+ expect(events.map((event) => event.type)).toEqual([+ "thread.settled",+ "thread.activity-appended",+ "thread.activity-appended",+ ]);+ expect(events.slice(1).map((event) => event.payload)).toEqual(+ ["first", "second"].map((requestId) => ({+ threadId: command.threadId,+ activity: expect.objectContaining({+ kind: "user-input.resolved",+ summary: "User input dismissed",+ payload: { requestId, responseMode: "message" },+ }),+ })),+ );+ let projected = readModel;+ for (const [index, event] of events.entries()) {+ projected = yield* projectEvent(projected, { ...event, sequence: index + 1 });+ }+ expect(projected.threads[0]?.settledOverride).toBe("settled");+ expect(projected.threads[0]?.messages).toEqual([]);+ const repeated = yield* decideOrchestrationCommand({ command, readModel: projected });+ expect(repeated).toMatchObject({ type: "thread.settled" });+ }),+ );++ it.effect("async questions do not bypass automatic settlement or other blockers", () =>+ Effect.gen(function* () {+ const question: OrchestrationThread["activities"][number] = {+ id: EventId.make("async-question"),+ kind: "user-input.requested",+ summary: "Question",+ tone: "approval",+ turnId: null,+ createdAt: NOW,+ payload: { requestId: "async-question", responseMode: "message" },+ };+ for (const blocker of ["auto", "running", "starting", "approval", "native"] as const) {+ const error = yield* decideOrchestrationCommand({+ command:+ blocker === "auto"+ ? {+ type: "thread.auto-settle",+ commandId: CommandId.make(`settle-${blocker}`),+ threadId: ThreadId.make("thread-1"),+ snapshotSequence: 0,+ settledAt: NOW,+ }+ : {+ type: "thread.settle",+ commandId: CommandId.make(`settle-${blocker}`),+ threadId: ThreadId.make("thread-1"),+ },+ readModel: makeReadModel(+ null,+ null,+ makeSession(blocker === "running" || blocker === "starting" ? blocker : "ready"),+ [+ question,+ ...(blocker === "approval" || blocker === "native"+ ? [+ {+ ...question,+ id: EventId.make("blocking-request"),+ kind: blocker === "approval" ? "approval.requested" : "user-input.requested",+ payload: { requestId: "blocking-request" },+ },+ ]+ : []),+ ],+ ),+ }).pipe(Effect.flip);+ expect(error).toMatchObject({ _tag: "OrchestrationThreadSettleBlockedError" });+ }+ }),+ );+it.effect("clears an open request when its respond failure marks it stale", () =>Effect.gen(function* () {const activity = (diff --git a/apps/server/src/orchestration/decider.ts b/apps/server/src/orchestration/decider.tsindex 9dc55e1194c..9762d9bfd6d 100644--- a/apps/server/src/orchestration/decider.ts+++ b/apps/server/src/orchestration/decider.ts@@ -68,10 +68,8 @@ function isStaleRequestFailureDetail(payload: Record<string, unknown> | null): b// Scans the read model's activities, which the projector caps at the most// recent 500 plus pending async questions. Async questions remain actionable// while the agent works, so they must not expire with the activity window.-function hasOpenBlockingRequest(thread: {- readonly activities: ReadonlyArray<{ readonly kind: string; readonly payload: unknown }>;-}): boolean {- const openRequestIds = new Set<string>();+function openRequests(thread: Pick<OrchestrationThread, "activities">) {+ const requests = new Map<string, OrchestrationThreadActivity>();for (const activity of thread.activities) {const payload =typeof activity.payload === "object" && activity.payload !== null@@ -80,18 +78,18 @@ function hasOpenBlockingRequest(thread: {const requestId = typeof payload?.requestId === "string" ? payload.requestId : null;if (requestId === null) continue;if (activity.kind === "approval.requested" || activity.kind === "user-input.requested") {- openRequestIds.add(requestId);+ requests.set(requestId, activity);} else if (activity.kind === "approval.resolved" || activity.kind === "user-input.resolved") {- openRequestIds.delete(requestId);+ requests.delete(requestId);} else if ((activity.kind === "provider.approval.respond.failed" ||activity.kind === "provider.user-input.respond.failed") &&isStaleRequestFailureDetail(payload)) {- openRequestIds.delete(requestId);+ requests.delete(requestId);}}- return openRequestIds.size > 0;+ return requests;}/** Apply the shared shell-level rule to the detailed command read model. */@@ -456,10 +454,18 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"if (thread.session?.status === "starting" || thread.session?.status === "running") {return yield* new OrchestrationThreadSettleBlockedError({ threadId: command.threadId });}- // Pending approval / user-input requests are blocked-on-you work: a- // raced or stale client must not park them behind a settled override- // that would surface only after the request resolves.- if (hasOpenBlockingRequest(thread)) {+ const pendingRequests = openRequests(thread);+ // Manual settlement dismisses async questions without answering them.+ // Native callbacks and approvals still need a response or interruption.+ if (+ Array.from(pendingRequests.values()).some(+ (activity) =>+ command.type === "thread.auto-settle" ||+ activity.kind !== "user-input.requested" ||+ !Predicate.isObject(activity.payload) ||+ activity.payload.responseMode !== "message",+ )+ ) {return yield* new OrchestrationThreadSettleBlockedError({ threadId: command.threadId });}const occurredAt = yield* nowIso;@@ -495,6 +501,29 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"// Settling is "I'm done with this": clear states that would keep the// row pinned or snoozed instead of showing the new settled state.const companionEvents: Array<Omit<OrchestrationEvent, "sequence">> = [];+ for (const [requestId, request] of pendingRequests) {+ companionEvents.push({+ ...(yield* withEventBase({+ aggregateKind: "thread",+ aggregateId: command.threadId,+ occurredAt,+ commandId: command.commandId,+ })),+ type: "thread.activity-appended",+ payload: {+ threadId: command.threadId,+ activity: {+ id: EventId.make(`settle:${command.commandId}:${requestId}`),+ kind: "user-input.resolved",+ summary: "User input dismissed",+ tone: "info",+ turnId: request.turnId,+ createdAt: occurredAt,+ payload: { requestId, responseMode: "message" },+ },+ },+ });+ }if (thread.pinnedAt != null) {companionEvents.push({...(yield* withEventBase({@@ -581,7 +610,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"// user-input request is the agent waiting on the user, and hiding it// defeats the request. (A running session IS snoozable — snooze only// affects visibility, never the agent.)- if (hasOpenBlockingRequest(thread)) {+ if (openRequests(thread).size > 0) {return yield* Effect.fail(new OrchestrationCommandInvariantError({commandType: command.type,@@ -1453,7 +1482,7 @@ export const decideOrchestrationCommand = Effect.fn("decideOrchestrationCommand"thread.messages.length > 0 ||thread.latestTurn !== null ||thread.session !== null ||- hasOpenBlockingRequest(thread)+ openRequests(thread).size > 0) {return yield* new OrchestrationCommandInvariantError({commandType: command.type,diff --git a/docs/user/thread-sidebar.md b/docs/user/thread-sidebar.mdindex 4286ed654d8..f20d5acbb17 100644--- a/docs/user/thread-sidebar.md+++ b/docs/user/thread-sidebar.md@@ -63,6 +63,8 @@ their default order until the server is updated.Choose **Settle thread** from its menu to move finished work out of the active listwithout deleting the conversation. **Un-settle thread** restores it to active workand prevents automatic settlement until new activity resumes the usual rules.+Manually settling an idle thread dismisses unanswered async questions without+sending an answer or restarting the agent.By default, environments settle inactive threads after three days and settlethreads whose pull request merged. A closed pull request can also settle an idle