Skip to content
Open
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
121 changes: 121 additions & 0 deletions apps/server/src/mcp/OrchestratorMcpService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4876,6 +4876,127 @@ describe("OrchestratorMcpService thread lookup", () => {
}),
);

describe("sending to a retired thread", () => {
const retiredShell = (
replacedBy: ThreadId,
modes: Parameters<typeof liveThreadShell>[1] = {},
) => ({
...liveThreadShell(ThreadId.make("thread:retired-bot"), { activeRunId: null, ...modes }),
replacedByThreadId: replacedBy,
});
const asThread = (threadId: ThreadId): McpInvocationScope => ({
...client,
requestNamespace: `provider:${threadId}`,
thread: {
threadId,
providerSessionId: `provider:${threadId}`,
providerInstanceId: ProviderInstanceId.make("codex"),
},
client: undefined,
});

it.effect("refuses a redirect whose live replacement is above the caller's limits", () =>
Effect.gen(function* () {
const caller = liveThreadShell(ThreadId.make("thread:limited-caller"), {
runtimeMode: "auto",
});
const live = liveThreadShell(ThreadId.make("thread:wide-replacement"), {
activeRunId: null,
runtimeMode: "full-access",
});
// The retired thread itself is within the caller's limits; only its replacement is not.
const retired = retiredShell(live.id, { runtimeMode: "auto" });
const sent = yield* Ref.make(0);
const error = yield* Effect.gen(function* () {
const mcp = yield* OrchestratorMcpService.OrchestratorMcpService;
return yield* mcp
.sendToThread(asThread(caller.id), { threadId: retired.id, message: "hello" })
.pipe(Effect.flip);
}).pipe(
Effect.provide(
service([caller, retired, live], sent, {
getThreadRecords: () => Effect.succeed(idleThreadProjection(caller)),
getProjectThreadRecords: (input) =>
Effect.succeed(
idleThreadProjection(input.threadId === retired.id ? retired : live),
),
}),
),
);
assert.equal(error.code, "runtime_mode_escalation_denied");
assert.include(error.message, live.id);
assert.include(error.message, "above this caller's");
assert.equal(yield* Ref.get(sent), 0);
}),
);

it.effect("reports the live thread that took the message and retries setup there", () =>
Effect.gen(function* () {
const live = liveThreadShell(ThreadId.make("thread:live-replacement"), {
activeRunId: null,
});
const retired = retiredShell(live.id);
const failedRunId = RunId.make("run:replacement-setup-failed");
const retried: Array<ThreadLaunchService.ThreadLaunchPreparationInput> = [];
const recordsRead: Array<ThreadId> = [];
const sent = yield* Ref.make(0);
const result = yield* Effect.gen(function* () {
const mcp = yield* OrchestratorMcpService.OrchestratorMcpService;
return yield* mcp.sendToThread(client, { threadId: retired.id, message: "hello" });
}).pipe(
Effect.provide(
service(
[retired, live],
sent,
{
getProjectThreadRecords: () => Effect.succeed(idleThreadProjection(live)),
getThreadRecords: (threadId) => {
recordsRead.push(threadId);
return Effect.succeed({
thread: { ...live, id: threadId, worktreePath: null },
runs: [
{
id: failedRunId,
status: "failed",
startedAt: null,
workspacePreparation: { type: "worktree" },
},
],
} as never);
},
sendToThread: () =>
Effect.succeed({
run: {
id: RunId.make("run:replacement-held"),
threadId: live.id,
status: "queued",
queueHeld: true,
},
delivery: "queued",
} as never),
},
{
retryPreparation: (input) => {
retried.push(input);
return Effect.succeed({} as never);
},
},
),
),
);
// The result names the thread that took the turn, not the retired one the caller aimed at.
assert.equal(result.threadId, live.id);
assert.include(result.link ?? "", live.id);
assert.notInclude(result.link ?? "", retired.id);
assert.deepStrictEqual(recordsRead, [live.id]);
assert.deepStrictEqual(
retried.map((input) => [input.threadId, input.runId]),
[[live.id, failedRunId]],
);
}),
);
});

