@devries-cameron20 / t3code Mirror · read-only / commits / 6b2188aac4
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 22, 22:00 UTC

fix(server): re-inject T3 instructions into ACP sessions after compaction (#21053)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Anton committed Oct 20, 2026 at 07:11 UTC 6b2188aac4f63ce036966cbe0683b5da26e4560b
3 files changed +192 -3
apps/server/scripts/acp-mock-agent.ts
+18 -1
@@ -90,6 +90,10 @@ const emitStaleXAiPromptCompleteBeforeSecondHang =
90 const emitOverlappingXAiPromptCompleteOutOfOrder =
91 process.env.T3_ACP_EMIT_OVERLAPPING_XAI_PROMPT_COMPLETE_OUT_OF_ORDER === "1";
92 const failPrompt = process.env.T3_ACP_FAIL_PROMPT === "1";
93 +const failPromptOrdinal = Number(process.env.T3_ACP_FAIL_PROMPT_ORDINAL);
94 +const compactionPromptOrdinals = new Set(
95 + (process.env.T3_ACP_COMPACTION_PROMPT_ORDINALS ?? "").split(",").map(Number),
96 +);
97 const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1";
98 const failSetModeConfigOption = process.env.T3_ACP_FAIL_SET_MODE_CONFIG_OPTION === "1";
99 const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1";
@@ -1299,7 +1303,20 @@ const program = Effect.gen(function* () {
1303 yield* Effect.sleep(`${promptDelayMs} millis`);
1304 }
1305
1302 - if (failPrompt) {
1306 + if (compactionPromptOrdinals.has(promptCount)) {
1307 + for (const status of ["in_progress", "completed"] as const) {
1308 + yield* agent.client.sessionUpdate({
1309 + sessionId: requestedSessionId,
1310 + update: {
1311 + sessionUpdate: "compaction_update",
1312 + compactionId: `compact-${promptCount}`,
1313 + status,
1314 + },
1315 + });
1316 + }
1317 + }
1318 +
1319 + if (failPrompt || promptCount === failPromptOrdinal) {
1320 return yield* AcpError.AcpRequestError.internalError("Mock prompt failure");
1321 }
1322
apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts
+140
@@ -538,6 +538,100 @@ const pollProtocolMethods = (events: Queue.Queue<EffectAcpProtocol.AcpProtocolLo
538 return methods;
539 });
540
541 +const makeInstructionCompactionHarness = Effect.fnUntraced(function* (
542 + environment: Readonly<Record<string, string>>,
543 +) {
544 + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
545 + const path = yield* Path.Path;
546 + const selfInvocation = yield* resolveSelfInvocation();
547 + const mockAgentPath = yield* path.fromFileUrl(
548 + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url),
549 + );
550 + const protocolEvents = yield* Queue.unbounded<EffectAcpProtocol.AcpProtocolLogEvent>();
551 + const instanceId = ProviderInstanceId.make("acp-test-instruction-compaction");
552 + const threadId = ThreadId.make("thread-acp-instruction-compaction");
553 + yield* (yield* McpProviderSessions.McpProviderSessions).set({
554 + environmentId: EnvironmentId.make("environment-acp-instruction-compaction"),
555 + threadId,
556 + providerSessionId: "mcp-session-acp-instruction-compaction",
557 + providerInstanceId: instanceId,
558 + endpoint: "http://127.0.0.1:43123/mcp",
559 + authorizationHeader: "Bearer instruction-compaction-token",
560 + browserToolsAvailable: true,
561 + });
562 + const adapter = yield* makeAcpAdapterV2({
563 + instanceId,
564 + flavor: {
565 + driver: ACP_TEST_DRIVER,
566 + capabilities: AcpProviderCapabilitiesV2,
567 + supportsCompaction: true,
568 + makeRuntime: makeMockRuntime({
569 + childProcessSpawner,
570 + mockAgentPath,
571 + protocolEvents,
572 + environment,
573 + wrapRuntime: (runtime) => ({
574 + ...runtime,
575 + // Make compaction during prompt completion deterministic at the adapter boundary.
576 + prompt: (payload, options) =>
577 + runtime.prompt(payload, options).pipe(Effect.tap(() => runtime.drainEvents)),
578 + }),
579 + }),
580 + },
581 + selfInvocation,
582 + });
583 + const runtimePolicy = ProviderAdapter.ProviderAdapterV2RuntimePolicy.make({
584 + runtimeMode: "full-access",
585 + interactionMode: "default",
586 + cwd: process.cwd(),
587 + });
588 + const modelSelection = { instanceId, model: "default" } as const;
589 + const runtime = yield* adapter.openSession({
590 + threadId,
591 + providerSessionId: ProviderSessionId.make("provider-session-acp-instruction-compaction"),
592 + modelSelection,
593 + runtimePolicy,
594 + });
595 + const providerThread = yield* runtime.ensureThread({ threadId, modelSelection, runtimePolicy });
596 + const now = yield* DateTime.now;
597 + let ordinal = 0;
598 + return Effect.fnUntraced(function* (messageText: string, expectedStatus = "completed") {
599 + yield* runtime.startTurn(
600 + makeTurnInput({
601 + threadId,
602 + providerThread,
603 + instanceId,
604 + runtimePolicy,
605 + now,
606 + ordinal: ++ordinal,
607 + messageText,
608 + }),
609 + );
610 + const terminal = yield* runtime.events.pipe(
611 + Stream.filter((event) => event.type === "turn.terminal"),
612 + Stream.runHead,
613 + );
614 + assert.equal(Option.getOrThrow(terminal).status, expectedStatus);
615 + while (true) {
616 + const event = yield* Queue.take(protocolEvents);
617 + if (event.direction === "outgoing" && rawProtocolMethod(event) === "session/prompt") {
618 + return rawProtocolPromptTextBlocks(event);
619 + }
620 + }
621 + });
622 +});
623 +
624 +function assertReinjectedInstructions(
625 + blocks: Array<{ type: "text"; text: string }>,
626 + request: string,
627 +) {
628 + const text = blocks[0]?.text ?? "";
629 + assert.include(text, "T3 Code interaction mode: Default");
630 + assert.include(text, "T3 Code collaborative browser");
631 + assert.include(text, "T3 Code orchestration");
632 + assert.include(text, `<user_request>\n${request}\n</user_request>`);
633 +}
634 +
635 describe("AcpAdapterV2", () => {
636 it.live.each(["failed", "recovered", "completed", "cancelled"] as const)(
637 "projects Mistral retry notices and their %s outcome",
@@ -827,6 +921,52 @@ describe("AcpAdapterV2", () => {
921 }).pipe(Effect.provide(layerTest), Effect.scoped),
922 );
923
924 + it.live(
925 + "reinjects ACP instructions after protocol compaction, including during reinjection",
926 + () =>
927 + Effect.gen(function* () {
928 + const runTurn = yield* makeInstructionCompactionHarness({
929 + T3_ACP_COMPACTION_PROMPT_ORDINALS: "2,4",
930 + });
931 + yield* runTurn("Start work.");
932 + yield* runTurn("Continue until context compacts.");
933 + assert.deepEqual(yield* runTurn(" /repro-skill"), [
934 + { type: "text", text: " /repro-skill" },
935 + ]);
936 + assertReinjectedInstructions(
937 + yield* runTurn("Continue after compaction."),
938 + "Continue after compaction.",
939 + );
940 + assertReinjectedInstructions(
941 + yield* runTurn("Continue after the second compaction."),
942 + "Continue after the second compaction.",
943 + );
944 + assert.equal((yield* runTurn("Finish work."))[0]?.text, "Finish work.");
945 + }).pipe(Effect.provide(layerTest), Effect.scoped),
946 + );
947 +
948 + it.live(
949 + "reinjects ACP instructions after successful native compact, but not failed compact",
950 + () =>
951 + Effect.gen(function* () {
952 + const runTurn = yield* makeInstructionCompactionHarness({
953 + T3_ACP_FAIL_PROMPT_ORDINAL: "2",
954 + });
955 + yield* runTurn("Start work.");
956 + assert.deepEqual(yield* runTurn("/compact", "failed"), [
957 + { type: "text", text: "/compact" },
958 + ]);
959 + assert.equal(
960 + (yield* runTurn("Continue after failure."))[0]?.text,
961 + "Continue after failure.",
962 + );
963 + assert.deepEqual(yield* runTurn("/compact"), [{ type: "text", text: "/compact" }]);
964 + assert.deepEqual(yield* runTurn("/repro-skill"), [{ type: "text", text: "/repro-skill" }]);
965 + assertReinjectedInstructions(yield* runTurn("Continue work."), "Continue work.");
966 + assert.equal((yield* runTurn("Finish work."))[0]?.text, "Finish work.");
967 + }).pipe(Effect.provide(layerTest), Effect.scoped),
968 + );
969 +
970 it.live("reapplies a selection after a switch away from it failed partway", () =>
971 Effect.gen(function* () {
972 const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
packages/provider-acp/src/server/adapter.ts
+34 -2
@@ -1581,6 +1581,8 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
1581 const activeSelection = yield* Ref.make<ModelSelection | null>(null);
1582 const activeInteractionMode = yield* Ref.make<ProviderInteractionMode | null>(null);
1583 const promptInstructionStates = yield* Ref.make(new Map<string, T3AcpInstructionState>());
1584 + // Unique markers keep delayed prompt completions from clearing later compactions.
1585 + const compactionMarkers = yield* Ref.make(new Map<string, symbol>());
1586 const runtimeRestartRequired = yield* Ref.make(false);
1587 const runtimeTeardownState = yield* Ref.make<AcpRuntimeTeardownState>({ _tag: "Idle" });
1588 const runtimeCallbackGeneration = yield* Ref.make(0);
@@ -3659,6 +3661,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
3661 updated.delete(context.nativeThreadId);
3662 return updated;
3663 });
3664 + yield* Ref.update(compactionMarkers, (current) => {
3665 + const updated = new Map(current);
3666 + updated.set(context.nativeThreadId, Symbol());
3667 + return updated;
3668 + });
3669 }
3670 } else if (mcpIdentity !== undefined) {
3671 turnItem = {
@@ -6893,6 +6900,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
6900 settledStatus === "completed"
6901 ) {
6902 const nativeItemId = `${context.nativeTurnId}:compaction`;
6903 + yield* Ref.update(compactionMarkers, (current) => {
6904 + const updated = new Map(current);
6905 + updated.set(context.nativeThreadId, Symbol());
6906 + return updated;
6907 + });
6908 yield* emitProviderEvent({
6909 type: "turn_item.updated",
6910 driver,
@@ -7058,6 +7070,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7070 hasT3Mcp: (yield* readMcpContext(turnInput.threadId)).servers.length > 0,
7071 } satisfies T3AcpInstructionState;
7072 const previousInstructionState = (yield* Ref.get(promptInstructionStates)).get(sessionId);
7073 + const compactionMarker = (yield* Ref.get(compactionMarkers)).get(sessionId);
7074 const messageText = providerMessageTextWithAttachmentPaths({
7075 text: turnInput.message.text,
7076 attachments: turnInput.message.attachments,
@@ -7067,7 +7080,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7080 const text = t3AcpPromptWithInstructions({
7081 prompt: messageText,
7082 state: instructionState,
7070 - ...(previousInstructionState === undefined
7083 + ...(previousInstructionState === undefined || compactionMarker !== undefined
7084 ? {}
7085 : { previousState: previousInstructionState }),
7086 });
@@ -7123,7 +7136,11 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7136 }),
7137 });
7138 }
7126 - return { prompt, instructionState: text === messageText ? undefined : instructionState };
7139 + return {
7140 + prompt,
7141 + instructionState: text === messageText ? undefined : instructionState,
7142 + compactionMarker,
7143 + };
7144 });
7145
7146 const restartRuntimeAfterTeardownIfRequired = Effect.fnUntraced(function* (
@@ -7438,6 +7455,20 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
7455 return updated;
7456 }),
7457 ),
7458 + Effect.tap(() =>
7459 + Ref.update(compactionMarkers, (current) => {
7460 + if (promptParts?.instructionState === undefined) return current;
7461 + const observedMarker = promptParts.compactionMarker;
7462 + if (
7463 + observedMarker === undefined ||
7464 + current.get(requestedSessionId) !== observedMarker
7465 + )
7466 + return current;
7467 + const updated = new Map(current);
7468 + updated.delete(requestedSessionId);
7469 + return updated;
7470 + }),
7471 + ),
7472 // Wire settlement precedes the completion callback's permit request so
7473 // settled-soft classification can observe the native return even when
7474 // the completion fiber has not yet set promptSettled under the permit.
@@ -8237,6 +8268,7 @@ export const makeAcpAdapterV2 = Effect.fn("makeAcpAdapterV2")(function* (
8268 yield* Ref.set(activeSelection, null);
8269 yield* Ref.set(activeInteractionMode, null);
8270 yield* Ref.set(promptInstructionStates, new Map());
8271 + yield* Ref.set(compactionMarkers, new Map());
8272 yield* Ref.set(providerTurns, new Map());
8273 yield* Ref.set(snapshot, {
8274 order: [],