Skip to content

Commit 8949722

Browse files
t3dotggclaude
andcommitted
fix(cli): thread --wait no longer hangs when no turn matches
--wait now also ends when the session goes idle after the message, which covers failed starts, provider commands, steers, and a later turn replacing the requested one. The sent message and its reply are found by paging back, so a newer user message cannot hide them. --json now also quiets logs from the handler itself. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
1 parent b140a9b commit 8949722

2 files changed

Lines changed: 99 additions & 39 deletions

File tree

‎apps/server/src/cli/thread.test.ts‎

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -64,35 +64,49 @@ const makeSession = (
6464
});
6565

6666
describe("turnOutcome", () => {
67-
it("keeps waiting while the previous turn is still the latest turn", () => {
67+
const LATER = "2026-09-24T12:00:05.000Z";
68+
69+
it("keeps waiting before the server picks up the message", () => {
70+
const thread = makeThread({
71+
latestTurn: makeTurn(EARLIER, "completed"),
72+
session: makeSession("ready", EARLIER),
73+
});
74+
assert.equal(turnOutcome(thread, SENT_AT), undefined);
75+
});
76+
77+
it("keeps waiting while the turn starts or runs", () => {
6878
assert.equal(
69-
turnOutcome(makeThread({ latestTurn: makeTurn(EARLIER, "completed") }), SENT_AT),
79+
turnOutcome(makeThread({ session: makeSession("starting", SENT_AT) }), SENT_AT),
7080
undefined,
7181
);
72-
});
73-
74-
it("keeps waiting while the requested turn runs", () => {
7582
assert.equal(
76-
turnOutcome(makeThread({ latestTurn: makeTurn(SENT_AT, "running") }), SENT_AT),
83+
turnOutcome(
84+
makeThread({
85+
latestTurn: makeTurn(SENT_AT, "running"),
86+
session: makeSession("running", SENT_AT),
87+
}),
88+
SENT_AT,
89+
),
7790
undefined,
7891
);
7992
});
8093

8194
it("reports how the requested turn ended", () => {
95+
const session = makeSession("ready", LATER);
8296
assert.equal(
83-
turnOutcome(makeThread({ latestTurn: makeTurn(SENT_AT, "completed") }), SENT_AT),
97+
turnOutcome(makeThread({ latestTurn: makeTurn(SENT_AT, "completed"), session }), SENT_AT),
8498
"completed",
8599
);
86100
assert.equal(
87-
turnOutcome(makeThread({ latestTurn: makeTurn(SENT_AT, "interrupted") }), SENT_AT),
101+
turnOutcome(makeThread({ latestTurn: makeTurn(SENT_AT, "interrupted"), session }), SENT_AT),
88102
"interrupted",
89103
);
90104
});
91105

92106
it("reports a turn that failed to start", () => {
93107
const thread = makeThread({
94108
latestTurn: makeTurn(EARLIER, "completed"),
95-
session: makeSession("error", SENT_AT),
109+
session: makeSession("error", LATER),
96110
});
97111
assert.equal(turnOutcome(thread, SENT_AT), "error");
98112
});
@@ -102,14 +116,32 @@ describe("turnOutcome", () => {
102116
assert.equal(turnOutcome(thread, SENT_AT), undefined);
103117
});
104118

119+
it("ends when the message was handled without a turn of its own", () => {
120+
// A provider command, or a steer into a turn another client started.
121+
const thread = makeThread({
122+
latestTurn: makeTurn(EARLIER, "completed"),
123+
session: makeSession("ready", LATER),
124+
});
125+
assert.equal(turnOutcome(thread, SENT_AT), "completed");
126+
});
127+
128+
it("ends when a later turn has replaced the requested one", () => {
129+
const thread = makeThread({
130+
latestTurn: makeTurn(LATER, "completed"),
131+
session: makeSession("ready", LATER),
132+
});
133+
assert.equal(turnOutcome(thread, SENT_AT), "completed");
134+
});
135+
105136
it("stops when the turn needs an approval or an answer", () => {
106137
const running = makeTurn(SENT_AT, "running");
138+
const session = makeSession("running", SENT_AT);
107139
assert.equal(
108-
turnOutcome(makeThread({ latestTurn: running, hasPendingApprovals: true }), SENT_AT),
140+
turnOutcome(makeThread({ latestTurn: running, session, hasPendingApprovals: true }), SENT_AT),
109141
"needs-input",
110142
);
111143
assert.equal(
112-
turnOutcome(makeThread({ latestTurn: running, hasPendingUserInput: true }), SENT_AT),
144+
turnOutcome(makeThread({ latestTurn: running, session, hasPendingUserInput: true }), SENT_AT),
113145
"needs-input",
114146
);
115147
});

‎apps/server/src/cli/thread.ts‎

Lines changed: 56 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
type ClientOrchestrationCommand,
1818
type ModelSelection,
1919
type OrchestrationLatestTurnState,
20+
type OrchestrationMessage,
2021
OrchestrationMessageRole,
2122
type OrchestrationProjectShell,
2223
OrchestrationSessionStatus,
@@ -219,22 +220,31 @@ export const findModelOffers = (
219220
});
220221

221222
/**
222-
* How the turn requested at `requestedAt` ended, or undefined while it runs.
223-
* `requestedAt` is the sent message's `createdAt`. The server gives the turn
224-
* that message starts the same `latestTurn.requestedAt`. A turn that fails to
225-
* start sets the session to error with that same timestamp instead.
223+
* How the message sent at `sentAt` was handled, or undefined while it may
224+
* still run. `sentAt` is the message's server `createdAt`, which the turn it
225+
* starts copies into `latestTurn.requestedAt`. The server holds the session
226+
* at "starting" while a turn start is pending, so an idle session updated
227+
* after `sentAt` means the message was handled without a turn of its own: a
228+
* failed start, a provider command, or a steer into another client's turn.
226229
*/
227230
export const turnOutcome = (
228231
thread: OrchestrationThreadShell,
229-
requestedAt: string,
232+
sentAt: string,
230233
): Exclude<OrchestrationLatestTurnState, "running"> | "needs-input" | undefined => {
231234
if (thread.hasPendingApprovals || thread.hasPendingUserInput) return "needs-input";
235+
if (isThreadBusy(thread)) return undefined;
232236
const turn = thread.latestTurn;
233-
if (turn?.requestedAt === requestedAt) {
237+
if (turn?.requestedAt === sentAt) {
234238
return turn.state === "running" ? undefined : turn.state;
235239
}
236-
if (thread.session?.status === "error" && thread.session.updatedAt === requestedAt) {
237-
return "error";
240+
const since = Date.parse(sentAt);
241+
// A later turn only starts after this message's turn has ended.
242+
if (turn !== null && Date.parse(turn.requestedAt) > since) return "completed";
243+
const session = thread.session;
244+
if (session !== null && Date.parse(session.updatedAt) >= since) {
245+
return session.status === "error" || session.status === "interrupted"
246+
? session.status
247+
: "completed";
238248
}
239249
return undefined;
240250
};
@@ -371,13 +381,13 @@ const connectLiveServer = Effect.fn("connectThreadCliServer")(function* (
371381
: Effect.succeed(thread);
372382
}),
373383
),
374-
/** Reads the messages of the latest `turns` user turns. */
375-
threadDetail: (threadId: ThreadId, turns: number) =>
384+
/** Reads the messages of `turns` user turns, the latest ones or those before `beforeCursor`. */
385+
threadDetail: (threadId: ThreadId, turns: number, beforeCursor?: string) =>
376386
call(
377387
client.orchestration.threadSnapshot({
378388
headers,
379389
params: { threadId },
380-
payload: { turnLimit: turns },
390+
payload: { turnLimit: turns, ...(beforeCursor === undefined ? {} : { beforeCursor }) },
381391
}),
382392
).pipe(
383393
Effect.catchIf(
@@ -414,20 +424,43 @@ const pollThread = <A>(
414424
});
415425

416426
/**
417-
* Waits for the turn that `messageId` started to end and returns the agent's
427+
* Reads pages of the thread, newest first, until it finds `messageId`.
428+
* Returns that message and the messages after it, until the next user message.
429+
* Dispatch returns after the projection commits, so a sent message is there.
430+
*/
431+
const readSentTurn = (server: LiveServer, threadId: ThreadId, messageId: MessageId) =>
432+
Effect.gen(function* () {
433+
let newer: ReadonlyArray<OrchestrationMessage> = [];
434+
let beforeCursor: string | undefined;
435+
for (;;) {
436+
const { thread, page } = yield* server.threadDetail(threadId, 1, beforeCursor);
437+
const messages = [...thread.messages, ...newer];
438+
const index = messages.findIndex((message) => message.id === messageId);
439+
const sent = messages[index];
440+
if (sent !== undefined) {
441+
const after = messages.slice(index + 1);
442+
const nextUser = after.findIndex((message) => message.role === "user");
443+
return { sent, replies: nextUser === -1 ? after : after.slice(0, nextUser) };
444+
}
445+
if (page?.beforeCursor == null) {
446+
return yield* Effect.die(
447+
new Error(`Sent message ${messageId} is missing from the thread.`),
448+
);
449+
}
450+
newer = messages;
451+
beforeCursor = page.beforeCursor;
452+
}
453+
});
454+
455+
/**
456+
* Waits until the server has handled `messageId` and returns the agent's
418457
* final reply. Fails when the turn fails, is interrupted, or needs the user.
419458
*/
420459
const waitForReply = (server: LiveServer, threadId: ThreadId, messageId: MessageId) =>
421460
Effect.gen(function* () {
422461
// The server replaces the command's createdAt with its own clock, so
423-
// read the stamp back from the message. Dispatch returns after the
424-
// projection commits, so the message is already there.
425-
const sent = (yield* server.threadDetail(threadId, 1)).thread.messages.find(
426-
(message) => message.id === messageId,
427-
);
428-
if (sent === undefined) {
429-
return yield* Effect.die(new Error(`Sent message ${messageId} is missing from the thread.`));
430-
}
462+
// read the stamp back from the message.
463+
const { sent } = yield* readSentTurn(server, threadId, messageId);
431464
const ended = yield* pollThread(server, threadId, (candidate) => {
432465
const outcome = turnOutcome(candidate, sent.createdAt);
433466
return outcome === undefined ? undefined : { outcome, thread: candidate };
@@ -438,13 +471,8 @@ const waitForReply = (server: LiveServer, threadId: ThreadId, messageId: Message
438471
detail: ended.thread.session?.lastError ?? null,
439472
});
440473
}
441-
const turnId = ended.thread.latestTurn?.turnId;
442-
const { thread: detail } = yield* server.threadDetail(threadId, 1);
443-
return (
444-
detail.messages.findLast(
445-
(message) => message.role === "assistant" && message.turnId === turnId,
446-
)?.text ?? ""
447-
);
474+
const { replies } = yield* readSentTurn(server, threadId, messageId);
475+
return replies.findLast((message) => message.role === "assistant")?.text ?? "";
448476
});
449477

450478
/** Runs `run` against the live server and prints what it returns. */
@@ -467,7 +495,7 @@ const runWithLiveServer = <E, R>(
467495
EnvironmentAuth.runtimeLayer.pipe(
468496
Layer.provideMerge(FetchHttpClient.layer),
469497
Layer.provide(ServerConfig.layer(config)),
470-
Layer.provide(Layer.succeed(References.MinimumLogLevel, logLevel)),
498+
Layer.provideMerge(Layer.succeed(References.MinimumLogLevel, logLevel)),
471499
),
472500
),
473501
);

0 commit comments

Comments
 (0)