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
16 changes: 16 additions & 0 deletions apps/server/src/mcp/McpInvocationContext.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,22 @@ export const withRuntimeModeCeiling = (
};
};

export function linkedMessageSender(
client: McpClientCaller | undefined,
origin: { readonly sessionId: string } | undefined,
): { readonly linkedSender?: OrchestrationV2LinkedSender } {
if (client?.linked !== true || client.senderThread === undefined) return {};
const { environmentId, threadId, title } = client.senderThread;
return {
linkedSender: {
environmentId,
threadId,
title,
...(client.sessionId === origin?.sessionId ? { fromOriginatingLink: true } : {}),
},
};
}

/** Thread callers default to their own thread; client callers need thread for tools that act as the caller. */
export interface McpInvocationScope {
readonly environmentId: EnvironmentId;
Expand Down
19 changes: 12 additions & 7 deletions apps/server/src/mcp/OrchestratorMcpService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -524,7 +524,7 @@ describe("OrchestratorMcpService", () => {
const childThreadId = ThreadId.make("thread:mcp-report-child");
const taskA = NodeId.make("node:mcp-report-task-a");
const taskB = NodeId.make("node:mcp-report-task-b");
const silent = "Child task completed without an assistant result.";
const silent = "Child run completed without an assistant result.";
const parentProjection = {
thread: { id: parentThreadId },
runs: [],
Expand Down Expand Up @@ -606,10 +606,11 @@ describe("OrchestratorMcpService", () => {
yield* Effect.gen(function* () {
const service = yield* OrchestratorMcpService.OrchestratorMcpService;
// Task A reported, then a run queued behind the report ended without text.
reports = [[1, "REPORT-A"]];
reports = [[1, "I need access before I can review the change."]];
const reported = yield* service.taskStatus(scope, taskA);
assert.equal(reported.status, "completed");
assert.equal(reported.summary, "REPORT-A");
assert.equal(reported.assignmentOutcome, "unverified");
assert.equal(reported.summary, "I need access before I can review the change.");
assert.equal(reported.latestTerminalRunId, runs[2]!.id);
assert.equal(reported.latestTerminalSummary, silent);
assert.equal((yield* service.taskStatus(scope, taskB)).summary, silent);
Expand Down Expand Up @@ -5576,16 +5577,19 @@ describe("OrchestratorMcpService thread lookup", () => {

it.effect("records the linked environment's thread that sent a message", () =>
Effect.gen(function* () {
const target = liveThreadShell(ThreadId.make("thread:target"));
const target = {
...liveThreadShell(ThreadId.make("thread:target")),
linkOrigin: { sessionId: "link-a", label: "A", access: "full-access" as const },
};
const sender = {
environmentId: EnvironmentId.make("environment:a"),
threadId: ThreadId.make("thread:orc"),
title: "orc lead",
};
const linked = (senderThread?: typeof sender): McpInvocationScope => ({
const linked = (senderThread?: typeof sender, sessionId = "link-a"): McpInvocationScope => ({
...client,
client: {
sessionId: "link-a",
sessionId,
label: "A",
access: "full-access",
linked: true,
Expand Down Expand Up @@ -5617,7 +5621,8 @@ describe("OrchestratorMcpService thread lookup", () => {
});

const fromLink = yield* sendAs(linked(sender));
assert.deepStrictEqual(fromLink?.linkedSender, sender);
assert.deepStrictEqual(fromLink?.linkedSender, { ...sender, fromOriginatingLink: true });
assert.deepStrictEqual((yield* sendAs(linked(sender, "another-link")))?.linkedSender, sender);
assert.isUndefined(fromLink?.senderThreadId);
assert.isUndefined((yield* sendAs(linked()))?.linkedSender);
}),
Expand Down
11 changes: 6 additions & 5 deletions apps/server/src/mcp/OrchestratorMcpService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ import {
type McpThreadInvocationScope,
requireThreadScope,
threadLinkFor,
linkedMessageSender,
} from "./McpInvocationContext.ts";
import * as Metrics from "../observability/Metrics.ts";
import {
Expand Down Expand Up @@ -1983,6 +1984,7 @@ const make = Effect.gen(function* () {
childRunId: childRun?.id ?? null,
childNodeId: task.id,
status,
...(status === "completed" ? { assignmentOutcome: "unverified" as const } : {}),
workState,
hasPendingChildRuns: hasPendingChildRuns(childProjection, childRun),
providerInstanceId: modelSelection.instanceId,
Expand Down Expand Up @@ -2178,6 +2180,7 @@ const make = Effect.gen(function* () {
childRunId: null,
childNodeId: task.id,
status,
...(status === "completed" ? { assignmentOutcome: "unverified" as const } : {}),
workState: terminal ? "result_available" : "working",
hasPendingChildRuns: false,
providerInstanceId: task.providerInstanceId,
Expand Down Expand Up @@ -3712,11 +3715,9 @@ const make = Effect.gen(function* () {
operation: "thread-send",
}),
threadId: input.threadId,
...(parent === undefined ? {} : { senderThreadId: parent.thread.id }),
// A linked environment's agent has no thread here; the link names it.
...(parent === undefined && scope.client?.senderThread !== undefined
? { linkedSender: scope.client.senderThread }
: {}),
...(parent === undefined
? linkedMessageSender(scope.client, target.thread.linkOrigin)
: { senderThreadId: parent.thread.id }),
messageId,
text: input.message,
attachments: [],
Expand Down
11 changes: 8 additions & 3 deletions apps/server/src/mcp/linkOrigin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -355,12 +355,17 @@ it.layer(Layer.provideMerge(layerTools, layerOrchestration))("work a link starts

// A link's delegated task names its parent there; only a link's launch may.
const delegatedFrom = {
environmentId: "environment-laptop",
threadId: "thread:laptop-parent",
environmentId: EnvironmentId.make("environment-laptop"),
threadId: ThreadId.make("thread:laptop-parent"),
title: "Laptop parent",
};
const task = yield* launch(laptop, "Delegated from the laptop", { delegatedFrom });
const origin = { ...laptop, client: { ...laptop.client!, senderThread: delegatedFrom } };
const task = yield* launch(origin, "Delegated from the laptop", { delegatedFrom });
assert.deepEqual((yield* projections.getThreadShell(task))?.delegatedFrom, delegatedFrom);
const mismatched = yield* launch(origin, "Other parent", {
delegatedFrom: { ...delegatedFrom, threadId: "other" },
});
assert.equal((yield* projections.getThreadShell(mismatched))?.delegatedFrom, undefined);
const claimed = yield* launch(claudeCode, "Claims a parent", { delegatedFrom });
assert.equal((yield* projections.getThreadShell(claimed))?.delegatedFrom, undefined);
}),
Expand Down
2 changes: 1 addition & 1 deletion apps/server/src/mcp/toolkits/orchestrator/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ const DelegateTaskTool = Tool.make("delegate_task", {

const TaskStatusTool = Tool.make("task_status", {
description:
"Read a child task you started only after its completion wakes you. workState: working, waiting_for_children, result_available. A finished turn with live child work is not done. Reading summary marks the final result delivered.",
"Read your child after its wake. workState: working, waiting_for_children, result_available. Child work can outlive a finished run. A completed run may report a blocker. Reading summary marks the result delivered.",
parameters: OrchestratorMcpTaskStatusInput,
success: OrchestratorMcpDelegateTaskResult,
failure: OrchestratorMcpFailure,
Expand Down
23 changes: 23 additions & 0 deletions apps/server/src/mcp/toolkits/project/handlers.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import {
type Project as ProjectRecord,
type ModelSelection,
type RuntimeMode,
type OrchestrationV2DelegatedFrom,
type OrchestrationV2ThreadShell,
ThreadId,
} from "@t3tools/contracts";
Expand Down Expand Up @@ -56,6 +57,7 @@ const clientLaunchHarness = (input: {
readonly overrideModel?: ModelSelection;
readonly launched: Array<ThreadLaunch.ThreadLaunchInput>;
readonly clientSessionId?: string;
readonly linkedSender?: OrchestrationV2DelegatedFrom;
readonly workspaceRoot?: string;
readonly checkWorktreeBase?: ThreadLaunch.ThreadLaunchService["Service"]["checkWorktreeBase"];
readonly hostedAppUrl?: string;
Expand Down Expand Up @@ -104,6 +106,9 @@ const clientLaunchHarness = (input: {
client: {
sessionId: clientSessionId,
label: "Claude Code",
...(input.linkedSender === undefined
? {}
: { linked: true, senderThread: input.linkedSender }),
access: input.runtimeModeCeiling,
hostedAppUrl: input.hostedAppUrl,
},
Expand Down Expand Up @@ -208,6 +213,7 @@ it.effect(
readonly targeted?: false;
readonly overrideModel?: ModelSelection;
readonly hostedAppUrl?: string;
readonly delegatedFrom?: OrchestrationV2DelegatedFrom;
readonly refusedByCeiling?: true;
},
) {
Expand All @@ -217,6 +223,7 @@ it.effect(
runtimeModeCeiling,
defaultRuntimeMode,
launched,
...(input.delegatedFrom === undefined ? {} : { linkedSender: input.delegatedFrom }),
...(overrideModel === undefined ? {} : { overrideModel }),
...(hostedAppUrl === undefined ? {} : { hostedAppUrl }),
...(refusedByCeiling === undefined ? {} : { refusedByCeiling }),
Expand Down Expand Up @@ -246,6 +253,22 @@ it.effect(
expect(belowCeiling.launched[0]?.runtimeMode).toBe("approval-required");
expect(belowCeiling.launched[0]?.initialMessage?.senderThreadId).toBeUndefined();

const parent = {
environmentId: EnvironmentId.make("remote"),
threadId: ThreadId.make("parent"),
title: "Coordinator",
};
const delegated = yield* launchWith("full-access", "approval-required", {
title: "Review",
message: "Review the diff",
delegatedFrom: parent,
});
expect(delegated.launched[0]?.initialMessage?.linkedSender).toEqual({
...parent,
fromOriginatingLink: true,
});
expect(delegated.launched[0]?.delegatedFrom).toEqual(parent);

const aboveCeiling = yield* launchWith("auto-accept-edits", "full-access", {
title: "Fix",
hostedAppUrl: "https://t3.example.com",
Expand Down
17 changes: 15 additions & 2 deletions apps/server/src/mcp/toolkits/project/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -392,6 +392,19 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
)?.supportedRuntimeModes,
});
}
const { linkedSender } = McpInvocationContext.linkedMessageSender(scope.client, linkOrigin);
const declaredParent = input.delegatedFrom;
const delegatedFrom =
caller === undefined &&
linkedSender?.fromOriginatingLink === true &&
declaredParent?.environmentId === linkedSender.environmentId &&
declaredParent.threadId === linkedSender.threadId
? {
environmentId: linkedSender.environmentId,
threadId: linkedSender.threadId,
title: linkedSender.title,
}
: undefined;
const result = yield* ThreadMessageIntake.launchThread({
commandId,
threadId,
Expand All @@ -407,15 +420,15 @@ export const layer = McpToolAccess.toLayer(ProjectToolkit, {
initialMessage: {
messageId,
...(caller === undefined ? {} : { senderThreadId: caller.id }),
...(linkedSender === undefined ? {} : { linkedSender }),
text: input.message ?? "",
attachments,
},
}),
createdBy: "agent",
creationSource: "mcp",
...(linkOrigin === undefined ? {} : { linkOrigin }),
// Kept only alongside linkOrigin: thread.create drops it otherwise.
...(input.delegatedFrom === undefined ? {} : { delegatedFrom: input.delegatedFrom }),
...(delegatedFrom === undefined ? {} : { delegatedFrom }),
}).pipe(
Effect.mapError((error) => {
if (error._tag === "AttachmentClaimError") {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ const withBrowserRules = (rules: ReadonlyArray<unknown>, browser: ReadonlyArray<
const TITLE = "Prime check";
const sessionInfo = (overrides: Record<string, unknown> = {}) => ({
id: SESSION,
agent: "build",
title: TITLE,
permissions: t3Rules,
projectID: "global",
Expand Down Expand Up @@ -344,6 +345,7 @@ const resumed = (
readonly version?: "2.2.1" | "2.2.5" | "2.2.6";
readonly shellRecovery?: ReadonlyArray<ProviderReplayEntry>;
readonly lastRunOrdinal?: number;
readonly missingAgent?: boolean;
readonly pendingBackgroundTasks?: OrchestrationV2ProviderThread["pendingBackgroundTasks"];
readonly goal?: OrchestrationV2ProviderThread["goal"];
readonly contextUsage?: OrchestrationV2ProviderThread["contextUsage"];
Expand All @@ -365,7 +367,7 @@ const resumed = (
[
...opening,
out("session.get", { sessionID: SESSION }),
replyData("session.get", sessionInfo()),
replyData("session.get", sessionInfo(options?.missingAgent ? { agent: undefined } : {})),
...noOpenRequests,
...(options?.version === "2.2.5" || options?.version === "2.2.6"
? [out("rpc.call", "<any>"), reply("rpc.call", { output: null })]
Expand Down Expand Up @@ -507,6 +509,26 @@ const nativeGoal = (status: "active" | "paused" | "complete") => ({
});

it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
it.effect(
"selects build before prompting a resumed session that uses the native default agent",
() =>
Effect.gen(function* () {
const { runtime, thread } = yield* resumed(
[
out("session.switchAgent", { sessionID: SESSION, agent: "build" }),
reply("session.switchAgent", null),
out("session.prompt", { sessionID: SESSION, text: "<any>" }),
promptAccepted,
event("session.execution.succeeded", { sessionID: SESSION }),
],
{ missingAgent: true },
);
const terminal = yield* terminalOf(runtime).pipe(Effect.forkScoped);
yield* runtime.startTurn(turnInput(thread));
assert.equal((yield* Fiber.join(terminal))?.status, "completed");
}),
);

it.effect("switches the session's model and variant before a turn that changed them", () =>
Effect.gen(function* () {
const { runtime, thread } = yield* resumed([
Expand Down Expand Up @@ -3701,6 +3723,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
out("agent.list", "<any>"),
reply("agent.list", agentList),
out("session.create", {
agent: "build",
location: { directory: WORK },
model: { providerID: "opencode", id: "big-pickle" },
permissions: supervisedRules,
Expand Down Expand Up @@ -6805,6 +6828,7 @@ it.layer(McpProviderSessions.layer)("OpenCode2 adapter", (it) => {
})),
}),
out("session.create", {
agent: "build",
location: { directory: custom },
model: { providerID: "opencode", id: "big-pickle" },
permissions: t3Rules,
Expand Down
10 changes: 7 additions & 3 deletions apps/server/src/orchestration-v2/ContextHandoffBudget.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,9 @@ const decodeHandoff = Schema.decodeUnknownSync(OrchestrationV2ContextHandoff);

const now = DateTime.makeUnsafe("2026-09-17T00:00:00Z");
const threadId = ThreadId.make("thread:handoff");
const thread = {
lineage: { relationshipToParent: null, parentThreadId: null, rootThreadId: threadId },
};
const summaryScope = { projectId: ProjectId.make("project:handoff"), threadId };
const providerThread: OrchestrationV2ProviderThread = {
id: ProviderThreadId.make("provider-thread:target"),
Expand Down Expand Up @@ -208,7 +211,7 @@ describe("handoff budget", () => {
assert.include(imageCommand!.text, "image/png");
assert.include(imageCommand!.text, "read screenshot.png");
const native = nativeContextHistory(
{ runs: [], attempts: [], providerTurns: [], contextHandoffs: [] },
{ thread, runs: [], attempts: [], providerTurns: [], contextHandoffs: [] },
providerThread,
);
native.nativeInputRunIds.add(base.runId);
Expand Down Expand Up @@ -349,6 +352,7 @@ describe("handoff budget", () => {
inputIntent: "turn_start",
attachments: [],
})!;
assert.equal(peer.text, peerText);
assert.deepEqual(peer.provenance, { createdBy: "agent", creationSource: "mcp", ...sender });
for (const rendered of [
renderHistory([peer], "Historical context"),
Expand Down Expand Up @@ -707,7 +711,7 @@ describe("handoff delivery", () => {
const first = yield* deliver();
assert.equal(
nativeContextHistory(
{ runs: [], attempts: [], providerTurns: [], contextHandoffs: durable },
{ thread, runs: [], attempts: [], providerTurns: [], contextHandoffs: durable },
providerThread,
).estimate([tail]),
native ? deliveredCost : 0,
Expand All @@ -720,7 +724,7 @@ describe("handoff delivery", () => {
target = providerThread,
) =>
nativeContextHistory(
{ runs: [], attempts: [], providerTurns: [], contextHandoffs },
{ thread, runs: [], attempts: [], providerTurns: [], contextHandoffs },
target,
);
const estimate = occupancy(durable.map((entry) => decodeHandoff(entry))).estimate([tail]);
Expand Down
Loading
Loading