TypeScript
fix(server): an open question stays in the thread window, so its answer panel shows (#22291)
AdEx-Partners-DE08a40a9d6e57
diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.tsindex 2f7c9f00b4e..9bd3566e559 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts@@ -2885,6 +2885,176 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {}),);+ it.effect("keeps an open question's row in the window after the run kept working", () =>+ Effect.gen(function* () {+ const projectionStore = yield* ProjectionStore.ProjectionStoreV2;+ const sql = yield* SqlClient.SqlClient;+ const now = yield* DateTime.now;+ const nowIso = DateTime.formatIso(now);+ const threadId = ThreadId.make("thread:open-question-window");+ yield* projectionStore.apply({+ id: EventId.make("event:open-question-window:thread"),+ type: "thread.created",+ threadId,+ occurredAt: now,+ payload: {+ createdBy: "user",+ creationSource: "web",+ id: threadId,+ projectId: ProjectId.make("project:open-question-window"),+ title: "Open question window",+ providerInstanceId,+ modelSelection,+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ activeProviderThreadId: null,+ lineage: { parentThreadId: null, relationshipToParent: null, rootThreadId: threadId },+ forkedFrom: null,+ createdAt: now,+ updatedAt: now,+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ lastVisitedAt: null,+ deletedAt: null,+ },+ });+ for (let ordinal = 10; ordinal <= 300; ordinal += 1) {+ const id = `turn-item:open-question-window:${ordinal}`;+ yield* sql`+ INSERT INTO orchestration_v2_projection_turn_items (+ turn_item_id, thread_id, run_id, node_id, provider_thread_id, provider_turn_id,+ parent_item_id, ordinal, type, status, updated_at, payload_json+ ) VALUES (+ ${id}, ${threadId}, NULL, NULL, NULL, NULL, NULL, ${ordinal},+ 'command_execution', 'completed', ${nowIso},+ ${encodeUnknownJsonString({+ id,+ threadId,+ runId: null,+ nodeId: null,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal,+ status: "completed",+ title: `command ${ordinal}`,+ input: `echo ${ordinal}`,+ output: "ok",+ exitCode: 0,+ startedAt: nowIso,+ completedAt: nowIso,+ updatedAt: nowIso,+ type: "command_execution",+ })}+ )+ `;+ }+ const requestId = RuntimeRequestId.make("request:open-question-window");+ const nodeId = NodeId.make("node:open-question-window");+ const itemId = TurnItemId.make("turn-item:open-question-window:question");+ yield* projectionStore.apply({+ id: EventId.make("event:open-question-window:node"),+ type: "node.updated",+ threadId,+ nodeId,+ occurredAt: now,+ payload: {+ id: nodeId,+ threadId,+ runId: null,+ parentNodeId: null,+ rootNodeId: nodeId,+ kind: "user_input_request",+ status: "waiting",+ countsForRun: false,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ runtimeRequestId: requestId,+ checkpointScopeId: null,+ startedAt: now,+ completedAt: null,+ },+ });+ const request = {+ id: requestId,+ nodeId,+ providerTurnId: null,+ nativeRequestRef: null,+ kind: "user_input" as const,+ status: "pending" as const,+ responseCapability: { type: "message" as const },+ createdAt: now,+ resolvedAt: null,+ };+ yield* projectionStore.apply({+ id: EventId.make("event:open-question-window:request"),+ type: "runtime-request.updated",+ threadId,+ nodeId,+ occurredAt: now,+ payload: request,+ });+ yield* projectionStore.apply({+ id: EventId.make("event:open-question-window:item"),+ type: "turn-item.updated",+ threadId,+ nodeId,+ occurredAt: now,+ payload: {+ id: itemId,+ type: "user_input_request",+ threadId,+ runId: null,+ nodeId,+ providerThreadId: null,+ providerTurnId: null,+ nativeItemRef: null,+ parentItemId: null,+ ordinal: 5,+ status: "waiting",+ title: null,+ startedAt: now,+ completedAt: null,+ updatedAt: now,+ requestId,+ responseMode: "message",+ questions: [{ id: "choice", header: "Choice", question: "Continue?", options: [] }],+ },+ });++ const questionRows = (snapshot: {+ readonly projection: { readonly turnItems: ReadonlyArray<{ readonly id: string }> };+ }) => snapshot.projection.turnItems.filter((item) => item.id === itemId).length;+ const open = yield* projectionStore.getThreadSnapshotWindow(threadId, { rowLimit: 76 });+ assert.strictEqual(questionRows(open), 1);+ const bounded = buildBoundedThreadProjection({+ policy: { ...THREAD_HISTORY_PAGE_POLICY, maxUserTurns: undefined, maxItems: 50 },+ projection: open.projection,+ snapshotSequence: open.snapshotSequence,+ });+ assert.strictEqual(questionRows(bounded), 1);+ assert.isFalse(+ bounded.projection.visibleTurnItems.some((row) => row.sourceItemId === itemId),+ );++ yield* projectionStore.apply({+ id: EventId.make("event:open-question-window:resolved"),+ type: "runtime-request.updated",+ threadId,+ nodeId,+ occurredAt: now,+ payload: { ...request, status: "resolved", resolvedAt: now },+ });+ const answered = yield* projectionStore.getThreadSnapshotWindow(threadId, { rowLimit: 76 });+ assert.strictEqual(questionRows(answered), 0);+ }),+ );+it.effect("scopes actionable provider state to the requested bounded thread", () =>Effect.gen(function* () {const projectionStore = yield* ProjectionStore.ProjectionStoreV2;diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.tsindex e2481acda8a..95c0f7a4bae 100644--- a/apps/server/src/orchestration-v2/ProjectionStore.ts+++ b/apps/server/src/orchestration-v2/ProjectionStore.ts@@ -2967,6 +2967,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =)AND request.type = 'run_interrupt_request'UNION+ -- An open question or approval stays in the window: clients+ -- build the answer panel from its row, and a run that kept+ -- working pushes the row out of the newest turns.+ SELECT question.rowid AS item_rowid, question.ordinal, question.turn_item_id+ FROM orchestration_v2_projection_runtime_requests AS pending+ JOIN orchestration_v2_projection_turn_items AS question+ ON question.node_id = pending.node_id+ WHERE pending.thread_id = ${threadId}+ AND pending.status = 'pending'+ AND question.thread_id = ${threadId}+ AND question.type IN ('user_input_request', 'approval_request')+ AND ${window.rowLimit} > 0+ AND ${window.anchorItemId ?? null} IS NULL+ AND ${window.requiredRunId ?? null} IS NULL+ UNIONSELECT latest.item_rowid, latest.ordinal, latest.turn_item_idFROM (SELECT rowid AS item_rowid, ordinal, turn_item_iddiff --git a/apps/server/src/orchestration-v2/threadHistoryPaging.ts b/apps/server/src/orchestration-v2/threadHistoryPaging.tsindex 7f1ea4db95d..03d056531a7 100644--- a/apps/server/src/orchestration-v2/threadHistoryPaging.ts+++ b/apps/server/src/orchestration-v2/threadHistoryPaging.ts@@ -501,6 +501,29 @@ function isLocalProjectedRow(return row.visibility === "local" || String(row.sourceThreadId) === String(projection.thread.id);}+function pendingRequestIdsOf(+ projection: Pick<OrchestrationV2ThreadProjection, "runtimeRequests">,+): ReadonlySet<string> {+ return new Set(+ projection.runtimeRequests+ .filter((request) => request.status === "pending")+ .map((request) => String(request.id)),+ );+}++// Clients build the answer panel of an open question or approval from its row,+// and a run that kept working pushes that row out of the newest turns.+function isRetainedDependency(+ item: OrchestrationV2TurnItem,+ pendingRequestIds: ReadonlySet<string>,+): boolean {+ return (+ item.type === "run_interrupt_request" ||+ ((item.type === "user_input_request" || item.type === "approval_request") &&+ pendingRequestIds.has(String(item.requestId)))+ );+}+/** Retain small requests outside the visible window; later result pages still need them for attempt/run reducers. */function retainedInterruptRequestTurnItems(projection: OrchestrationV2ThreadProjection,@@ -513,9 +536,10 @@ function retainedInterruptRequestTurnItems(}}+ const pendingRequestIds = pendingRequestIdsOf(projection);const retained: OrchestrationV2TurnItem[] = [];for (const item of projection.turnItems) {- if (item.type !== "run_interrupt_request") {+ if (!isRetainedDependency(item, pendingRequestIds)) {continue;}if (visibleLocalIds.has(String(item.id))) {@@ -635,8 +659,9 @@ export function buildBoundedThreadProjection(input: {const dependencyReserve = (() => {let reserve = 0;+ const pendingRequestIds = pendingRequestIdsOf(controlProjection);for (const item of controlProjection.turnItems) {- if (item.type === "run_interrupt_request") {+ if (isRetainedDependency(item, pendingRequestIds)) {reserve += bytesOfJson(item);}}