it.effect("refuses waiting without orchestration capability before reading the target", () =>
Effect.gen(function* () {
const sent = yield* Ref.make(0);
Expand Down
41 changes: 32 additions & 9 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { BACKGROUND_WAIT_STALE_MINUTES } from "@t3tools/contracts";
import { BACKGROUND_WAIT_STALE_MINUTES, resolveActiveThreadTargetWith } from "@t3tools/contracts";
import {
staleTimeoutMs,
waitActivityMs,
Expand Down Expand Up @@ -276,6 +276,7 @@ function threadManagementFailure(error: unknown): OrchestratorMcpFailure {
return failure("run_not_found", error.message);
case "ThreadManagementThreadArchivedError":
case "ThreadManagementWorktreeRestoreError":
case "ThreadRedirectError":
return failure("thread_not_sendable", error.message);
case "ThreadManagementNoSteerableRunError":
return failure(
Expand Down Expand Up @@ -3619,17 +3620,37 @@ const make = Effect.gen(function* () {
} satisfies OrchestratorMcpThreadReadResult;
}),
sendToThread: Effect.fn("OrchestratorMcpService.sendToThread")(function* (scope, input) {
const { parent, limits, target } = yield* loadScopedThread(scope, input.threadId, ["runs"]);
yield* assertLiveCallerForOtherThread(scope, parent, target);
yield* assertTargetWithinLimits(limits, target.thread);
const {
parent,
limits,
target: requested,
} = yield* loadScopedThread(scope, input.threadId, ["runs"]);
yield* assertLiveCallerForOtherThread(scope, parent, requested);
yield* assertTargetWithinLimits(limits, requested.thread);
// A retired thread forwards the message to its live replacement, so the replacement is the
// thread that takes the turn: the caller must reach it and stay within its modes too.
const resolved = yield* resolveActiveThreadTargetWith(
(id) => threadManagement.getThreadShell(id),
input.threadId,
).pipe(Effect.mapError(threadManagementFailure));
const target =
resolved.hopCount === 0
? requested
: parent !== undefined && resolved.threadId === parent.thread.id
? parent
: yield* loadTargetThread(scope, resolved.threadId);
if (resolved.hopCount > 0) {
yield* assertLiveCallerForOtherThread(scope, parent, target);
yield* assertTargetWithinLimits(limits, target.thread);
}

const mode = input.mode ?? "auto";
// A message to another thread rides in that thread's next digest unless the sender
// names a class. A message to the sender's own thread keeps the mode it asked for.
const deliveryClass =
input.deliveryClass ??
(input.digestCategory !== undefined ||
(parent !== undefined && parent.thread.id !== input.threadId)
(parent !== undefined && parent.thread.id !== target.thread.id)
? "digest"
: undefined);
if (
Expand Down Expand Up @@ -3693,8 +3714,10 @@ const make = Effect.gen(function* () {
),
),
);
// The thread that took the message: the replacement when the target was retired.
const liveThreadId = result.run.threadId ?? target.thread.id;
if (result.run.status === "queued" && result.run.queueHeld === true) {
yield* threadManagement.getThreadRecords(input.threadId, ["runs"]).pipe(
yield* threadManagement.getThreadRecords(liveThreadId, ["runs"]).pipe(
Effect.flatMap(({ thread, runs }) => {
const failed = latestExecutedRun(runs);
return thread.worktreePath === null &&
Expand All @@ -3704,7 +3727,7 @@ const make = Effect.gen(function* () {
commandId: CommandId.make(
`${stableCommandId({ scope, requestKey: key, operation: "thread-send" })}:retry-preparation`,
),
threadId: input.threadId,
threadId: liveThreadId,
runId: failed.id,
})
: Effect.void;
Expand All @@ -3715,8 +3738,8 @@ const make = Effect.gen(function* () {
);
}
return {
threadId: input.threadId,
link: threadLinkFor(scope, input.threadId, target.thread.title),
threadId: liveThreadId,
link: threadLinkFor(scope, liveThreadId, target.thread.title),
messageId,
runId: result.run.id,
...(result.run.delegatedTaskId === undefined ? {} : { taskId: result.run.delegatedTaskId }),
Expand Down
182 changes: 182 additions & 0 deletions apps/server/src/mcp/ThreadMetadataMcpService.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
import { describe, expect, it } from "@effect/vitest";
import {
EnvironmentId,
type OrchestrationV2ThreadShell,
ProviderInstanceId,
ThreadId,
type ThreadMetadataMcpUpdateInput,
} from "@t3tools/contracts";
import * as SecureRandom from "effect/crypto/SecureRandom";
import * as Effect from "effect/Effect";
import * as Layer from "effect/Layer";

import * as ThreadManagement from "../orchestration-v2/ThreadManagementService.ts";
import type { McpInvocationScope } from "./McpInvocationContext.ts";
import { liveThreadShell } from "./McpToolAccess.testkit.ts";
import * as ThreadMetadataMcpService from "./ThreadMetadataMcpService.ts";

const retired = ThreadId.make("thread:redirect-gate:retired");
const live = ThreadId.make("thread:redirect-gate:live");
const fullAccessCaller = ThreadId.make("thread:redirect-gate:full-access");
const supervisedCaller = ThreadId.make("thread:redirect-gate:supervised");
const planCaller = ThreadId.make("thread:redirect-gate:plan");

const shells = new Map<ThreadId, OrchestrationV2ThreadShell>([
[retired, liveThreadShell(retired, { activeRunId: null })],
[live, liveThreadShell(live, { activeRunId: null })],
[fullAccessCaller, liveThreadShell(fullAccessCaller)],
[supervisedCaller, liveThreadShell(supervisedCaller, { runtimeMode: "approval-required" })],
[planCaller, liveThreadShell(planCaller, { interactionMode: "plan" })],
]);

const scopeFor = (
thread: ThreadId | undefined,
client?: McpInvocationScope["client"],
): McpInvocationScope => ({
environmentId: EnvironmentId.make("environment"),
requestNamespace: "test:redirect-gate",
thread:
thread === undefined
? undefined
: {
threadId: thread,
providerSessionId: `provider:${thread}`,
providerInstanceId: ProviderInstanceId.make("codex"),
},
client,
capabilities: new Set(["orchestration"]),
issuedAt: 0,
});

const client = (
access: "read-only" | "approval-required" | "full-access",
narrowedTo?: { runtimeMode: "auto" | "full-access"; interactionMode: "plan" | "default" },
): NonNullable<McpInvocationScope["client"]> => ({
sessionId: "session",
label: "Test client",
access,
...(narrowedTo === undefined ? {} : { narrowedTo }),
});

const setRedirect = (replacedByThreadId: ThreadId | null): ThreadMetadataMcpUpdateInput => ({
threadId: retired,
action: "set_redirect",
replacedByThreadId,
clientRequestId: "redirect-request",
});

const run = (scope: McpInvocationScope, input: ThreadMetadataMcpUpdateInput) => {
const dispatched: Array<unknown> = [];
const layer = ThreadMetadataMcpService.layer.pipe(
Layer.provide(
Layer.mergeAll(
Layer.mock(SecureRandom.SecureRandom)({}),
Layer.mock(ThreadManagement.ThreadManagementService)({
getThreadShell: (threadId) => Effect.succeed(shells.get(threadId) ?? null),
dispatch: (command) =>
Effect.sync(() => {
dispatched.push(command);
return { sequence: 1, storedEvents: [] } as never;
}),
}),
),
),
);
return Effect.gen(function* () {
const service = yield* ThreadMetadataMcpService.ThreadMetadataMcpService;
const outcome = yield* service.update(scope, input).pipe(
Effect.map(() => "updated" as const),
Effect.catch((error) => Effect.succeed(error.code)),
);
return { outcome, dispatched };
}).pipe(Effect.provide(layer));
};

describe("ThreadMetadataMcpService set_redirect authority", () => {
it.effect("lets a full-access, default-mode thread set and clear a redirect", () =>
Effect.gen(function* () {
const set = yield* run(scopeFor(fullAccessCaller), setRedirect(live));
expect(set.outcome).toBe("updated");
expect(set.dispatched).toHaveLength(1);
const cleared = yield* run(scopeFor(fullAccessCaller), setRedirect(null));
expect(cleared.outcome).toBe("updated");
}),
);

it.effect("lets a full-access client without a thread set a redirect", () =>
Effect.gen(function* () {
const set = yield* run(scopeFor(undefined, client("full-access")), setRedirect(live));
expect(set.outcome).toBe("updated");
}),
);

it.effect("refuses a caller thread in a narrower runtime mode", () =>
Effect.gen(function* () {
for (const input of [setRedirect(live), setRedirect(null)]) {
const denied = yield* run(scopeFor(supervisedCaller), input);
expect(denied.outcome).toBe("capability_denied");
expect(denied.dispatched).toHaveLength(0);
}
}),
);

it.effect("refuses a caller thread in plan mode", () =>
Effect.gen(function* () {
const denied = yield* run(scopeFor(planCaller), setRedirect(live));
expect(denied.outcome).toBe("capability_denied");
expect(denied.dispatched).toHaveLength(0);
}),
);

it.effect("refuses a client below full access, or narrowed below it", () =>
Effect.gen(function* () {
const scopes = [
scopeFor(undefined, client("approval-required")),
scopeFor(undefined, client("read-only")),
scopeFor(
undefined,
client("full-access", { runtimeMode: "auto", interactionMode: "default" }),
),
scopeFor(
undefined,
client("full-access", { runtimeMode: "full-access", interactionMode: "plan" }),
),
// A full-access thread behind a narrowed client keeps the client's cap.
scopeFor(
fullAccessCaller,
client("full-access", { runtimeMode: "auto", interactionMode: "default" }),
),
// No thread and no client is the lowest ceiling.
scopeFor(undefined),
];
for (const scope of scopes) {
const denied = yield* run(scope, setRedirect(live));
expect(denied.outcome).toBe("capability_denied");
expect(denied.dispatched).toHaveLength(0);
}
}),
);

it.effect("refuses when the calling thread cannot be read", () =>
Effect.gen(function* () {
const denied = yield* run(
scopeFor(ThreadId.make("thread:redirect-gate:unknown")),
setRedirect(live),
);
expect(denied.outcome).toBe("capability_denied");
expect(denied.dispatched).toHaveLength(0);
}),
);

it.effect("leaves other metadata updates open to a narrower caller", () =>
Effect.gen(function* () {
const renamed = yield* run(scopeFor(supervisedCaller), {
threadId: retired,
action: "rename",
title: "Renamed",
clientRequestId: "rename-request",
});
expect(renamed.outcome).toBe("updated");
}),
);
});
Loading
Loading