Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 81 additions & 1 deletion apps/server/src/mcp/McpToolAccess.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,16 @@
import { expect, it } from "@effect/vitest";
import {
EnvironmentId,
MessageId,
NodeId,
type OrchestrationV2Run,
OrchestratorMcpEnvironmentTarget,
OrchestratorMcpFailure,
ProviderInstanceId,
ProviderInteractionMode,
ProviderThreadId,
RunAttemptId,
RunId,
RuntimeMode,
ThreadId,
} from "@t3tools/contracts";
Expand All @@ -23,7 +29,7 @@ import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.t
import * as McpHttpServer from "./McpHttpServer.ts";
import * as McpInvocationContext from "./McpInvocationContext.ts";
import * as McpToolAccess from "./McpToolAccess.ts";
import { liveThreadShell } from "./McpToolAccess.testkit.ts";
import { idleThreadProjection, liveThreadShell } from "./McpToolAccess.testkit.ts";

const supervisedThreadId = ThreadId.make("thread:supervised");
const planThreadId = ThreadId.make("thread:plan");
Expand All @@ -33,6 +39,8 @@ const backgroundThreadId = ThreadId.make("thread:background");
const oldProviderThreadId = ThreadId.make("thread:old-provider-background");
const archivedThreadId = ThreadId.make("thread:archived-background");
const unknownOwnerThreadId = ThreadId.make("thread:unknown-background-owner");
const queuedWakeThreadId = ThreadId.make("thread:queued-wake");
const foreignQueuedThreadId = ThreadId.make("thread:foreign-queued");

const backgroundShell = (threadId: ThreadId, providerInstanceId: ProviderInstanceId) => ({
...liveThreadShell(threadId, { activeRunId: null }),
Expand All @@ -41,6 +49,63 @@ const backgroundShell = (threadId: ThreadId, providerInstanceId: ProviderInstanc
],
});

const queuedShell = (threadId: ThreadId, runId: RunId) => {
const base = liveThreadShell(threadId, { activeRunId: null });
return {
...base,
status: "queued" as const,
latestRunId: runId,
latestRunRequestedAt: base.updatedAt,
latestRunCompletedAt: null,
};
};

const queuedRun = (
threadId: ThreadId,
id: RunId,
providerInstanceId: ProviderInstanceId,
): OrchestrationV2Run => ({
id,
threadId,
ordinal: 1,
providerInstanceId,
modelSelection: { instanceId: providerInstanceId, model: "gpt-5" },
providerThreadId: ProviderThreadId.make("provider-thread:queued"),
userMessageId: MessageId.make("message:queued"),
rootNodeId: NodeId.make("node:queued"),
activeAttemptId: RunAttemptId.make("attempt:queued"),
status: "queued",
queuePosition: 1,
requestedAt: liveThreadShell(threadId).updatedAt,
startedAt: null,
completedAt: null,
checkpointId: null,
contextHandoffId: null,
});

const queuedRuns = new Map<ThreadId, ReadonlyArray<OrchestrationV2Run>>([
[
queuedWakeThreadId,
[
queuedRun(
queuedWakeThreadId,
RunId.make("run:queued-wake"),
ProviderInstanceId.make("codex"),
),
],
],
[
foreignQueuedThreadId,
[
queuedRun(
foreignQueuedThreadId,
RunId.make("run:foreign-queued"),
ProviderInstanceId.make("claude"),
),
],
],
]);

