@devries-cameron20 / t3code-1 / commits / 0c6d0ee862
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): steering a running turn carries MCP app model context (#38554)

Julius Marminge committed Nov 18, 2026 at 02:58 UTC 0c6d0ee862cf84fe107e3085c03edc63485eee8b
12 files changed +422 -131
apps/server/src/mcpApps/McpAppModelContext.ts
+23
@@ -38,6 +38,29 @@ export class McpAppModelContext extends Context.Service<
38 }
39 >()("t3/mcpApps/McpAppModelContext") {}
40
41 +/** The thread's notes as a provider turn or steer sends them; a failed read sends none. */
42 +export const forProvider = Effect.fn("McpAppModelContext.forProvider")(function* (
43 + modelContext: McpAppModelContext["Service"],
44 + threadId: ThreadId,
45 +) {
46 + const entries = yield* modelContext
47 + .forThread(threadId)
48 + .pipe(
49 + Effect.catch((cause) =>
50 + Effect.logWarning("Failed to read MCP app model context.", { cause }).pipe(
51 + Effect.as([] as ReadonlyArray<McpAppModelContextEntry>),
52 + ),
53 + ),
54 + );
55 + return entries.map((entry) => ({
56 + // The item id alone is unique and needs no escaping; server and
57 + // tool names are free text that would break the tag Codex wraps
58 + // the context in.
59 + key: `mcp_app_${entry.itemId.replace(/[^\w.-]/g, "_")}`,
60 + text: entry.text,
61 + }));
62 +});
63 +
64 export const layer = Layer.effect(
65 McpAppModelContext,
66 Effect.gen(function* () {
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+33 -3
@@ -6860,10 +6860,34 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6860 }),
6861 appContext: [{ key: "mcp_app_item-1", text: note }],
6862 });
6863 + return lastOffered();
6864 + });
6865 + const lastOffered = () => {
6866 const content = harness.offeredMessages.at(-1)?.message.content;
6867 return typeof content === "string"
6868 ? content
6869 : (content ?? []).map((block) => (block.type === "text" ? block.text : "")).join("\n");
6870 + };
6871 + const steer = Effect.fnUntraced(function* (ordinal: number, note: string) {
6872 + const attemptId = `mcp-app-context-${ordinal}`;
6873 + yield* harness.runtime.steerTurn({
6874 + threadId: harness.threadId,
6875 + runId: RunId.make(`run-${attemptId}`),
6876 + providerThread: harness.providerThread,
6877 + providerTurnId: (yield* IdAllocator.IdAllocatorV2).derive.providerTurn({
6878 + driver: ClaudeAdapterV2.CLAUDE_PROVIDER,
6879 + nativeTurnId: `turn:${attemptId}`,
6880 + }),
6881 + message: {
6882 + createdBy: "user",
6883 + creationSource: "web",
6884 + messageId: MessageId.make(`steer-${attemptId}-${harness.offeredMessages.length}`),
6885 + text: "What did the app report now?",
6886 + attachments: [],
6887 + },
6888 + appContext: [{ key: "mcp_app_item-1", text: note }],
6889 + });
6890 + return lastOffered();
6891 });
6892 const finishTurn = Effect.fnUntraced(function* (ordinal: number) {
6893 yield* harness.offerAndWait(
@@ -6886,8 +6910,14 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6910 yield* finishTurn(1);
6911 // Already in Claude's history: resending it every turn would only grow the context.
6912 assert.notInclude(yield* runTurn(2, "Created Jira issue PROJ-42"), "PROJ-42");
6913 + // regression: #38541 a note the app changes mid-turn rides on the next steer, once.
6914 + assert.notInclude(yield* steer(2, "Created Jira issue PROJ-42"), "PROJ-42");
6915 + assert.include(yield* steer(2, "Created Jira issue PROJ-44"), "PROJ-44");
6916 + assert.notInclude(yield* steer(2, "Created Jira issue PROJ-44"), "PROJ-44");
6917 yield* finishTurn(2);
6890 - assert.include(yield* runTurn(3, "Created Jira issue PROJ-43"), "PROJ-43");
6918 + assert.notInclude(yield* runTurn(3, "Created Jira issue PROJ-44"), "PROJ-44");
6919 + yield* finishTurn(3);
6920 + assert.include(yield* runTurn(4, "Created Jira issue PROJ-43"), "PROJ-43");
6921 yield* harness.offerAndWait(
6922 claudeSdkFrame({
6923 type: "system",
@@ -6897,9 +6927,9 @@ describe("ClaudeAdapterV2 background wake turns", () => {
6927 session_id: WAKE_NATIVE_SESSION,
6928 }),
6929 );
6900 - yield* finishTurn(3);
6930 + yield* finishTurn(4);
6931 // Compaction summarizes the note away, so the next turn carries it again.
6902 - assert.include(yield* runTurn(4, "Created Jira issue PROJ-43"), "PROJ-43");
6932 + assert.include(yield* runTurn(5, "Created Jira issue PROJ-43"), "PROJ-43");
6933 }).pipe(
6934 Effect.provide(
6935 Layer.mergeAll(
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+24 -11
@@ -13787,7 +13787,7 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13787 existing.openedPermissionMode === currentTurn.queryPolicy.permissionMode)
13788 ? steerSelection
13789 : undefined;
13790 - const userMessage = yield* makeClaudeUserMessageWithAttachments({
13790 + const steerMessage = yield* makeClaudeUserMessageWithAttachments({
13791 text: applyClaudePromptEffortPrefix(
13792 turnInput.message.text,
13793 (
@@ -13806,6 +13806,27 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13806 Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
13807 Effect.provideService(Path.Path, path),
13808 );
13809 + // Notes this turn's prompt or an earlier steer already carried are not sent again.
13810 + const appContext = turnInput.appContext ?? [];
13811 + const seenAppContext =
13812 + currentTurn.appContextOffered ?? deliveredAppContext.get(existing.nativeThreadId);
13813 + const userMessage = withClaudeAppContext(
13814 + steerMessage,
13815 + appContext.filter((entry) => seenAppContext?.get(entry.key) !== entry.text),
13816 + pdfReservation,
13817 + );
13818 + // `offer` may call this twice; a second call must not restore notes compaction cleared.
13819 + let offerCommitted = false;
13820 + const commitOffer = () => {
13821 + if (offerCommitted) return;
13822 + offerCommitted = true;
13823 + pdfReservation.commit();
13824 + if (userMessage !== steerMessage) {
13825 + currentTurn.appContextOffered = new Map(
13826 + appContext.map((entry) => [entry.key, entry.text]),
13827 + );
13828 + }
13829 + };
13830 yield* backgroundForegroundSubagents(existing, backgroundDeadline);
13831 if (liveSteerSelection !== undefined) {
13832 yield* applySelectionLive(existing, liveSteerSelection);
@@ -13839,16 +13860,8 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
13860 });
13861 yield* emitSteerStatus(currentTurn, messageId, "pending");
13862 yield* Effect.uninterruptibleMask((restore) =>
13842 - restore(
13843 - existing.query.offer(userMessage, () => {
13844 - pdfReservation.commit();
13845 - }),
13846 - ).pipe(
13847 - Effect.tap(() =>
13848 - Effect.sync(() => {
13849 - pdfReservation.commit();
13850 - }),
13851 - ),
13863 + restore(existing.query.offer(userMessage, commitOffer)).pipe(
13864 + Effect.tap(() => Effect.sync(commitOffer)),
13865 ),
13866 ).pipe(
13867 Effect.onError(() =>
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+91
@@ -1915,6 +1915,97 @@ describe("CodexAdapterV2 post-settle continuation", () => {
1915 ),
1916 );
1917
1918 + // regression: #38541 an MCP app note that changes mid-turn reaches the next steer, once.
1919 + it.effect("steers carry MCP app notes Codex has not been sent", () =>
1920 + Effect.gen(function* () {
1921 + const nativeThreadId = "steer-app-context-thread";
1922 + const nativeTurnId = "steer-app-context-turn";
1923 + const note = "<external_mcp_app_item-1>Pressed: blue</external_mcp_app_item-1>";
1924 + const steerFrame = (id: number, input: ReadonlyArray<string>) =>
1925 + [
1926 + {
1927 + type: "expect_outbound",
1928 + label: "turn/steer",
1929 + frame: {
1930 + id,
1931 + method: "turn/steer",
1932 + params: {
1933 + threadId: nativeThreadId,
1934 + expectedTurnId: nativeTurnId,
1935 + input: input.map((text) => ({ type: "text", text })),
1936 + },
1937 + },
1938 + },
1939 + { type: "emit_inbound", frame: { id, result: { turnId: nativeTurnId } } },
1940 + ] as const;
1941 + const harness = yield* makeCodexReplayHarness(
1942 + makeCodexReplayTranscript({
1943 + scenario: "steer-app-context",
1944 + entries: [
1945 + ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Work." }),
1946 + ...steerFrame(4, [note, "What did the app report?"]),
1947 + ...steerFrame(5, ["And now?"]),
1948 + {
1949 + type: "emit_inbound",
1950 + frame: {
1951 + method: "turn/completed",
1952 + params: {
1953 + threadId: nativeThreadId,
1954 + turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
1955 + },
1956 + },
1957 + },
1958 + ],
1959 + }),
1960 + );
1961 + const turnInput = makeCodexTestTurnInput({
1962 + threadId: harness.threadId,
1963 + providerThread: harness.providerThread,
1964 + now: yield* DateTime.now,
1965 + attemptId: RunAttemptId.make("steer-app-context-attempt"),
1966 + text: "Work.",
1967 + });
1968 + yield* harness.runtime.startTurn(turnInput);
1969 + yield* harness.until(() =>
1970 + harness.events.some(
1971 + (event) =>
1972 + event.type === "provider_turn.updated" &&
1973 + event.providerTurn.nativeTurnRef?.nativeId === nativeTurnId,
1974 + ),
1975 + );
1976 + const providerTurnId = harness.events.flatMap((event) =>
1977 + event.type === "provider_turn.updated" ? [event.providerTurn.id] : [],
1978 + )[0];
1979 + assert.isDefined(providerTurnId);
1980 + if (providerTurnId === undefined) return;
1981 + const appContext = [{ key: "mcp_app_item-1", text: "Pressed: blue" }];
1982 + yield* harness.runtime.steerTurn({
1983 + ...turnInput,
1984 + providerTurnId,
1985 + appContext,
1986 + message: { ...turnInput.message, text: "What did the app report?" },
1987 + });
1988 + yield* harness.runtime.steerTurn({
1989 + ...turnInput,
1990 + providerTurnId,
1991 + appContext,
1992 + message: { ...turnInput.message, text: "And now?" },
1993 + });
1994 + yield* harness.firstTerminal;
1995 + assert.equal(harness.terminalEvents()[0]?.status, "completed");
1996 + }).pipe(
1997 + Effect.scoped,
1998 + Effect.provide(
1999 + Layer.mergeAll(
2000 + IdAllocator.layer,
2001 + McpProviderSessions.layer,
2002 + NodeServices.layer,
2003 + NodeCrypto.layer,
2004 + ),
2005 + ),
2006 + ),
2007 + );
2008 +
2009 it.effect("a speed change with no message updates Codex's next-turn settings", () =>
2010 Effect.gen(function* () {
2011 const nativeThreadId = "picker-tier-thread";
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+28 -1
@@ -8150,11 +8150,38 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
8150
8151 yield* applyServiceTier(threadId, turnInput.modelSelection);
8152 const codexInput = yield* toCodexInput(turnInput);
8153 + // turn/steer takes no additionalContext, so notes the thread has not been sent go
8154 + // as quoted user input, the way restoreAdditionalContext resends them.
8155 + const sentContext = (yield* Ref.get(additionalContextByThread)).get(threadId);
8156 + const unsentNotes = (turnInput.appContext ?? []).filter(
8157 + (entry) => sentContext?.[entry.key]?.value !== entry.text,
8158 + );
8159 yield* client.request("turn/steer", {
8160 expectedTurnId: activeTurn.nativeTurnId,
8155 - input: codexInput,
8161 + input: [
8162 + ...unsentNotes.map((entry) => ({
8163 + type: "text" as const,
8164 + text: `<external_${entry.key}>${entry.text}</external_${entry.key}>`,
8165 + })),
8166 + ...codexInput,
8167 + ],
8168 threadId,
8169 });
8170 + if (unsentNotes.length > 0) {
8171 + yield* Ref.update(additionalContextByThread, (current) => {
8172 + const next = new Map(current);
8173 + next.set(threadId, {
8174 + ...current.get(threadId),
8175 + ...Object.fromEntries(
8176 + unsentNotes.map((entry) => [
8177 + entry.key,
8178 + { kind: "untrusted" as const, value: entry.text },
8179 + ]),
8180 + ),
8181 + });
8182 + return next;
8183 + });
8184 + }
8185 },
8186 (effect, turnInput) =>
8187 effect.pipe(
apps/server/src/orchestration-v2/ProjectionControlReads.test.ts
+4 -1
@@ -24,6 +24,7 @@ import * as Queue from "effect/Queue";
24 import * as Stream from "effect/Stream";
25 import * as TestClock from "effect/testing/TestClock";
26 import * as SqlClient from "effect/sql/SqlClient";
27 +import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";
28 import * as SqlitePersistence from "../persistence/Sqlite.ts";
29 import * as EventSink from "./EventSink.ts";
30 import * as ProjectionStore from "./ProjectionStore.ts";
@@ -393,7 +394,9 @@ it.effect.each(storageCases)(
394 }).pipe(
395 Effect.provide(
396 Layer.merge(ProviderTurnControlService.layer, RuntimeRequestService.layer).pipe(
396 - Layer.provide(Layer.merge(layerSessions, layerEvents)),
397 + Layer.provide(
398 + Layer.mergeAll(layerSessions, layerEvents, McpAppModelContext.layerEmpty),
399 + ),
400 ),
401 ),
402 );
apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts
+193 -98
@@ -1,8 +1,10 @@
1 import { assert, it } from "@effect/vitest";
2 import {
3 + MessageId,
4 type ModelSelection,
5 NodeId,
6 type OrchestrationV2ProviderThread,
7 + type OrchestrationV2Run,
8 type OrchestrationV2ThreadProjection,
9 ProjectId,
10 ProviderDriverKind,
@@ -23,6 +25,7 @@ import * as Ref from "effect/Ref";
25 import * as Stream from "effect/Stream";
26
27 import { CodexProviderCapabilitiesV2 } from "./Adapters/CodexAdapterV2.ts";
28 +import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";
29 import * as EventSink from "./EventSink.ts";
30 import * as ProjectionStore from "./ProjectionStore.ts";
31 import type * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
@@ -123,6 +126,102 @@ function makeProjection(input: {
126 };
127 }
128
129 +function layerProjectionStore(
130 + getProviderControlContext: ProjectionStore.ProjectionStoreV2["Service"]["getProviderControlContext"],
131 +) {
132 + return Layer.succeed(
133 + ProjectionStore.ProjectionStoreV2,
134 + ProjectionStore.ProjectionStoreV2.of({
135 + apply: () => Effect.void,
136 + getLimitRecoveryCandidates: () => Effect.die("unused getLimitRecoveryCandidates"),
137 + getLimitRecoveryWakeAt: () => Effect.die("unused getLimitRecoveryWakeAt"),
138 + getOpenRemoteDelegatedTasks: Effect.die("unused getOpenRemoteDelegatedTasks"),
139 + getAgentAwarenessSnapshot: () => Effect.die("unused awareness snapshot"),
140 + getShellSnapshot: () => Effect.die("unused getShellSnapshot"),
141 + listActiveSubagentThreadIds: () => Effect.die("unused listActiveSubagentThreadIds"),
142 + countThreads: () => Effect.die("unused countThreads"),
143 + listActiveShellIndex: () => Effect.die("unused listActiveShellIndex"),
144 + listActiveThreads: () => Effect.die("unused listActiveThreads"),
145 + listOlderSettledThreads: () => Effect.die("unused listOlderSettledThreads"),
146 + readShellSnapshot: () => Effect.die("unused readShellSnapshot"),
147 + getThreadShell: () => Effect.die("unused getThreadShell"),
148 + getThreadTitles: () => Effect.die("unused getThreadTitles"),
149 + getThreadLinkMetadata: () => Effect.die("unused getThreadLinkMetadata"),
150 + findGuestShareThreadId: () => Effect.die("unused findGuestShareThreadId"),
151 + getThread: () => Effect.die("unused getThread"),
152 + findThread: () => Effect.die("unused findThread"),
153 + getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"),
154 + getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"),
155 + getThreadWorktreePaths: () => Effect.die("unused getThreadWorktreePaths"),
156 + getThreadProjection: () => Effect.die("control effects must not load transcript"),
157 + getTurnStartContext: () => Effect.die("unused"),
158 + getTurnStartHistory: () => Effect.die("unused"),
159 + getRuntimeRecoveryProjection: () => Effect.die("unused getRuntimeRecoveryProjection"),
160 + getPlan: () => Effect.die("unused"),
161 + hasUnpairedRunInterruptRequest: () => Effect.die("unused interrupt read"),
162 + hasRunInterruptRequest: () => Effect.die("unused stop read"),
163 + getRunProviderRecords: () => Effect.die("unused run provider read"),
164 + getThreadAttachmentIds: () => Effect.die("Unused attachment lookup"),
165 + searchThread: () => Effect.die("unused"),
166 + searchThreadStream: () => Stream.empty,
167 + getThreadHistoryPage: () => Effect.die("unused"),
168 + getTimelinePage: () => Effect.die("Unused timeline read"),
169 + getMessageCount: () => Effect.die("unused message count"),
170 + getTranscriptByteFloor: () => Effect.die("unused transcript byte floor"),
171 + hasPendingDelegatedCompletion: () => Effect.die("unused hasPendingDelegatedCompletion"),
172 + getSubagentCount: () => Effect.die("unused subagent count"),
173 + getRunCount: () => Effect.die("unused run count"),
174 + listAppOwnedChildThreadIds: () => Effect.die("unused listAppOwnedChildThreadIds"),
175 + getNextTurnItemOrdinal: () => Effect.die("unused ordinal read"),
176 + getTurnItem: () => Effect.die("unused turn item read"),
177 + getMessagesById: () => Effect.die("unused getMessagesById"),
178 + getThreadRecords: () => Effect.die("unused record read"),
179 + getRuntimeRequest: () => Effect.die("unused getRuntimeRequest"),
180 + getRunningTurnContext: () => Effect.die("unused getRunningTurnContext"),
181 + getThreadProviderContext: () => Effect.die("unused getThreadProviderContext"),
182 + getRuntimeResponseContext: () => Effect.die("unused getRuntimeResponseContext"),
183 + getPendingNativeUserInputs: () => Effect.die("unused getPendingNativeUserInputs"),
184 + getProviderControlContext,
185 + getCheckpointContext: () => Effect.die("not used"),
186 + getCheckpointRollbackContext: () => Effect.die("unused rollback context"),
187 + getCheckpointCaptureContext: () => Effect.die("not used"),
188 + getRunMessage: () => Effect.die("not used"),
189 + getRun: () => Effect.die("not used"),
190 + isNodeStored: () => Effect.die("not used"),
191 + canStartQueuedRun: () => Effect.die("not used"),
192 + getHeldQueuedRuns: () => Effect.die("not used"),
193 + getRecoveryThreadIds: () => Effect.die("unused getRecoveryThreadIds"),
194 + getUnreadableThreadIds: () => Effect.die("unused getUnreadableThreadIds"),
195 + getThreadSnapshot: () => Effect.die("unused getThreadSnapshot"),
196 + getThreadSnapshotWindow: () => Effect.die("unused getThreadSnapshotWindow"),
197 + getPullRequestSnapshot: () => Effect.die("unused getPullRequestSnapshot"),
198 + }),
199 + );
200 +}
201 +
202 +function layerSessions(
203 + liveSessionId: ProviderSessionId,
204 + runtime: ProviderAdapter.ProviderAdapterV2SessionRuntime,
205 +) {
206 + return Layer.succeed(
207 + ProviderSessionManager.ProviderSessionManagerV2,
208 + ProviderSessionManager.ProviderSessionManagerV2.of({
209 + shutdown: Effect.void,
210 + open: () => Effect.die("unused open"),
211 + get: (providerSessionId) =>
212 + Effect.succeed(providerSessionId === liveSessionId ? Option.some(runtime) : Option.none()),
213 + isLive: (providerSessionId) => Effect.succeed(providerSessionId === liveSessionId),
214 + close: () => Effect.void,
215 + closeInstance: () => Effect.void,
216 + release: () => Effect.void,
217 + detach: () => Effect.void,
218 + otherWorkingThreads: () => Effect.succeed([]),
219 + releaseUnlessBusy: () => Effect.succeed(true),
220 + subscribePromptSuggestion: () => Stream.empty,
221 + }),
222 + );
223 +}
224 +
225 it.effect(
226 "interrupts the historical session only for the exact committed restart replacement",
227 () =>
@@ -206,112 +305,27 @@ it.effect(
305 rollbackThread: () => Effect.die("unused rollbackThread"),
306 forkThread: () => Effect.die("unused forkThread"),
307 };
209 - const layerProjection = Layer.succeed(
210 - ProjectionStore.ProjectionStoreV2,
211 - ProjectionStore.ProjectionStoreV2.of({
212 - apply: () => Effect.void,
213 - getLimitRecoveryCandidates: () => Effect.die("unused getLimitRecoveryCandidates"),
214 - getLimitRecoveryWakeAt: () => Effect.die("unused getLimitRecoveryWakeAt"),
215 - getOpenRemoteDelegatedTasks: Effect.die("unused getOpenRemoteDelegatedTasks"),
216 - getAgentAwarenessSnapshot: () => Effect.die("unused awareness snapshot"),
217 - getShellSnapshot: () => Effect.die("unused getShellSnapshot"),
218 - listActiveSubagentThreadIds: () => Effect.die("unused listActiveSubagentThreadIds"),
219 - countThreads: () => Effect.die("unused countThreads"),
220 - listActiveShellIndex: () => Effect.die("unused listActiveShellIndex"),
221 - listActiveThreads: () => Effect.die("unused listActiveThreads"),
222 - listOlderSettledThreads: () => Effect.die("unused listOlderSettledThreads"),
223 - readShellSnapshot: () => Effect.die("unused readShellSnapshot"),
224 - getThreadShell: () => Effect.die("unused getThreadShell"),
225 - getThreadTitles: () => Effect.die("unused getThreadTitles"),
226 - getThreadLinkMetadata: () => Effect.die("unused getThreadLinkMetadata"),
227 - findGuestShareThreadId: () => Effect.die("unused findGuestShareThreadId"),
228 - getThread: () => Ref.get(projection).pipe(Effect.map((state) => state.thread)),
229 - findThread: () => Effect.die("unused findThread"),
230 - getSettlementCandidates: () => Effect.die("unused getSettlementCandidates"),
231 - getThreadsWithPullRequests: () => Effect.die("unused getThreadsWithPullRequests"),
232 - getThreadWorktreePaths: () => Effect.die("unused getThreadWorktreePaths"),
233 - getThreadProjection: () => Effect.die("control effects must not load transcript"),
234 - getTurnStartContext: () => Effect.die("unused"),
235 - getTurnStartHistory: () => Effect.die("unused"),
236 - getRuntimeRecoveryProjection: () => Effect.die("unused getRuntimeRecoveryProjection"),
237 - getPlan: () => Effect.die("unused"),
238 - hasUnpairedRunInterruptRequest: () => Effect.die("unused interrupt read"),
239 - hasRunInterruptRequest: () => Effect.die("unused stop read"),
240 - getRunProviderRecords: () => Effect.die("unused run provider read"),
241 - getThreadAttachmentIds: () => Effect.die("Unused attachment lookup"),
242 - searchThread: () => Effect.die("unused"),
243 - searchThreadStream: () => Stream.empty,
244 - getThreadHistoryPage: () => Effect.die("unused"),
245 - getTimelinePage: () => Effect.die("Unused timeline read"),
246 - getMessageCount: () => Effect.die("unused message count"),
247 - getTranscriptByteFloor: () => Effect.die("unused transcript byte floor"),
248 - hasPendingDelegatedCompletion: () => Effect.die("unused hasPendingDelegatedCompletion"),
249 - getSubagentCount: () => Effect.die("unused subagent count"),
250 - getRunCount: () => Effect.die("unused run count"),
251 - listAppOwnedChildThreadIds: () => Effect.die("unused listAppOwnedChildThreadIds"),
252 - getNextTurnItemOrdinal: () => Effect.die("unused ordinal read"),
253 - getTurnItem: () => Effect.die("unused turn item read"),
254 - getMessagesById: () => Effect.die("unused getMessagesById"),
255 - getThreadRecords: () => Effect.die("unused record read"),
256 - getRuntimeRequest: () => Effect.die("unused getRuntimeRequest"),
257 - getRunningTurnContext: () => Effect.die("unused getRunningTurnContext"),
258 - getThreadProviderContext: () => Effect.die("unused getThreadProviderContext"),
259 - getRuntimeResponseContext: () => Effect.die("unused getRuntimeResponseContext"),
260 - getPendingNativeUserInputs: () => Effect.die("unused getPendingNativeUserInputs"),
261 - getProviderControlContext: (_threadId, target) =>
262 - Ref.get(projection).pipe(
263 - Effect.map((current) => ({
264 - providerThread: current.providerThreads.find(
265 - (thread) => thread.id === target.providerThreadId,
266 - ),
267 - providerTurn: current.providerTurns.find(
268 - (turn) => turn.id === target.providerTurnId,
269 - ),
270 - attempt: current.attempts.find((attempt) => attempt.id === target.attemptId),
271 - message: undefined,
272 - run: undefined,
273 - })),
274 - ),
275 - getCheckpointContext: () => Effect.die("not used"),
276 - getCheckpointRollbackContext: () => Effect.die("unused rollback context"),
277 - getCheckpointCaptureContext: () => Effect.die("not used"),
278 - getRunMessage: () => Effect.die("not used"),
279 - getRun: () => Effect.die("not used"),
280 - isNodeStored: () => Effect.die("not used"),
281 - canStartQueuedRun: () => Effect.die("not used"),
282 - getHeldQueuedRuns: () => Effect.die("not used"),
283 - getRecoveryThreadIds: () => Effect.die("unused getRecoveryThreadIds"),
284 - getUnreadableThreadIds: () => Effect.die("unused getUnreadableThreadIds"),
285 - getThreadSnapshot: () => Effect.die("unused getThreadSnapshot"),
286 - getThreadSnapshotWindow: () => Effect.die("unused getThreadSnapshotWindow"),
287 - getPullRequestSnapshot: () => Effect.die("unused getPullRequestSnapshot"),
288 - }),
289 - );
290 - const layerSessionManager = Layer.succeed(
291 - ProviderSessionManager.ProviderSessionManagerV2,
292 - ProviderSessionManager.ProviderSessionManagerV2.of({
293 - shutdown: Effect.void,
294 - open: () => Effect.die("unused open"),
295 - get: (providerSessionId) =>
296 - Effect.succeed(
297 - providerSessionId === oldSessionId ? Option.some(runtime) : Option.none(),
308 + const layerProjection = layerProjectionStore((_threadId, target) =>
309 + Ref.get(projection).pipe(
310 + Effect.map((current) => ({
311 + providerThread: current.providerThreads.find(
312 + (thread) => thread.id === target.providerThreadId,
313 ),
299 - isLive: (providerSessionId) => Effect.succeed(providerSessionId === oldSessionId),
300 - close: () => Effect.void,
301 - closeInstance: () => Effect.void,
302 - release: () => Effect.void,
303 - detach: () => Effect.void,
304 - otherWorkingThreads: () => Effect.succeed([]),
305 - releaseUnlessBusy: () => Effect.succeed(true),
306 - subscribePromptSuggestion: () => Stream.empty,
307 - }),
314 + providerTurn: current.providerTurns.find((turn) => turn.id === target.providerTurnId),
315 + attempt: current.attempts.find((attempt) => attempt.id === target.attemptId),
316 + message: undefined,
317 + run: undefined,
318 + })),
319 + ),
320 );
321 + const layerSessionManager = layerSessions(oldSessionId, runtime);
322 const layerControl = ProviderTurnControlService.layer.pipe(
323 Layer.provide(
324 Layer.mergeAll(
325 layerProjection,
326 layerSessionManager,
327 Layer.mock(EventSink.EventSinkV2)({}),
328 + McpAppModelContext.layerEmpty,
329 ),
330 ),
331 );
@@ -362,3 +376,84 @@ it.effect(
376 assert.equal(interrupted?.nativeThreadRef?.nativeId, "native-thread:restart-session");
377 }),
378 );
379 +
380 +it.effect("steers a running turn with the thread's MCP app model context", () =>
381 + Effect.gen(function* () {
382 + const now = yield* DateTime.now;
383 + const threadId = ThreadId.make("thread:steer-app-context");
384 + const sessionId = ProviderSessionId.make("provider-session:steer-app-context");
385 + const providerTurnId = ProviderTurnId.make("provider-turn:steer-app-context");
386 + const attemptId = RunAttemptId.make("run-attempt:steer-app-context");
387 + const providerThread = {
388 + id: ProviderThreadId.make("provider-thread:steer-app-context"),
389 + driver,
390 + providerInstanceId,
391 + providerSessionId: sessionId,
392 + } as OrchestrationV2ProviderThread;
393 + const projection = makeProjection({ now, threadId, providerThread, providerTurnId, attemptId });
394 + const steered: Array<ProviderAdapter.ProviderAdapterV2SteerInput> = [];
395 + const runtime = {
396 + instanceId: providerInstanceId,
397 + driver,
398 + providerSessionId: sessionId,
399 + steerTurn: (input: ProviderAdapter.ProviderAdapterV2SteerInput) =>
400 + Effect.sync(() => void steered.push(input)),
401 + } as unknown as ProviderAdapter.ProviderAdapterV2SessionRuntime;
402 + const layerControl = ProviderTurnControlService.layer.pipe(
403 + Layer.provide(
404 + Layer.mergeAll(
405 + layerProjectionStore(() =>
406 + Effect.succeed({
407 + providerThread,
408 + providerTurn: projection.providerTurns[0],
409 + attempt: projection.attempts[0],
410 + message: {
411 + id: MessageId.make("message:steer-app-context"),
412 + text: "What did the app report?",
413 + attachments: [],
414 + createdBy: "user",
415 + creationSource: "web",
416 + } as unknown as NonNullable<
417 + ProjectionStore.ProjectionProviderControlContext["message"]
418 + >,
419 + run: {
420 + id: RunId.make("run:steer-app-context"),
421 + status: "running",
422 + activeAttemptId: attemptId,
423 + } as OrchestrationV2Run,
424 + }),
425 + ),
426 + layerSessions(sessionId, runtime),
427 + Layer.mock(EventSink.EventSinkV2)({}),
428 + Layer.mock(McpAppModelContext.McpAppModelContext)({
429 + forThread: () =>
430 + Effect.succeed([
431 + {
432 + itemId: "turn-item:call-1",
433 + server: "tools",
434 + tool: "picker",
435 + text: "Pressed: blue",
436 + },
437 + ]),
438 + }),
439 + ),
440 + ),
441 + );
442 +
443 + yield* Effect.gen(function* () {
444 + const control = yield* ProviderTurnControlService.ProviderTurnControlServiceV2;
445 + yield* control.steer({
446 + threadId,
447 + providerSessionId: sessionId,
448 + providerThreadId: providerThread.id,
449 + providerTurnId,
450 + messageId: MessageId.make("message:steer-app-context"),
451 + });
452 + }).pipe(Effect.provide(layerControl));
453 +
454 + assert.equal(steered.length, 1);
455 + assert.deepEqual("appContext" in steered[0]! ? steered[0].appContext : undefined, [
456 + { key: "mcp_app_turn-item_call-1", text: "Pressed: blue" },
457 + ]);
458 + }),
459 +);
apps/server/src/orchestration-v2/ProviderTurnControlService.ts
+8
@@ -18,6 +18,7 @@ import * as Schema from "effect/Schema";
18 import * as Stream from "effect/Stream";
19
20 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
21 +import * as McpAppModelContext from "../mcpApps/McpAppModelContext.ts";
22 import * as EventSink from "./EventSink.ts";
23 import * as ProjectionStore from "./ProjectionStore.ts";
24 import * as ProviderSessionManager from "./ProviderSessionManager.ts";
@@ -113,6 +114,7 @@ export const layer: Layer.Layer<
114 ProviderTurnControlServiceV2,
115 never,
116 | EventSink.EventSinkV2
117 + | McpAppModelContext.McpAppModelContext
118 | ProjectionStore.ProjectionStoreV2
119 | ProviderSessionManager.ProviderSessionManagerV2
120 > = Layer.effect(
@@ -121,6 +123,7 @@ export const layer: Layer.Layer<
123 const eventSink = yield* EventSink.EventSinkV2;
124 const projections = yield* ProjectionStore.ProjectionStoreV2;
125 const sessions = yield* ProviderSessionManager.ProviderSessionManagerV2;
126 + const mcpAppModelContext = yield* McpAppModelContext.McpAppModelContext;
127
128 const load = Effect.fn("ProviderTurnControlService.load")(function* (input: {
129 readonly threadId: ThreadId;
@@ -444,6 +447,10 @@ export const layer: Layer.Layer<
447 cause: "The persisted steering message or target run is missing.",
448 });
449 }
450 + const appContext = yield* McpAppModelContext.forProvider(
451 + mcpAppModelContext,
452 + input.threadId,
453 + );
454 yield* loaded.session.value
455 .steerTurn({
456 threadId: input.threadId,
@@ -453,6 +460,7 @@ export const layer: Layer.Layer<
460 ...(input.modelSelection === undefined
461 ? {}
462 : { modelSelection: input.modelSelection }),
463 + ...(appContext.length === 0 ? {} : { appContext }),
464 message: {
465 messageId: message.id,
466 text: projectComposerContextForProvider({
apps/server/src/orchestration-v2/RunExecutionService.ts
+4 -15
@@ -2200,21 +2200,10 @@ export const layer: Layer.Layer<
2200 }),
2201 );
2202 yield* touchMcpCredential;
2203 - const appContext = (yield* mcpAppModelContext
2204 - .forThread(input.run.threadId)
2205 - .pipe(
2206 - Effect.catch((cause) =>
2207 - Effect.logWarning("Failed to read MCP app model context.", { cause }).pipe(
2208 - Effect.as([]),
2209 - ),
2210 - ),
2211 - )).map((entry) => ({
2212 - // The item id alone is unique and needs no escaping; server and
2213 - // tool names are free text that would break the tag Codex wraps
2214 - // the context in.
2215 - key: `mcp_app_${entry.itemId.replace(/[^\w.-]/g, "_")}`,
2216 - text: entry.text,
2217 - }));
2203 + const appContext = yield* McpAppModelContext.forProvider(
2204 + mcpAppModelContext,
2205 + input.run.threadId,
2206 + );
2207 const turnInput = {
2208 appThread: input.appThread,
2209 threadId: input.run.threadId,
apps/server/src/orchestration-v2/runtimeLayer.ts
+6 -1
@@ -184,7 +184,12 @@ const layerProviderTurnStartServiceProvided = ProviderTurnStartService.layer.pip
184
185 const layerProviderTurnControlServiceProvided = ProviderTurnControlService.layer.pipe(
186 Layer.provide(
187 - Layer.mergeAll(layerEventSink, ProjectionStore.layer, layerProviderSessionManagerProvided),
187 + Layer.mergeAll(
188 + layerEventSink,
189 + McpAppModelContext.layer,
190 + ProjectionStore.layer,
191 + layerProviderSessionManagerProvided,
192 + ),
193 ),
194 );
195 const layerRuntimeRequestServiceProvided = RuntimeRequestService.layer.pipe(
apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts
+6 -1
@@ -454,7 +454,12 @@ export function layerWithRegistry<Error>(
454 );
455 const layerProviderTurnControlServiceProvided = ProviderTurnControlService.layer.pipe(
456 Layer.provide(
457 - Layer.mergeAll(layerEventSinkProvided, layerStores, layerProviderSessionManagerProvided),
457 + Layer.mergeAll(
458 + layerEventSinkProvided,
459 + McpAppModelContext.layerEmpty,
460 + layerStores,
461 + layerProviderSessionManagerProvided,
462 + ),
463 ),
464 );
465 const layerRuntimeRequestServiceProvided = RuntimeRequestService.layer.pipe(
packages/provider-core/src/server/ProviderAdapter.ts
+2
@@ -587,6 +587,8 @@ export interface ProviderAdapterV2SteerInput {
587 readonly message: ProviderAdapterV2TurnMessage;
588 /** The selection sent with the message when it differs from the running turn's. */
589 readonly modelSelection?: ModelSelection;
590 + /** The thread's MCP app notes; the adapter sends those the agent has not seen yet. */
591 + readonly appContext?: ProviderAdapterV2TurnInput["appContext"];
592 }
593
594 export interface ProviderAdapterV2InterruptInput {