@devries-cameron20 / t3code Mirror · read-only / commits / 1535b120ec
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 23, 00:30 UTC

fix(clients): async questions keep a running thread Working (#15430)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Guillermo Casanova committed Oct 19, 2026 at 18:14 UTC 1535b120ec6af190ccf7953d8bc4b44fe3fee470
8 files changed +244 -56
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+92 -4
@@ -3179,6 +3179,48 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
3179 );
3180 assert.isNull(shell?.latestRunCompletedAt);
3181
3182 + const requestId = RuntimeRequestId.make("request:projection-shell-question");
3183 + for (const [responseCapability, blocking] of [
3184 + [{ type: "message" }, false],
3185 + [{ type: "live", providerSessionId: ProviderSessionId.make("session:question") }, true],
3186 + ] as const) {
3187 + yield* projectionStore.apply({
3188 + id: EventId.make(`event:projection-shell-question:${responseCapability.type}`),
3189 + type: "runtime-request.updated",
3190 + threadId,
3191 + nodeId: rootNodeId,
3192 + driver,
3193 + occurredAt: now,
3194 + payload: {
3195 + id: requestId,
3196 + nodeId: rootNodeId,
3197 + providerTurnId: null,
3198 + nativeRequestRef: null,
3199 + kind: "user_input",
3200 + status: "pending",
3201 + responseCapability,
3202 + createdAt: now,
3203 + resolvedAt: null,
3204 + },
3205 + });
3206 + const projection = yield* projectionStore.getThreadProjection(threadId);
3207 + const sqlShell = (yield* projectionStore.getShellSnapshot()).threads.find(
3208 + (row) => row.id === threadId,
3209 + )!;
3210 + for (const questionShell of [
3211 + sqlShell,
3212 + ProjectionStore.threadShellFromProjection(projection),
3213 + ]) {
3214 + assert.equal(questionShell.activeRunId, runId);
3215 + assert.deepEqual(questionShell.pendingRuntimeRequest, {
3216 + id: requestId,
3217 + kind: "user_input",
3218 + createdAt: now,
3219 + blocking,
3220 + });
3221 + }
3222 + }
3223 +
3224 yield* projectionStore.apply({
3225 id: EventId.make("event:projection-shell-interruptible:waiting"),
3226 type: "run.updated",
@@ -4355,7 +4397,7 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
4397 title: null,
4398 startedAt: now,
4399 completedAt: null,
4358 - updatedAt: now,
4400 + updatedAt: DateTime.add(now, { seconds: ordinal }),
4401 type: "secret_request",
4402 label: "Test credential",
4403 reason: "Test pending input",
@@ -4366,6 +4408,45 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
4408 yield* addSecret("secret:b", 3, "waiting");
4409 yield* addSecret("secret:c", 4, "completed");
4410
4411 + yield* sql`
4412 + UPDATE orchestration_v2_projection_runs
4413 + SET status = 'running', payload_json = json_set(payload_json, '$.status', 'running')
4414 + WHERE run_id = ${runId}
4415 + `;
4416 + const secretOnlyShell = (yield* projectionStore.getShellSnapshot()).threads.find(
4417 + (thread) => thread.id === threadId,
4418 + );
4419 + const secretOnlyProjection = yield* projectionStore.getThreadProjection(threadId);
4420 + for (const shell of [
4421 + secretOnlyShell,
4422 + ProjectionStore.threadShellFromProjection(secretOnlyProjection),
4423 + ]) {
4424 + assert.equal(shell?.pendingRuntimeRequest?.id, "secret:b");
4425 + assert.isTrue(shell?.pendingRuntimeRequest?.blocking);
4426 + }
4427 +
4428 + const requestId = RuntimeRequestId.make(`request:${suffix}:async`);
4429 + yield* projectionStore.apply({
4430 + id: EventId.make(`event:${suffix}:async`),
4431 + type: "runtime-request.updated",
4432 + threadId,
4433 + runId,
4434 + nodeId,
4435 + driver,
4436 + occurredAt: now,
4437 + payload: {
4438 + id: requestId,
4439 + nodeId,
4440 + providerTurnId: null,
4441 + nativeRequestRef: null,
4442 + kind: "user_input",
4443 + status: "pending",
4444 + responseCapability: { type: "message" },
4445 + createdAt: DateTime.subtract(now, { seconds: 1 }),
4446 + resolvedAt: null,
4447 + },
4448 + });
4449 +
4450 for (const status of [
4451 "preparing",
4452 "starting",
@@ -4382,9 +4463,16 @@ it.layer(layerTest)("ProjectionStoreV2", (it) => {
4463 const shell = yield* projectionStore.getShellSnapshot();
4464 const thread = shell.threads.find((candidate) => candidate.id === threadId);
4465 assert.isDefined(thread);
4385 - assert.equal(
4386 - thread?.pendingRuntimeRequest?.id ?? null,
4387 - status === "completed" || status === "rolled_back" ? null : "secret:b",
4466 + const projection = yield* projectionStore.getThreadProjection(threadId);
4467 + const memoryShell = ProjectionStore.threadShellFromProjection(projection);
4468 + const terminal = status === "completed" || status === "rolled_back";
4469 + assert.deepEqual(
4470 + [thread?.pendingRuntimeRequest?.id, memoryShell.pendingRuntimeRequest?.id],
4471 + terminal ? [requestId, requestId] : ["secret:b", "secret:b"],
4472 + );
4473 + assert.deepEqual(
4474 + [thread?.pendingRuntimeRequest?.blocking, memoryShell.pendingRuntimeRequest?.blocking],
4475 + terminal ? [false, false] : [true, true],
4476 );
4477 }
4478 }),
apps/server/src/orchestration-v2/ProjectionStore.ts
+52 -47
@@ -19,6 +19,7 @@ import type {
19 OrchestrationV2CheckpointScope,
20 OrchestrationV2ExecutionNode,
21 OrchestrationV2PlanArtifact,
22 + OrchestrationV2PendingRuntimeRequestSummary,
23 PlanId,
24 OrchestrationV2ConversationMessage,
25 OrchestrationV2DomainEvent,
@@ -1427,20 +1428,27 @@ function buildVisibleTurnItems(input: {
1428 ]);
1429 }
1430
1431 +function pendingRuntimeRequestSummary(
1432 + request: OrchestrationV2ThreadProjection["runtimeRequests"][number] | null,
1433 +): OrchestrationV2PendingRuntimeRequestSummary | null {
1434 + if (request === null) return null;
1435 + return {
1436 + id: request.id,
1437 + kind: request.kind,
1438 + createdAt: request.createdAt,
1439 + blocking: request.responseCapability.type !== "message",
1440 + };
1441 +}
1442 +
1443 function secretRequestAsPendingInput(
1444 item: OrchestrationV2TurnItem | null,
1432 -): OrchestrationV2ThreadProjection["runtimeRequests"][number] | null {
1445 +): OrchestrationV2PendingRuntimeRequestSummary | null {
1446 if (item?.type !== "secret_request" || item.nodeId === null) return null;
1447 return {
1448 id: RuntimeRequestId.make(item.id),
1436 - nodeId: item.nodeId,
1437 - providerTurnId: item.providerTurnId,
1438 - nativeRequestRef: null,
1449 kind: "user_input",
1440 - status: "pending",
1441 - responseCapability: { type: "message" },
1450 createdAt: item.startedAt ?? item.updatedAt,
1443 - resolvedAt: null,
1451 + blocking: true,
1452 };
1453 }
1454
@@ -1469,27 +1477,31 @@ export function threadShellFromProjection(
1477 .filter(isActivityRunForShell)
1478 .toSorted((left, right) => right.ordinal - left.ordinal)[0] ?? null;
1479 const liveRunIds = new Set(projection.runs.filter(isActivityRunForShell).map((run) => run.id));
1472 - const pendingRuntimeRequest =
1480 + let pendingRuntimeRequest = pendingRuntimeRequestSummary(
1481 projection.runtimeRequests
1482 .filter((request) => request.status === "pending")
1483 .toSorted(
1484 (left, right) =>
1485 DateTime.toEpochMillis(right.createdAt) - DateTime.toEpochMillis(left.createdAt),
1478 - )[0] ??
1479 - secretRequestAsPendingInput(
1480 - projection.turnItems
1481 - .filter(
1482 - (item) =>
1483 - item.type === "secret_request" &&
1484 - item.status === "waiting" &&
1485 - item.runId !== null &&
1486 - liveRunIds.has(item.runId),
1487 - )
1488 - .toSorted(
1489 - (left, right) =>
1490 - DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
1491 - )[0] ?? null,
1492 - );
1486 + )[0] ?? null,
1487 + );
1488 + if (pendingRuntimeRequest === null || pendingRuntimeRequest.blocking === false) {
1489 + pendingRuntimeRequest =
1490 + secretRequestAsPendingInput(
1491 + projection.turnItems
1492 + .filter(
1493 + (item) =>
1494 + item.type === "secret_request" &&
1495 + item.status === "waiting" &&
1496 + item.runId !== null &&
1497 + liveRunIds.has(item.runId),
1498 + )
1499 + .toSorted(
1500 + (left, right) =>
1501 + DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
1502 + )[0] ?? null,
1503 + ) ?? pendingRuntimeRequest;
1504 + }
1505 const userMessages = projection.messages
1506 .filter((message) => message.role === "user")
1507 .toSorted(
@@ -1546,14 +1558,7 @@ export function threadShellFromProjection(
1558 latestRootProviderFailure(latestRun, projection.turnItems),
1559 providerSession?.lastError ?? null,
1560 ),
1549 - pendingRuntimeRequest:
1550 - pendingRuntimeRequest === null
1551 - ? null
1552 - : {
1553 - id: pendingRuntimeRequest.id,
1554 - kind: pendingRuntimeRequest.kind,
1555 - createdAt: pendingRuntimeRequest.createdAt,
1556 - },
1561 + pendingRuntimeRequest,
1562 // Thread detail owns message bodies. Keeping them out of shell rows makes
1563 // initial hydration and streaming updates independent of transcript size.
1564 latestVisibleMessage: null,
@@ -1648,7 +1653,7 @@ type ShellThreadState = {
1653 readonly lastError: string | null;
1654 readonly lastErrorClass: OrchestrationV2ThreadShell["lastErrorClass"];
1655 readonly usageLimitResetAt: OrchestrationV2ThreadShell["usageLimitResetAt"];
1651 - readonly pendingRuntimeRequest: OrchestrationV2ThreadProjection["runtimeRequests"][number] | null;
1656 + readonly pendingRuntimeRequest: OrchestrationV2PendingRuntimeRequestSummary | null;
1657 readonly latestUserMessageAt: DateTime.Utc | null;
1658 readonly latestUserAuthoredMessageAt: DateTime.Utc | null;
1659 readonly hasActionableProposedPlan: boolean;
@@ -1801,14 +1806,7 @@ function shellFromState(input: {
1806 lastError: input.state.lastError,
1807 lastErrorClass: input.state.lastErrorClass,
1808 usageLimitResetAt: input.state.usageLimitResetAt,
1804 - pendingRuntimeRequest:
1805 - input.state.pendingRuntimeRequest === null
1806 - ? null
1807 - : {
1808 - id: input.state.pendingRuntimeRequest.id,
1809 - kind: input.state.pendingRuntimeRequest.kind,
1810 - createdAt: input.state.pendingRuntimeRequest.createdAt,
1811 - },
1809 + pendingRuntimeRequest: input.state.pendingRuntimeRequest,
1810 latestVisibleMessage: null,
1811 latestUserMessageAt: input.state.latestUserMessageAt,
1812 latestUserAuthoredMessageAt: input.state.latestUserAuthoredMessageAt,
@@ -5791,14 +5789,21 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
5789 pendingTurnItemsByThreadId,
5790 } = input;
5791 const thread = yield* decodeThreadPayload(row.payload_json);
5794 - const pendingRuntimeRequest =
5792 + let pendingRuntimeRequest =
5793 row.pending_request_payload_json !== null
5796 - ? yield* decodeRuntimeRequestPayload(row.pending_request_payload_json)
5797 - : row.pending_secret_request_payload_json !== null
5798 - ? secretRequestAsPendingInput(
5799 - yield* decodeTurnItemPayload(row.pending_secret_request_payload_json),
5800 - )
5801 - : null;
5794 + ? pendingRuntimeRequestSummary(
5795 + yield* decodeRuntimeRequestPayload(row.pending_request_payload_json),
5796 + )
5797 + : null;
5798 + if (
5799 + (pendingRuntimeRequest === null || pendingRuntimeRequest.blocking === false) &&
5800 + row.pending_secret_request_payload_json !== null
5801 + ) {
5802 + pendingRuntimeRequest =
5803 + secretRequestAsPendingInput(
5804 + yield* decodeTurnItemPayload(row.pending_secret_request_payload_json),
5805 + ) ?? pendingRuntimeRequest;
5806 + }
5807 let terminalFailureItem =
5808 row.terminal_failure_payload_json === null
5809 ? null
packages/client-runtime/src/state/entities.test.ts
+52
@@ -26,7 +26,9 @@ import {
26 } from "./models.ts";
27 import { v2Projection, v2ThreadShell } from "./orchestrationV2TestFixtures.ts";
28 import { deriveLatestThreadRun, deriveThreadRuntime } from "./threadExecution.ts";
29 +import { isThreadWorking } from "./threadInbox.ts";
30 import { derivePendingThreadRequests } from "./threadRequests.ts";
31 +import { canSnooze, effectiveSnoozed } from "./threadSettled.ts";
32
33 const environmentId = EnvironmentId.make("environment-v2");
34
@@ -111,6 +113,56 @@ describe("V2 client presentation", () => {
113 });
114 });
115
116 + it("keeps async questions in Working until the run completes", () => {
117 + const runId = RunId.make("run-async-question");
118 + const running = {
119 + ...v2ThreadShell,
120 + snoozedAt: DateTime.makeUnsafe("2026-06-19T23:59:00.000Z"),
121 + snoozedUntil: DateTime.makeUnsafe("2026-06-20T01:00:00.000Z"),
122 + latestRunId: runId,
123 + activeRunId: runId,
124 + status: "running" as const,
125 + pendingRuntimeRequest: {
126 + id: RuntimeRequestId.make("request-async-question"),
127 + kind: "user_input" as const,
128 + createdAt: v2ThreadShell.updatedAt,
129 + blocking: false,
130 + },
131 + };
132 + const active = presentThreadShell(environmentId, running);
133 + expect(active.hasPendingUserInput).toBe(false);
134 + expect(isThreadWorking(active)).toBe(true);
135 + expect(canSnooze(active, { now: "2026-06-20T00:05:00.000Z" })).toBe(false);
136 +
137 + const completed = presentThreadShell(environmentId, {
138 + ...running,
139 + activeRunId: null,
140 + status: "completed",
141 + });
142 + expect(completed.hasPendingUserInput).toBe(true);
143 + expect(isThreadWorking(completed)).toBe(false);
144 + expect(effectiveSnoozed(active, { now: "2026-06-20T00:05:00.000Z" })).toBe(false);
145 + });
146 +
147 + it("keeps blocking and legacy questions out of Working", () => {
148 + for (const capability of [{ blocking: true }, {}]) {
149 + const shell = presentThreadShell(environmentId, {
150 + ...v2ThreadShell,
151 + latestRunId: RunId.make("run-blocking-question"),
152 + activeRunId: RunId.make("run-blocking-question"),
153 + status: "running",
154 + pendingRuntimeRequest: {
155 + id: RuntimeRequestId.make("request-blocking-question"),
156 + kind: "user_input",
157 + createdAt: v2ThreadShell.updatedAt,
158 + ...capability,
159 + },
160 + });
161 + expect(shell.hasPendingUserInput).toBe(true);
162 + expect(isThreadWorking(shell)).toBe(false);
163 + }
164 + });
165 +
166 it("preserves shell run timestamps for sidebar activity clocks", () => {
167 const runId = RunId.make("run-working-clock");
168 const requestedAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
packages/client-runtime/src/state/models.ts
+10 -2
@@ -220,6 +220,12 @@ export function presentThreadShell(
220 : nullableIso(thread.latestRunCompletedAt),
221 assistantMessageId: null,
222 } satisfies ThreadRunSummary);
223 + const runtime = shellRuntime(thread);
224 + // Waiting runs have ended their provider turn and are only draining effects.
225 + const runtimeIsWorking =
226 + runtime?.status === "preparing" ||
227 + runtime?.status === "starting" ||
228 + runtime?.status === "running";
229 return {
230 environmentId,
231 id: thread.id,
@@ -241,7 +247,7 @@ export function presentThreadShell(
247 forkedFrom: thread.forkedFrom,
248 activeProviderThreadId: thread.activeProviderThreadId,
249 latestRun,
244 - runtime: shellRuntime(thread),
250 + runtime,
251 latestUserMessageAt: nullableIso(thread.latestUserMessageAt),
252 ...(thread.latestUserAuthoredMessageAt === undefined
253 ? {}
@@ -250,7 +256,9 @@ export function presentThreadShell(
256 thread.pendingRuntimeRequest !== null &&
257 thread.pendingRuntimeRequest.kind !== "user_input" &&
258 thread.pendingRuntimeRequest.kind !== "auth_refresh",
253 - hasPendingUserInput: thread.pendingRuntimeRequest?.kind === "user_input",
259 + hasPendingUserInput:
260 + thread.pendingRuntimeRequest?.kind === "user_input" &&
261 + (thread.pendingRuntimeRequest.blocking !== false || !runtimeIsWorking),
262 pendingSubagentRequest,
263 hasActionableProposedPlan: thread.hasActionableProposedPlan,
264 pendingBackgroundTasks: thread.pendingBackgroundTasks ?? [],
packages/client-runtime/src/state/threadSettled.ts
+6 -1
@@ -1,7 +1,7 @@
1 // @effect-diagnostics globalDate:off -- UI snooze presets use local calendar boundaries and Intl labels.
2 import * as DateTime from "effect/DateTime";
3
4 -import type { PendingSubagentRequest } from "./models.ts";
4 +import type { EnvironmentThreadShell, PendingSubagentRequest } from "./models.ts";
5
6 interface SettlementRunLike {
7 readonly turnId?: unknown;
@@ -71,6 +71,7 @@ export function hasQueuedTurnStart(
71 }
72
73 export interface ThreadSnoozeShell extends QueuedThreadShell {
74 + readonly source?: Pick<EnvironmentThreadShell["source"], "pendingRuntimeRequest">;
75 readonly snoozedUntil?: string | null;
76 readonly snoozedAt?: string | null;
77 readonly hasPendingApprovals: boolean;
@@ -80,6 +81,7 @@ export interface ThreadSnoozeShell extends QueuedThreadShell {
81
82 export function threadRaisedHandWhileSnoozed(shell: ThreadSnoozeShell): boolean {
83 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return true;
84 + if (shell.source?.pendingRuntimeRequest != null) return true;
85 if (shell.pendingSubagentRequest != null) return true;
86 const latestRun = shell.latestRun ?? shell.latestTurn ?? null;
87 const failedAt = failureEdgeAt(shell);
@@ -124,10 +126,13 @@ export function canSnooze(
126 | "latestRun"
127 | "session"
128 | "runtime"
129 + | "source"
130 >,
131 options: { readonly now: string },
132 ): boolean {
133 if (shell.hasPendingApprovals || shell.hasPendingUserInput) return false;
134 + // The server rejects snoozing even for nonblocking questions.
135 + if (shell.source?.pendingRuntimeRequest != null) return false;
136 if (shell.pendingSubagentRequest != null) return false;
137 if (hasQueuedTurnStart(shell, options)) return false;
138 return true;
packages/contracts/src/orchestrationV2.ts
+2
@@ -1782,6 +1782,8 @@ export const OrchestrationV2PendingRuntimeRequestSummary = Schema.Struct({
1782 id: RuntimeRequestId,
1783 kind: OrchestrationV2RuntimeRequest.fields.kind,
1784 createdAt: Schema.DateTimeUtc,
1785 + /** False for async questions the run keeps working past. Absent from older servers. */
1786 + blocking: Schema.optional(Schema.Boolean),
1787 });
1788 export type OrchestrationV2PendingRuntimeRequestSummary =
1789 typeof OrchestrationV2PendingRuntimeRequestSummary.Type;
packages/shared/src/agentAwareness.test.ts
+22
@@ -122,6 +122,28 @@ describe("projectThreadAwarenessV2", () => {
122 ).toMatchObject({ phase: "waiting_for_input", headline: "Waiting for input" });
123 });
124
125 + it("reports an async question as input only after the working run completes", () => {
126 + const input = {
127 + environmentId: "env-1" as EnvironmentId,
128 + project,
129 + thread: v2Thread({
130 + pendingRuntimeRequest: {
131 + id: RuntimeRequestId.make("request-async"),
132 + kind: "user_input",
133 + createdAt: updatedAt,
134 + blocking: false,
135 + },
136 + }),
137 + };
138 + expect(projectThreadAwarenessV2(input)).toMatchObject({
139 + phase: "running",
140 + headline: "Agent is working",
141 + });
142 + expect(
143 + projectThreadAwarenessV2({ ...input, thread: { ...input.thread, status: "completed" } }),
144 + ).toMatchObject({ phase: "waiting_for_input", headline: "Waiting for input" });
145 + });
146 +
147 it("does not present authentication refreshes as user approvals", () => {
148 expect(
149 projectThreadAwarenessV2({
packages/shared/src/agentAwareness.ts
+8 -2
@@ -86,16 +86,22 @@ export function projectThreadAwarenessV2(
86 function resolveThreadAwarenessPhaseV2(
87 thread: ProjectThreadAwarenessV2Input["thread"],
88 ): AgentAwarenessPhase | null {
89 - if (thread.pendingRuntimeRequest?.kind === "user_input") {
89 + const runStatus = thread.activityRunStatus ?? thread.status;
90 + if (
91 + thread.pendingRuntimeRequest?.kind === "user_input" &&
92 + (thread.pendingRuntimeRequest.blocking !== false ||
93 + !(runStatus === "preparing" || runStatus === "starting" || runStatus === "running"))
94 + ) {
95 return "waiting_for_input";
96 }
97 if (
98 thread.pendingRuntimeRequest !== null &&
99 + thread.pendingRuntimeRequest.kind !== "user_input" &&
100 thread.pendingRuntimeRequest.kind !== "auth_refresh"
101 ) {
102 return "waiting_for_approval";
103 }
98 - switch (thread.activityRunStatus ?? thread.status) {
104 + switch (runStatus) {
105 case "preparing":
106 case "starting":
107 return "starting";