const shells = new Map([
[supervisedThreadId, liveThreadShell(supervisedThreadId, { runtimeMode: "approval-required" })],
[
Expand All @@ -65,6 +130,8 @@ const shells = new Map([
pendingBackgroundTasks: [{ taskId: "task:unknown", kind: "subagent" as const }],
},
],
[queuedWakeThreadId, queuedShell(queuedWakeThreadId, RunId.make("run:queued-wake"))],
[foreignQueuedThreadId, queuedShell(foreignQueuedThreadId, RunId.make("run:foreign-queued"))],
]);

const threadCaller = (threadId: ThreadId): McpInvocationContext.McpInvocationScope => ({
Expand Down Expand Up @@ -233,6 +300,8 @@ const background = threadCaller(backgroundThreadId);
const oldProviderBackground = threadCaller(oldProviderThreadId);
const archivedBackground = threadCaller(archivedThreadId);
const unknownOwnerBackground = threadCaller(unknownOwnerThreadId);
const queuedWake = threadCaller(queuedWakeThreadId);
const foreignQueued = threadCaller(foreignQueuedThreadId);
const mismatchedProvider = {
...background,
thread: { ...background.thread!, providerInstanceId: ProviderInstanceId.make("claude") },
Expand Down Expand Up @@ -269,11 +338,15 @@ it.effect.each([
["acts_as_caller", mismatchedProvider, {}, "parent_not_active"],
["acts_as_caller", archivedBackground, {}, "parent_not_active"],
["acts_as_caller", unknownOwnerBackground, {}, "parent_not_active"],
["acts_as_caller", queuedWake, {}, "ran"],
["acts_as_caller", foreignQueued, {}, "parent_not_active"],

["writes", supervised, {}, "ran"],
["writes", ended, {}, "parent_not_active"],
["writes", background, {}, "ran"],
["writes", oldProviderBackground, {}, "parent_not_active"],
["writes", queuedWake, {}, "ran"],
["writes", foreignQueued, {}, "parent_not_active"],
["writes", supervisedClient, {}, "ran"],
["writes", previewOnly, {}, "capability_denied"],
["writes_environment", previewOnly, {}, "capability_denied"],
Expand Down Expand Up @@ -328,6 +401,13 @@ it.effect.each([
probeServer(
Layer.mock(ThreadManagement.ThreadManagementService)({
getThreadShell: (threadId) => Effect.succeed(shells.get(threadId) ?? null),
getProjectThreadRecords: ({ threadId }) => {
const shell = shells.get(threadId) ?? liveThreadShell(threadId, { activeRunId: null });
return Effect.succeed({
...idleThreadProjection(shell),
runs: queuedRuns.get(threadId) ?? [],
});
},
}),
),
),
Expand Down
51 changes: 45 additions & 6 deletions apps/server/src/mcp/OrchestratorMcpService.activity.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1064,12 +1064,14 @@ it("readThread and sendToThread reach threads in other projects", async () => {
getProjectThreadRecords: (input) =>
input.threadId === foreignThreadId && input.projectId === foreignProjectId
? Effect.succeed(foreignProjection(input.threadId))
: Effect.fail(
new ThreadManagementService.ThreadManagementThreadNotFoundError({
projectId: input.projectId,
threadId: input.threadId,
}),
),
: input.threadId === parentThreadId && input.projectId === parentShell?.projectId
? Effect.succeed(parentProjection)
: Effect.fail(
new ThreadManagementService.ThreadManagementThreadNotFoundError({
projectId: input.projectId,
threadId: input.threadId,
}),
),
sendToThread: () =>
Effect.succeed({
run: { id: "run-foreign", status: "queued" },
Expand Down Expand Up @@ -1214,6 +1216,43 @@ it("readThread and sendToThread reach threads in other projects", async () => {
.sendToThread(makeScope(), { threadId: foreignThreadId, message: "after stop" })
.pipe(Effect.flip);
expect(stopped.code).toBe("parent_not_active");

const queuedRunId = RunId.make("run-parent-queued-wake");
parentRuns = [
{
...makeRun({ id: queuedRunId, ordinal: 2, status: "queued" }),
rootNodeId: taskId,
},
];
parentShell = {
...liveThreadShell(parentThreadId, { activeRunId: null }),
status: "queued",
latestRunId: queuedRunId,
latestRunRequestedAt: now,
latestRunCompletedAt: null,
};
const queuedSent = yield* service.sendToThread(makeScope(), {
threadId: foreignThreadId,
message: "queued wake",
});
expect(queuedSent.threadId).toBe(foreignThreadId);
// Queued wakes do not satisfy backgroundSubagentRun when no background subagent is pending.
const queuedDelegate = yield* service
.delegateTask(makeScope(), { task: "requires an active run" })
.pipe(Effect.flip);
expect(queuedDelegate.code).toBe("parent_not_active");

parentRuns = [
{
...makeRun({ id: queuedRunId, ordinal: 2, status: "queued" }),
providerInstanceId: customCodexInstanceId,
rootNodeId: taskId,
},
];
const foreignQueuedSent = yield* service
.sendToThread(makeScope(), { threadId: foreignThreadId, message: "foreign queued" })
.pipe(Effect.flip);
expect(foreignQueuedSent.code).toBe("parent_not_active");
}).pipe(Effect.provide(layer), Effect.runPromise);
});

Expand Down
21 changes: 14 additions & 7 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,10 @@ import {
SECRET_REQUEST_UNSAVED_NOTE,
} from "@t3tools/contracts";
import { getProviderOptionCurrentValue, withLegacyUltracodeEffort } from "@t3tools/shared/model";
import { backgroundWorkHoldsCompletion } from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import {
backgroundWorkHoldsCompletion,
hasPendingBackgroundSubagent,
} from "@t3tools/shared/orchestrationV2PendingBackgroundWork";
import { runRanAfter } from "@t3tools/shared/orchestrationV2ThreadError";
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
import { formatThreadLink } from "@t3tools/shared/threadLinks";
Expand Down Expand Up @@ -138,7 +141,7 @@ import {
runtimeModeRank,
taskPrompt,
} from "./delegatedTaskModes.ts";
import { assertTargetWithinLimits, isLiveCallerShell, threadNotFound } from "./threadAccess.ts";
import { assertLiveCallerShell, assertTargetWithinLimits, threadNotFound } from "./threadAccess.ts";
import { WITHHELD, withoutWebhookUrlToken } from "../scheduledTasks/webhookUrlToken.ts";
import * as SecretRequests from "../secrets/SecretRequests.ts";
import * as PeerForwarding from "../peer/PeerForwarding.ts";
Expand Down Expand Up @@ -1529,9 +1532,7 @@ const make = Effect.gen(function* () {
return threadManagement.getThreadShell(parent.thread.id).pipe(
Effect.mapError(threadManagementFailure),
Effect.flatMap((shell) =>
isLiveCallerShell(shell, scope.thread?.providerInstanceId)
? Effect.void
: Effect.fail(notActive),
assertLiveCallerShell(threadManagement, shell, scope.thread?.providerInstanceId),
),
);
}
Expand All @@ -1550,9 +1551,15 @@ const make = Effect.gen(function* () {
.getThreadShell(threadId)
.pipe(Effect.mapError(threadManagementFailure));
if (
shell?.activeRunId !== null ||
shell === null ||
shell.archivedAt !== null ||
shell.activeRunId !== null ||
shell.latestRunId === null ||
!isLiveCallerShell(shell, scope.thread?.providerInstanceId)
shell.providerInstanceId !== scope.thread?.providerInstanceId ||
!hasPendingBackgroundSubagent(
shell.pendingBackgroundTasks,
scope.thread?.providerInstanceId,
)
) {
return undefined;
}
Expand Down
Loading
Loading