Skip to content

Commit b3727bc

Browse files
committed
fix(mcp): 保持跨版本线程等待的兼容性
- 外部客户端显式启用输入感知等待,并保留线程调用者和跨环境转发的默认行为。 - CLI 兼容旧服务器的待回答查询与完成竞态,避免误报失败或无限等待。 - 区分普通问题、密钥输入卡和审批的操作指引,按实测更新上下文预算。 - 变更范围检查通过:225 项测试及 36 个受影响包的类型检查。
1 parent 81b7646 commit b3727bc

10 files changed

Lines changed: 173 additions & 8 deletions

File tree

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

Lines changed: 27 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@ import * as Effect from "effect/Effect";
1010
import * as FileSystem from "effect/FileSystem";
1111
import * as Layer from "effect/Layer";
1212
import * as Path from "effect/Path";
13+
import * as Schema from "effect/Schema";
1314
import * as TestConsole from "effect/testing/TestConsole";
1415
import { Command } from "effect/cli";
1516
import { vi } from "vite-plus/test";
@@ -137,10 +138,14 @@ it.effect(
137138
/** Answers each tool call with the next scripted response for that tool. */
138139
const scriptedTools = (script: Record<string, Array<unknown>>) => {
139140
const calls: Array<{ readonly tool: string; readonly args: unknown }> = [];
140-
const call = ((tool: string, args: unknown) => {
141+
const call = ((tool: string, args: unknown, schema: Schema.Decoder<unknown>) => {
141142
calls.push({ tool, args });
142143
const next = script[tool]?.shift();
143-
return next === undefined ? Effect.die(`unscripted ${tool} call`) : Effect.succeed(next);
144+
return next === undefined
145+
? Effect.die(`unscripted ${tool} call`)
146+
: tool === "t3_thread_wait"
147+
? Schema.decodeEffect(schema)(next).pipe(Effect.orDie)
148+
: Effect.succeed(next);
144149
}) as ThreadTools["call"];
145150
return { tools: { call } satisfies ThreadTools, calls };
146151
};
@@ -175,8 +180,8 @@ it.effect("--wait follows the sent run to its continuation's terminal status", (
175180
assert.deepStrictEqual(
176181
calls.filter((entry) => entry.tool === "t3_thread_wait").map((entry) => entry.args),
177182
[
178-
{ threadId, runId, timeoutMs: 15_000 },
179-
{ threadId, runId, timeoutMs: 15_000 },
183+
{ threadId, runId, timeoutMs: 15_000, returnOnInput: true },
184+
{ threadId, runId, timeoutMs: 15_000, returnOnInput: true },
180185
],
181186
);
182187
}),
@@ -236,6 +241,24 @@ it.effect("--wait reports its run's result when a later run is the one waiting",
236241
}),
237242
);
238243

244+
it.effect.each(["running", "completed"] as const)(
245+
"--wait reads legacy pending requests and rechecks its %s run",
246+
(status) =>
247+
Effect.gen(function* () {
248+
const { tools } = scriptedTools({
249+
t3_thread_wait: [
250+
{ threadId, runId, status: "running", timedOut: true },
251+
{ threadId, runId, status, timedOut: status === "running" },
252+
],
253+
t3_thread_read: [{ thread: { pendingRequestCount: 1 } }],
254+
});
255+
assert.deepStrictEqual(
256+
yield* waitForRun(tools, threadId, runId),
257+
status === "running" ? { type: "needs_input" } : { type: "ended", runId, status },
258+
);
259+
}),
260+
);
261+
239262
/** Serves t3_thread_read pages the way the server does: positions count every item. */
240263
const timelineTools = (types: ReadonlyArray<string>) => {
241264
const items = types.map((type, position) => ({ position, itemId: `item-${position}`, type }));

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

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -435,6 +435,12 @@ type WaitOutcome =
435435
}
436436
| { readonly type: "needs_input" };
437437

438+
// Keep the missing flag observable: older servers need the thread-wide request fallback.
439+
const CliThreadWaitResult = Schema.Struct({
440+
...OrchestratorMcpThreadWaitResult.fields,
441+
hasPendingQuestion: Schema.optional(Schema.Boolean),
442+
});
443+
438444
/**
439445
* Waits for this exact run, following a restart to its continuation, so a
440446
* message another client sends meanwhile cannot stand in for its result.
@@ -445,15 +451,33 @@ export const waitForRun = Effect.fn("cli.thread.waitForRun")(function* (
445451
runId: RunId,
446452
) {
447453
const waitSlice = (timeoutMs: number) =>
448-
tools.call("t3_thread_wait", { threadId, runId, timeoutMs }, OrchestratorMcpThreadWaitResult);
449-
const ended = (waited: OrchestratorMcpThreadWaitResult) =>
454+
tools.call(
455+
"t3_thread_wait",
456+
{ threadId, runId, timeoutMs, returnOnInput: true },
457+
CliThreadWaitResult,
458+
);
459+
const ended = (waited: typeof CliThreadWaitResult.Type) =>
450460
({ type: "ended", runId: waited.runId, status: waited.status }) satisfies WaitOutcome;
451461
while (true) {
452462
const waited = yield* waitSlice(WAIT_SLICE_MS);
453463
if (waited.hasPendingQuestion || waited.pendingApproval !== null) {
454464
return { type: "needs_input" } satisfies WaitOutcome;
455465
}
456466
if (!waited.timedOut) return ended(waited);
467+
if (waited.hasPendingQuestion === undefined) {
468+
const { thread } = yield* tools.call(
469+
"t3_thread_read",
470+
{ threadId, limit: 1, runLimit: 1 },
471+
OrchestratorMcpThreadReadResult,
472+
);
473+
if (thread.pendingRequestCount > 0) {
474+
// A later run can own the request if our run finished since the timeout.
475+
const recheck = yield* waitSlice(1);
476+
return recheck.hasPendingQuestion || recheck.pendingApproval !== null || recheck.timedOut
477+
? ({ type: "needs_input" } satisfies WaitOutcome)
478+
: ended(recheck);
479+
}
480+
}
457481
}
458482
});
459483

‎apps/server/src/mcp/McpInvocationContext.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -133,6 +133,12 @@ export interface McpInvocationScope {
133133
readonly linkedEnvironments?: boolean;
134134
}
135135

136+
/** External clients must opt in: older CLIs treat every non-timeout as a terminal run. */
137+
export const threadWaitReturnsOnInput = (
138+
scope: McpInvocationScope,
139+
returnOnInput: boolean | undefined,
140+
): boolean => returnOnInput ?? (scope.thread !== undefined || scope.client?.linked === true);
141+
136142
/**
137143
* T3 Code renders `t3-thread://` links as thread chips. Other MCP clients cannot open them, so
138144
* they get the hosted link Copy thread copies, which opens the thread in either app or a browser.

‎apps/server/src/mcp/OrchestratorMcpService.test.ts‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,8 @@ import * as Queue from "effect/Queue";
3737
import * as Ref from "effect/Ref";
3838
import * as Schema from "effect/Schema";
3939
import * as Stream from "effect/Stream";
40+
import * as TestClock from "effect/testing/TestClock";
41+
import * as ProviderSessionManager from "../orchestration-v2/ProviderSessionManager.ts";
4042

4143
import { CodexProviderCapabilitiesV2 } from "../orchestration-v2/Adapters/CodexAdapterV2.ts";
4244
import * as CommandReceiptStore from "../orchestration-v2/CommandReceiptStore.ts";
@@ -3655,6 +3657,94 @@ describe("OrchestratorMcpService thread lookup", () => {
36553657
}),
36563658
);
36573659

3660+
it.effect.each([
3661+
{ name: "legacy client", returnOnInput: undefined, agent: false, pending: false },
3662+
{ name: "updated client", returnOnInput: true, agent: false, pending: true },
3663+
{ name: "thread caller", returnOnInput: undefined, agent: true, pending: true },
3664+
{ name: "terminal-only thread caller", returnOnInput: false, agent: true, pending: false },
3665+
])("preserves wait semantics for $name", (scenario) =>
3666+
Effect.gen(function* () {
3667+
const runId = RunId.make("run:compat-wait");
3668+
const projection = {
3669+
...idleThreadProjection(launched),
3670+
runs: [{ id: runId, ordinal: 1, status: "running" }],
3671+
nodes: [{ id: "node:compat-wait", runId }],
3672+
runtimeRequests: [
3673+
{
3674+
id: "request:compat-wait",
3675+
nodeId: "node:compat-wait",
3676+
kind: "command",
3677+
status: "pending",
3678+
responseCapability: { type: "live" },
3679+
createdAt: DateTime.makeUnsafe(0),
3680+
},
3681+
],
3682+
} as unknown as OrchestrationV2ThreadProjection;
3683+
const management = yield* ThreadManagementService.ThreadManagementService.pipe(
3684+
Effect.provide(
3685+
ThreadManagementService.layer.pipe(
3686+
Layer.provide(
3687+
Layer.mergeAll(
3688+
Layer.mock(ProviderSessionManager.ProviderSessionManagerV2)({}),
3689+
Layer.mock(CommandReceiptStore.CommandReceiptStoreV2)({}),
3690+
ServerSettings.layerTest(),
3691+
Layer.mock(Orchestrator.OrchestratorV2)({
3692+
getThreadEventSequence: () => Effect.succeed(0),
3693+
getThreadRecords: () => Effect.succeed(projection),
3694+
streamStoredEventsFrom: () => Stream.never,
3695+
}),
3696+
),
3697+
),
3698+
),
3699+
),
3700+
);
3701+
const sent = yield* Ref.make(0);
3702+
yield* Effect.gen(function* () {
3703+
const mcp = yield* OrchestratorMcpService.OrchestratorMcpService;
3704+
const waiting = yield* mcp
3705+
.waitForThread(
3706+
{
3707+
...client,
3708+
...(scenario.agent
3709+
? {
3710+
thread: {
3711+
threadId: launched.id,
3712+
providerSessionId: "session:compat-wait",
3713+
providerInstanceId: ProviderInstanceId.make("codex"),
3714+
},
3715+
}
3716+
: {}),
3717+
},
3718+
{
3719+
threadId: launched.id,
3720+
runId,
3721+
timeoutMs: 60_000,
3722+
...(scenario.returnOnInput === undefined
3723+
? {}
3724+
: { returnOnInput: scenario.returnOnInput }),
3725+
},
3726+
)
3727+
.pipe(Effect.forkChild);
3728+
yield* TestClock.adjust("1 minute");
3729+
const result = yield* Fiber.join(waiting);
3730+
assert.equal(result.timedOut, !scenario.pending);
3731+
assert.equal(result.status, "running");
3732+
assert.equal(
3733+
result.pendingApproval?.requestId ?? null,
3734+
scenario.pending ? "request:compat-wait" : null,
3735+
);
3736+
}).pipe(
3737+
Effect.provide(
3738+
service([launched], sent, {
3739+
getThreadRecords: () => Effect.succeed(projection),
3740+
getProjectThreadRecords: () => Effect.succeed(projection),
3741+
waitForThread: management.waitForThread,
3742+
}),
3743+
),
3744+
);
3745+
}),
3746+
);
3747+
36583748
it.effect("waits on the caller's own thread without a separate shell lookup", () =>
36593749
Effect.gen(function* () {
36603750
const sent = yield* Ref.make(0);

‎apps/server/src/mcp/OrchestratorMcpService.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,7 @@ import {
115115
type McpThreadInvocationScope,
116116
requireThreadScope,
117117
threadLinkFor,
118+
threadWaitReturnsOnInput,
118119
} from "./McpInvocationContext.ts";
119120
import * as Metrics from "../observability/Metrics.ts";
120121
import {
@@ -3237,6 +3238,7 @@ const make = Effect.gen(function* () {
32373238
projectId: target.thread.projectId,
32383239
threadId: input.threadId,
32393240
...(input.runId === undefined ? {} : { runId: input.runId }),
3241+
terminalOnly: !threadWaitReturnsOnInput(scope, input.returnOnInput),
32403242
timeoutMs: Math.min(
32413243
MAX_WAIT_TIMEOUT_MS,
32423244
Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),

‎apps/server/src/mcp/toolkits/orchestrator/tools.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@ const ThreadSendTool = Tool.make("t3_thread_send", {
283283

284284
const ThreadWaitTool = Tool.make("t3_thread_wait", {
285285
description:
286-
"Wait for completion/input. No runId: latest. Read: t3_pending_request. Timeout: next means end turn; else retry.",
286+
"Wait for completion/input. No runId: latest. Questions: t3_pending_request; secret cards: t3_thread_read activity. Ask the user to answer secret cards and approvals in the thread. Timeout: next means end turn; else retry.",
287287
parameters: OrchestratorMcpThreadWaitInput,
288288
success: OrchestratorMcpThreadWaitResult,
289289
failure: OrchestratorMcpFailure,

‎apps/server/src/peer/PeerForwarding.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -465,6 +465,19 @@ it.effect("keeps a forwarded wait short and its retries scoped to the caller", (
465465
[PeerForwarding.FORWARDED_WAIT_CHUNK_MS, boxRun],
466466
]);
467467

468+
// An explicit terminal-only wait must survive the linked-client boundary.
469+
yield* a.call("thread:laptop-full", "t3_thread_wait", {
470+
environmentId: box.environmentId,
471+
threadId: boxThread,
472+
returnOnInput: false,
473+
});
474+
expect((yield* Ref.get(seen)).waits.map(({ terminalOnly }) => terminalOnly)).toEqual([
475+
false,
476+
false,
477+
false,
478+
true,
479+
]);
480+
468481
const send = (caller: string, clientRequestId: string) =>
469482
a.call(caller, "t3_thread_send", {
470483
environmentId: box.environmentId,

‎apps/server/src/peer/PeerForwarding.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,7 @@ const make = Effect.gen(function* () {
199199
threadId: input.threadId,
200200
...(runId === undefined ? {} : { runId }),
201201
timeoutMs: chunk,
202+
returnOnInput: McpInvocationContext.threadWaitReturnsOnInput(scope, input.returnOnInput),
202203
...(input.untilDelegatedWorkSettled === undefined
203204
? {}
204205
: { untilDelegatedWorkSettled: input.untilDelegatedWorkSettled }),
Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
{
22
"claudeSystemAppendBytes": 5366,
33
"codexAdditionalContextBytes": 7096,
4-
"mcpToolListJsonBytes": 48102
4+
"mcpToolListJsonBytes": 48358
55
}

‎packages/contracts/src/orchestratorMcp.ts‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,12 @@ export const OrchestratorMcpThreadWaitInput = Schema.Struct({
529529
threadId: ThreadId,
530530
runId: Schema.optional(RunId),
531531
timeoutMs: Schema.optional(Schema.Finite),
532+
returnOnInput: Schema.optional(
533+
Schema.Boolean.annotate({
534+
description:
535+
"Return on questions/approvals. Defaults to true for thread callers, false for external clients.",
536+
}),
537+
),
532538
untilDelegatedWorkSettled: Schema.optional(
533539
Schema.Boolean.annotate({
534540
description:

0 commit comments

Comments
 (0)