Skip to content

Commit 681bf67

Browse files
donjor-agent[bot]donjor
authored andcommitted
fix(server): external MCP reads show background work and native subagent turns (#1648)
## Problem External MCP reports run status only. An owner whose run ended with 5 native subagents still running reads `completed`, and each child reads `idle` with `runCount: 0`. The UI shows the same owner as **Waiting on 5 subagents**. Refs #1647; it stays open for the gap below. ## Change `t3_external_thread_read`, `_list`, and `_wait` gain an additive `work` field. It reads the projection the UI reads: | Source | Feeds | | --- | --- | | Shell `pendingBackgroundTasks` | `background`, the sidebar's roster | | Last runless `root_turn` node | `nativeTurn` on provider-native subagents | | Shell and native turn times | `updatedAt`: the latest | `work.state` ranks like client-runtime `shellRuntime`: 1. `awaiting_response`: a request waits on a person 2. `running`: a live or queued run, or native turn 3. `waiting_on_background`: held background work 4. `running`: a run waiting on its checkpoint 5. `idle` ### Unchanged | Field | Rule | | --- | --- | | `status`, `pendingRequestCount` | run view, as before | | Pinned `runId` wait | run outcome stands; `work` reports what remains | | Native child run ids | none fabricated; `runId` stays null | | Grant, filters, pagination | `work` computed only for granted, paged rows | ### New wait mode `until: "work"` polls every 500 ms until `work` is `idle` or `awaiting_response`. With `runId` it refuses `invalid_request`. A held command, such as a dev server, stays listed but does not hold the thread. List reads nodes only for native subagent rows on the page, 4 at a time. Deleted threads now read as missing at the shell, as the record read already did. ## Known gap: resumed native subagents `work` reads the projection; it cannot be more current than it. A native subagent resumed by a later run records nothing on its child thread (#1650, upstream `pingdotgg#16261`). | Read | Result for a resumed child | | --- | --- | | Owner `work.background` | correct: lists it with `childThreadId` | | Child `work.nativeTurn` | frozen pre-resume turn | | Child `work.state` | may read `idle` while it works | Reproduced live on 2026-10-06 with 5 resumed Claude subagents. The routing fix is separate work under #1650; this PR does not change routing. ## Scope and approval Owner-requested fix to the fork's external MCP (`device-auth`). Internal `/mcp` parity is a follow-up. ## Verification ```text vp test run apps/server/src/mcp/external/ → 47 passed vp test run apps/server/src/mcp/ → 256 passed roster and native turn ignored (mutation) → 12 of 23 work tests fail apps/server vp run typecheck → exit 0 vp lint <touched files> → exit 0 independent review, 2 rounds → nothing blocking aftercare on 6be86e5 (limited, not a full review) → 0 findings apps/server vp run build → exit 0 vp run fork:ci → exit 0 ``` Shells in the tests come from the real `threadShellFromProjection`, shaped like the live repro. Not yet checked: the running instance; it needs a release and restart. Claude Opus 5.5 (high, 1m) via Claude Code in T3 Code. ## Fork trailers Squashes: - 3c8f826 fix(server): external MCP reads show background work and native subagent turns (#1648) (#1648) - eccf782 fixup! fix(server): external MCP reads show background work and native subagent turns (#1648) (#1648) Fork-Domain: device-auth Fork-Tier: core Co-authored-by: donjor <[email protected]>
1 parent 43dfaa3 commit 681bf67

6 files changed

Lines changed: 928 additions & 34 deletions

File tree

‎apps/server/src/mcp/external/ExternalMcpService.fork.test.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -122,7 +122,11 @@ const makeHarness = (
122122
getThreadShell: (threadId) =>
123123
Effect.succeed(
124124
threads.has(threadId)
125-
? ({ id: threadId, projectId: threads.get(threadId)!.projectId } as never)
125+
? ({
126+
id: threadId,
127+
projectId: threads.get(threadId)!.projectId,
128+
deletedAt: null,
129+
} as never)
126130
: null,
127131
),
128132
getProjectThreadRecords: (input) => Effect.succeed(projection(input.threadId) as never),

‎apps/server/src/mcp/external/ExternalMcpService.fork.ts‎

Lines changed: 116 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,15 @@ import {
1818
type OrchestratorMcpTarget,
1919
OrchestratorMcpThreadInterruptResult,
2020
type OrchestratorMcpThreadListInput,
21+
type OrchestratorMcpThreadDetail,
2122
type OrchestratorMcpThreadListItem,
2223
type OrchestratorMcpThreadReadInput,
2324
type OrchestratorMcpThreadReadResult,
2425
OrchestratorMcpThreadSendResult,
2526
type OrchestratorMcpThreadWaitResult,
2627
type OrchestrationV2AppThread,
2728
type OrchestrationV2Run,
29+
type OrchestrationV2ThreadShell,
2830
type OrchestrationV2TurnItem,
2931
type ProjectId,
3032
RunAttemptId,
@@ -34,6 +36,7 @@ import {
3436
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
3537
import * as Context from "effect/Context";
3638
import * as DateTime from "effect/DateTime";
39+
import * as Duration from "effect/Duration";
3740
import * as Effect from "effect/Effect";
3841
import * as Layer from "effect/Layer";
3942
import * as Option from "effect/Option";
@@ -58,6 +61,13 @@ import {
5861
threadRunFork,
5962
timelineItemFork,
6063
} from "../OrchestratorMcpService.ts";
64+
import {
65+
type ExternalMcpThreadWork,
66+
hasNativeTurn,
67+
isWorkSettled,
68+
nativeTurnOf,
69+
threadWork,
70+
} from "./ExternalMcpWork.fork.ts";
6171
import {
6272
makeExternalMcpRequestLedger,
6373
requestFingerprint,
@@ -71,6 +81,9 @@ const DEFAULT_THREAD_ITEM_MAX_CHARS = 20_000;
7181
// stays well under common proxy and client timeouts.
7282
const DEFAULT_WAIT_TIMEOUT_MS = 60 * 1_000;
7383
const MAX_WAIT_TIMEOUT_MS = 10 * 60 * 1_000;
84+
const WORK_POLL_INTERVAL_MS = 500;
85+
// Native subagent rows on one list page whose turn is read at once.
86+
const NATIVE_TURN_READ_CONCURRENCY = 4;
7487
// An interrupt pin recording that no run was active; no run id is empty.
7588
const NO_ACTIVE_RUN_PIN = "";
7689

@@ -96,11 +109,24 @@ export interface ExternalMcpProject {
96109

97110
export interface ExternalMcpThreadListResult {
98111
readonly projectId: ProjectId;
99-
readonly threads: ReadonlyArray<OrchestratorMcpThreadListItem>;
112+
readonly threads: ReadonlyArray<
113+
OrchestratorMcpThreadListItem & { readonly work: ExternalMcpThreadWork }
114+
>;
100115
readonly nextCursor: number | null;
101116
readonly total: number;
102117
}
103118

119+
export interface ExternalMcpThreadReadResult extends Omit<
120+
OrchestratorMcpThreadReadResult,
121+
"thread"
122+
> {
123+
readonly thread: OrchestratorMcpThreadDetail & { readonly work: ExternalMcpThreadWork };
124+
}
125+
126+
export interface ExternalMcpThreadWaitResult extends OrchestratorMcpThreadWaitResult {
127+
readonly work: ExternalMcpThreadWork;
128+
}
129+
104130
export interface ExternalMcpServiceShape {
105131
readonly listProjects: (
106132
principal: ExternalMcpPrincipal,
@@ -112,15 +138,16 @@ export interface ExternalMcpServiceShape {
112138
readonly readThread: (
113139
principal: ExternalMcpPrincipal,
114140
input: OrchestratorMcpThreadReadInput,
115-
) => Effect.Effect<OrchestratorMcpThreadReadResult, OrchestratorMcpFailure>;
141+
) => Effect.Effect<ExternalMcpThreadReadResult, OrchestratorMcpFailure>;
116142
readonly waitForThread: (
117143
principal: ExternalMcpPrincipal,
118144
input: {
119145
readonly threadId: ThreadId;
120146
readonly runId?: RunId | undefined;
121147
readonly timeoutMs?: number | undefined;
148+
readonly until?: "run" | "work" | undefined;
122149
},
123-
) => Effect.Effect<OrchestratorMcpThreadWaitResult, OrchestratorMcpFailure>;
150+
) => Effect.Effect<ExternalMcpThreadWaitResult, OrchestratorMcpFailure>;
124151
readonly createThread: (
125152
principal: ExternalMcpPrincipal,
126153
input: {
@@ -274,14 +301,24 @@ const make = Effect.gen(function* () {
274301
});
275302

276303
/** A thread outside the grant reads as missing, so its existence does not leak. */
277-
const loadThread = (principal: ExternalMcpPrincipal, threadId: ThreadId) =>
304+
const loadShell = (principal: ExternalMcpPrincipal, threadId: ThreadId) =>
278305
Effect.gen(function* () {
279306
const shell = yield* threadManagement
280307
.getThreadShell(threadId)
281308
.pipe(Effect.mapError((error) => failure("orchestration_error", errorMessage(error))));
282-
if (shell === null || !externalMcpPolicyAllowsProject(principal.policy, shell.projectId)) {
309+
if (
310+
shell === null ||
311+
shell.deletedAt !== null ||
312+
!externalMcpPolicyAllowsProject(principal.policy, shell.projectId)
313+
) {
283314
return yield* threadUnavailable(threadId);
284315
}
316+
return shell;
317+
});
318+
319+
const loadThread = (principal: ExternalMcpPrincipal, threadId: ThreadId) =>
320+
Effect.gen(function* () {
321+
const shell = yield* loadShell(principal, threadId);
285322
const target = yield* threadManagement
286323
.getProjectThreadRecords({ projectId: shell.projectId, threadId }, [
287324
"runs",
@@ -293,6 +330,49 @@ const make = Effect.gen(function* () {
293330
return target;
294331
});
295332

333+
/** Only a provider-native subagent thread reads its nodes; every other thread has runs. */
334+
const workOf = (shell: OrchestrationV2ThreadShell) =>
335+
hasNativeTurn(shell)
336+
? threadManagement.getThreadRecords(shell.id, ["nodes"]).pipe(
337+
Effect.map((records) => threadWork(shell, nativeTurnOf(records.nodes))),
338+
Effect.mapError(threadManagementFailureFork),
339+
)
340+
: Effect.succeed(threadWork(shell, null));
341+
342+
const currentWork = (principal: ExternalMcpPrincipal, threadId: ThreadId) =>
343+
loadShell(principal, threadId).pipe(
344+
Effect.flatMap((shell) => workOf(shell).pipe(Effect.map((work) => ({ shell, work })))),
345+
);
346+
347+
/**
348+
* Waits until nothing runs and no background work holds the thread, or a
349+
* request waits on a person. Never pins a run: background work outlives the
350+
* run that started it.
351+
*/
352+
const waitForWork = (principal: ExternalMcpPrincipal, threadId: ThreadId, timeoutMs: number) =>
353+
Effect.gen(function* () {
354+
const settled = Effect.gen(function* () {
355+
while (true) {
356+
const current = yield* currentWork(principal, threadId);
357+
if (isWorkSettled(current.work)) return current;
358+
yield* Effect.sleep(Duration.millis(WORK_POLL_INTERVAL_MS));
359+
}
360+
}).pipe(Effect.timeoutOption(Duration.millis(timeoutMs)));
361+
const waited = yield* settled;
362+
// As with a run wait, the final read decides, so work that settled while
363+
// the timeout won the race does not count as timed out.
364+
const { shell, work } = Option.isSome(waited)
365+
? waited.value
366+
: yield* currentWork(principal, threadId);
367+
return {
368+
threadId,
369+
runId: shell.latestRunId,
370+
status: shell.activityRunStatus ?? shell.status,
371+
timedOut: !isWorkSettled(work),
372+
work,
373+
} satisfies ExternalMcpThreadWaitResult;
374+
});
375+
296376
/**
297377
* The message an earlier attempt already dispatched under its stable id, with
298378
* the run it reached, so a retry reports that run instead of acting again.
@@ -455,19 +535,24 @@ const make = Effect.gen(function* () {
455535
const statuses = input.statuses === undefined ? null : new Set(input.statuses);
456536
const titleContains = input.titleContains?.toLocaleLowerCase();
457537
const filtered = projectThreads
458-
.map(listItemFromShellFork)
459-
.filter((thread) => statuses === null || statuses.has(thread.status))
460-
.filter((thread) => input.settled === undefined || thread.settled === input.settled)
538+
.map((shell) => ({ shell, thread: listItemFromShellFork(shell) }))
539+
.filter(({ thread }) => statuses === null || statuses.has(thread.status))
540+
.filter(({ thread }) => input.settled === undefined || thread.settled === input.settled)
461541
.filter(
462-
(thread) =>
542+
({ thread }) =>
463543
titleContains === undefined ||
464544
thread.title.toLocaleLowerCase().includes(titleContains),
465545
);
466546
const cursor = input.cursor ?? 0;
467547
const page = filtered.slice(cursor, cursor + (input.limit ?? DEFAULT_THREAD_LIST_LIMIT));
548+
const threads = yield* Effect.forEach(
549+
page,
550+
({ shell, thread }) => workOf(shell).pipe(Effect.map((work) => ({ ...thread, work }))),
551+
{ concurrency: NATIVE_TURN_READ_CONCURRENCY },
552+
);
468553
return {
469554
projectId: input.projectId,
470-
threads: page,
555+
threads,
471556
nextCursor: cursor + page.length < filtered.length ? cursor + page.length : null,
472557
total: filtered.length,
473558
};
@@ -476,6 +561,7 @@ const make = Effect.gen(function* () {
476561
readThread: (principal, input) =>
477562
Effect.gen(function* () {
478563
const target = yield* loadThread(principal, input.threadId);
564+
const { work } = yield* currentWork(principal, input.threadId);
479565
const maxChars = input.maxCharsPerItem ?? DEFAULT_THREAD_ITEM_MAX_CHARS;
480566
const timeline = yield* threadManagement
481567
.getTimelinePage(input.threadId, {
@@ -504,7 +590,7 @@ const make = Effect.gen(function* () {
504590
),
505591
);
506592
return {
507-
thread: threadDetailFork(target, timeline.totalItems),
593+
thread: { ...threadDetailFork(target, timeline.totalItems), work },
508594
recentRuns: target.runs
509595
.toSorted((left, right) => right.ordinal - left.ordinal)
510596
.slice(0, input.runLimit ?? DEFAULT_THREAD_RUN_LIMIT)
@@ -519,29 +605,42 @@ const make = Effect.gen(function* () {
519605
),
520606
nextPosition: timeline.items.at(-1)?.position ?? null,
521607
hasMore: timeline.hasMore,
522-
} satisfies OrchestratorMcpThreadReadResult;
608+
} satisfies ExternalMcpThreadReadResult;
523609
}),
524610

525611
waitForThread: (principal, input) =>
526612
Effect.gen(function* () {
613+
const timeoutMs = Math.min(
614+
MAX_WAIT_TIMEOUT_MS,
615+
Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
616+
);
617+
if (input.until === "work") {
618+
if (input.runId !== undefined) {
619+
return yield* failure(
620+
"invalid_request",
621+
"runId waits on one run; until=work waits on the whole thread. Pass one, not both.",
622+
);
623+
}
624+
return yield* waitForWork(principal, input.threadId, timeoutMs);
625+
}
527626
const target = yield* loadThread(principal, input.threadId);
528627
const result = yield* threadManagement
529628
.waitForThread({
530629
projectId: target.thread.projectId,
531630
threadId: input.threadId,
532631
...(input.runId === undefined ? {} : { runId: input.runId }),
533-
timeoutMs: Math.min(
534-
MAX_WAIT_TIMEOUT_MS,
535-
Math.max(1, input.timeoutMs ?? DEFAULT_WAIT_TIMEOUT_MS),
536-
),
632+
timeoutMs,
537633
})
538634
.pipe(Effect.mapError(threadManagementFailureFork));
635+
// The run's outcome stands; work reports what still runs after it.
636+
const { work } = yield* currentWork(principal, input.threadId);
539637
return {
540638
threadId: input.threadId,
541639
runId: result.run?.id ?? null,
542640
status: result.run?.status ?? "idle",
543641
timedOut: result.timedOut,
544-
} satisfies OrchestratorMcpThreadWaitResult;
642+
work,
643+
} satisfies ExternalMcpThreadWaitResult;
545644
}),
546645

547646
createThread: (principal, input) =>

0 commit comments

Comments
 (0)