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

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

fix(opencode): a failed steer no longer leaves the turn running forever (#24701)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>

Victor committed Nov 14, 2026 at 01:29 UTC aecad62a5080aba99f1231467e2bf1840eb69049
2 files changed +337 -9
packages/provider-opencode/src/server/adapter.test.ts
+271
@@ -2722,6 +2722,268 @@ describe("OpenCodeAdapterV2", () => {
2722 }).pipe(Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer))),
2723 );
2724
2725 + it.effect.each([
2726 + "during",
2727 + "idle-during-status",
2728 + "busy-during-status",
2729 + "after-refused-connection",
2730 + ] as const)("completes the turn when the session goes idle %s a rejected steer", (idleTiming) =>
2731 + Effect.gen(function* () {
2732 + const nativeEvents = asyncEventStream();
2733 + const sessionId = `native-steer-rejected-${idleTiming}`;
2734 + const idle = {
2735 + type: "session.status",
2736 + properties: { sessionID: sessionId, status: { type: "idle" } },
2737 + };
2738 + const promptIds: Array<string> = [];
2739 + const terminal = yield* Deferred.make<void>();
2740 + const statusRead = promiseGate<void>();
2741 + const statusRechecked = promiseGate<void>();
2742 + let statusCalls = 0;
2743 + const harness = yield* makeOpenCodeRuntimeHarness(`steer-rejected-${idleTiming}`, sessionId, {
2744 + event: { subscribe: async () => ({ stream: nativeEvents.stream }) },
2745 + session: {
2746 + create: async () => ({ data: { id: sessionId, time: { created: 1, updated: 1 } } }),
2747 + get: async () => ({ data: { id: sessionId, time: { created: 1, updated: 1 } } }),
2748 + messages: async () => ({ data: [] }),
2749 + status: async () => {
2750 + statusCalls++;
2751 + statusRead.resolve();
2752 + if (idleTiming === "busy-during-status") {
2753 + if (statusCalls === 1) {
2754 + await nativeEvents.push({
2755 + type: "session.status",
2756 + properties: { sessionID: sessionId, status: { type: "busy" } },
2757 + });
2758 + return { data: { [sessionId]: { type: "idle" } } };
2759 + }
2760 + statusRechecked.resolve();
2761 + return { data: { [sessionId]: { type: statusCalls === 2 ? "busy" : "idle" } } };
2762 + }
2763 + if (idleTiming === "idle-during-status" && statusCalls === 1) {
2764 + await nativeEvents.push(idle);
2765 + return { data: { [sessionId]: { type: "busy" } } };
2766 + }
2767 + return {
2768 + data: {
2769 + [sessionId]: { type: idleTiming === "after-refused-connection" ? "busy" : "idle" },
2770 + },
2771 + };
2772 + },
2773 + promptAsync: async (input: { messageID: string }) => {
2774 + promptIds.push(input.messageID);
2775 + if (promptIds.length === 1) return { data: true };
2776 + if (idleTiming === "during") await nativeEvents.push(idle);
2777 + if (idleTiming === "after-refused-connection") {
2778 + throw new TypeError("fetch failed", {
2779 + cause: Object.assign(new Error("connect ECONNREFUSED"), { code: "ECONNREFUSED" }),
2780 + });
2781 + }
2782 + // The SDK wraps an HTTP error reply in an Error with its status on `cause`.
2783 + throw new Error("steer rejected", { cause: { body: "steer rejected", status: 503 } });
2784 + },
2785 + abort: async () => ({ data: true }),
2786 + children: async () => ({ data: [] }),
2787 + },
2788 + });
2789 + yield* harness.startTurn();
2790 + yield* Effect.promise(() =>
2791 + nativeEvents.push({
2792 + type: "message.updated",
2793 + properties: {
2794 + sessionID: sessionId,
2795 + info: {
2796 + id: promptIds[0],
2797 + sessionID: sessionId,
2798 + role: "user",
2799 + time: { created: DateTime.toEpochMillis(harness.now) },
2800 + },
2801 + },
2802 + }),
2803 + );
2804 + const running = yield* harness.runtime.readThreadSnapshot({
2805 + providerThread: harness.providerThread,
2806 + });
2807 + yield* harness.runtime.events.pipe(
2808 + Stream.tap((event) =>
2809 + event.type === "turn.terminal" ? Deferred.succeed(terminal, undefined) : Effect.void,
2810 + ),
2811 + Stream.runDrain,
2812 + Effect.forkScoped,
2813 + );
2814 + const steer = yield* Effect.exit(
2815 + harness.runtime.steerTurn({
2816 + threadId: harness.threadId,
2817 + runId: harness.runId,
2818 + providerThread: harness.providerThread,
2819 + providerTurnId: running.providerTurns.at(-1)!.id,
2820 + message: {
2821 + messageId: MessageId.make(`message-steer-rejected-${idleTiming}`),
2822 + text: "also cover the README",
2823 + attachments: [],
2824 + createdBy: "user",
2825 + creationSource: "web",
2826 + },
2827 + }),
2828 + );
2829 + assert.isTrue(Exit.isFailure(steer));
2830 + yield* Effect.promise(() => statusRead.promise);
2831 + if (idleTiming === "busy-during-status") {
2832 + const outcome = yield* Effect.raceFirst(
2833 + Effect.promise(() => statusRechecked.promise).pipe(Effect.as("rechecked")),
2834 + Deferred.await(terminal).pipe(Effect.as("completed")),
2835 + );
2836 + assert.equal(outcome, "rechecked");
2837 + const active = yield* harness.runtime.readThreadSnapshot({
2838 + providerThread: harness.providerThread,
2839 + });
2840 + assert.equal(active.providerTurns.at(-1)?.status, "running");
2841 + yield* Effect.promise(() => nativeEvents.push(idle));
2842 + }
2843 + if (idleTiming === "after-refused-connection") {
2844 + const active = yield* harness.runtime.readThreadSnapshot({
2845 + providerThread: harness.providerThread,
2846 + });
2847 + assert.equal(active.providerTurns.at(-1)?.status, "running");
2848 + yield* Effect.promise(() => nativeEvents.push(idle));
2849 + }
2850 + yield* Deferred.await(terminal);
2851 + if (idleTiming !== "busy-during-status") {
2852 + assert.equal(statusCalls, idleTiming === "idle-during-status" ? 2 : 1);
2853 + }
2854 +
2855 + const settled = yield* harness.runtime.readThreadSnapshot({
2856 + providerThread: harness.providerThread,
2857 + });
2858 + assert.equal(settled.providerTurns.at(-1)?.status, "completed");
2859 + }).pipe(
2860 + Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
2861 + Effect.scoped,
2862 + ),
2863 + );
2864 +
2865 + it.effect(
2866 + "keeps the turn for a steer whose reply was lost until its output lands, even after a retry is rejected",
2867 + () =>
2868 + Effect.gen(function* () {
2869 + const nativeEvents = asyncEventStream();
2870 + const sessionId = "native-steer-reply-lost";
2871 + const promptIds: Array<string> = [];
2872 + const harness = yield* makeOpenCodeRuntimeHarness(sessionId, sessionId, {
2873 + event: { subscribe: async () => ({ stream: nativeEvents.stream }) },
2874 + session: {
2875 + create: async () => ({ data: { id: sessionId, time: { created: 1, updated: 1 } } }),
2876 + get: async () => ({ data: { id: sessionId, time: { created: 1, updated: 1 } } }),
2877 + messages: async () => ({ data: [] }),
2878 + // OpenCode took the steer but has not saved its message yet.
2879 + status: async () => ({ data: { [sessionId]: { type: "idle" } } }),
2880 + promptAsync: async (input: { messageID: string }) => {
2881 + promptIds.push(input.messageID);
2882 + if (promptIds.length === 1) return { data: true };
2883 + if (promptIds.length === 3) {
2884 + throw new Error("Service Unavailable", { cause: { status: 503 } });
2885 + }
2886 + throw new TypeError("fetch failed", {
2887 + cause: Object.assign(new Error("other side closed"), { code: "UND_ERR_SOCKET" }),
2888 + });
2889 + },
2890 + abort: async () => ({ data: true }),
2891 + children: async () => ({ data: [] }),
2892 + },
2893 + });
2894 + yield* harness.startTurn();
2895 + const userMessage = (id: string | undefined) =>
2896 + Effect.promise(() =>
2897 + nativeEvents.push({
2898 + type: "message.updated",
2899 + properties: {
2900 + sessionID: sessionId,
2901 + info: { id, sessionID: sessionId, role: "user", time: { created: 1 } },
2902 + },
2903 + }),
2904 + );
2905 + yield* userMessage(promptIds[0]);
2906 + const running = yield* harness.runtime.readThreadSnapshot({
2907 + providerThread: harness.providerThread,
2908 + });
2909 + const received = yield* harness.runtime.events.pipe(
2910 + Stream.takeUntil((event) => event.type === "turn.terminal"),
2911 + Stream.runCollect,
2912 + Effect.forkScoped,
2913 + );
2914 + const steer = harness.runtime.steerTurn({
2915 + threadId: harness.threadId,
2916 + runId: harness.runId,
2917 + providerThread: harness.providerThread,
2918 + providerTurnId: running.providerTurns.at(-1)!.id,
2919 + message: {
2920 + messageId: MessageId.make("message-steer-reply-lost"),
2921 + text: "also cover the README",
2922 + attachments: [],
2923 + createdBy: "user",
2924 + creationSource: "web",
2925 + },
2926 + });
2927 + assert.isTrue(Exit.isFailure(yield* Effect.exit(steer)));
2928 + // T3 retries a failed steer; this retry's request is refused outright.
2929 + assert.isTrue(Exit.isFailure(yield* Effect.exit(steer)));
2930 + // A real status read answers before OpenCode saves the steer's message.
2931 + yield* Effect.yieldNow;
2932 + yield* userMessage(promptIds[1]);
2933 + const assistant = (completed?: number) =>
2934 + Effect.promise(() =>
2935 + nativeEvents.push({
2936 + type: "message.updated",
2937 + properties: {
2938 + sessionID: sessionId,
2939 + info: {
2940 + id: "steer-answer",
2941 + sessionID: sessionId,
2942 + role: "assistant",
2943 + time: completed === undefined ? { created: 2 } : { created: 2, completed },
2944 + },
2945 + },
2946 + }),
2947 + );
2948 + yield* assistant();
2949 + yield* Effect.promise(() =>
2950 + nativeEvents.push({
2951 + type: "message.part.updated",
2952 + properties: {
2953 + sessionID: sessionId,
2954 + part: {
2955 + id: "steer-answer-text",
2956 + sessionID: sessionId,
2957 + messageID: "steer-answer",
2958 + type: "text",
2959 + text: "README covered",
2960 + time: { start: 2 },
2961 + },
2962 + },
2963 + }),
2964 + );
2965 + yield* assistant(3);
2966 + yield* Effect.promise(() =>
2967 + nativeEvents.push({
2968 + type: "session.status",
2969 + properties: { sessionID: sessionId, status: { type: "idle" } },
2970 + }),
2971 + );
2972 + const events = yield* Fiber.join(received);
2973 + const answers = events.flatMap((event) =>
2974 + event.type === "turn_item.updated" && event.turnItem.type === "assistant_message"
2975 + ? [event.turnItem.text]
2976 + : [],
2977 + );
2978 + assert.include(answers, "README covered");
2979 + const terminal = events.at(-1);
2980 + assert.equal(terminal?.type === "turn.terminal" ? terminal.status : undefined, "completed");
2981 + }).pipe(
2982 + Effect.provide(Layer.merge(IdAllocator.layer, McpProviderSessions.layer)),
2983 + Effect.scoped,
2984 + ),
2985 + );
2986 +
2987 it.effect("interrupts an initial prompt while its SDK request is pending", () =>
2988 Effect.gen(function* () {
2989 const nativeEvents = asyncEventStream();
@@ -3102,6 +3364,15 @@ describe("OpenCodeAdapterV2", () => {
3364 "unknown",
3365 );
3366 assert.isTrue(admission.admissionPending);
3367 + const stalled = yield* reconcileOpenCodePromptAdmissionStatus(
3368 + admission,
3369 + 4,
3370 + Effect.never,
3371 + ).pipe(Effect.forkChild({ startImmediately: true }));
3372 + yield* TestClock.adjust("10 seconds");
3373 + assert.isDefined(stalled.pollUnsafe());
3374 + assert.equal(yield* Fiber.join(stalled), "unknown");
3375 + assert.isTrue(admission.admissionPending);
3376 assert.equal(
3377 yield* reconcileOpenCodePromptAdmissionStatus(admission, 4, Effect.succeed("idle")),
3378 "idle",
packages/provider-opencode/src/server/adapter.ts
+66 -9
@@ -314,6 +314,8 @@ interface ActiveOpenCodeTurn {
314 admissionAccepted: boolean;
315 admissionMessageObserved: boolean;
316 idleDuringAdmission: boolean;
317 + admissionUncertain: boolean;
318 + admissionStatusSequence: number;
319 admissionSettled: Deferred.Deferred<void>;
320 admissionAbortController: AbortController | null;
321 }
@@ -370,7 +372,10 @@ export const reconcileOpenCodePromptAdmissionStatus = Effect.fn(
372 if (admission.admissionGeneration !== generation || !admission.admissionPending) {
373 return "stale" as const;
374 }
373 - const status = yield* readStatus;
375 + const status = yield* readStatus.pipe(
376 + Effect.timeoutOption("10 seconds"),
377 + Effect.map(Option.getOrElse(() => "unknown" as const)),
378 + );
379 if (admission.admissionGeneration !== generation || !admission.admissionPending) {
380 return "stale" as const;
381 }
@@ -904,6 +909,28 @@ function isMessageAbortedError(event: Extract<OpenCodeEvent, { type: "session.er
909 return event.properties.error?.name === "MessageAbortedError";
910 }
911
912 +// Node's fetch reports these when the connection failed before the request was sent.
913 +const OPENCODE_UNSENT_REQUEST_CODES = new Set([
914 + "ECONNREFUSED",
915 + "ENOTFOUND",
916 + "EAI_AGAIN",
917 + "EHOSTUNREACH",
918 + "ENETUNREACH",
919 + "UND_ERR_CONNECT_TIMEOUT",
920 +]);
921 +
922 +// Only an HTTP error reply (the SDK puts its status on `cause`) or an unsent request
923 +// proves OpenCode did not take a prompt; a reset or timeout after sending is ambiguous.
924 +function isOpenCodePromptRejected(error: unknown): boolean {
925 + const cause = OpenCodeRuntime.isOpenCodeRuntimeError(error) ? error.cause : error;
926 + if (!(cause instanceof Error)) return false;
927 + const reason = cause.cause as { readonly status?: unknown; readonly code?: unknown } | undefined;
928 + return (
929 + typeof reason?.status === "number" ||
930 + (typeof reason?.code === "string" && OPENCODE_UNSENT_REQUEST_CODES.has(reason.code))
931 + );
932 +}
933 +
934 function isOpenCodeNotFound(cause: unknown): boolean {
935 const seen = new Set<unknown>();
936 const queue: Array<unknown> = [cause];
@@ -2223,11 +2250,14 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2250 generation: number,
2251 ) {
2252 while (promptAdmissionIsCurrent(state, turn, generation)) {
2253 + const statusSequence = turn.admissionStatusSequence;
2254 const status = yield* reconcileOpenCodePromptAdmissionStatus(
2255 turn,
2256 generation,
2229 - sdkCall("session.status", { sessionID: state.nativeSessionId, generation }, () =>
2230 - client.session.status(),
2257 + sdkCall(
2258 + "session.status",
2259 + { sessionID: state.nativeSessionId, generation },
2260 + (signal) => client.session.status(undefined, { signal }),
2261 ).pipe(
2262 Effect.match({
2263 onFailure: () => "unknown" as const,
@@ -2250,6 +2280,10 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2280 ) {
2281 return;
2282 }
2283 + if (turn.admissionStatusSequence !== statusSequence) {
2284 + turn.admissionPending = true;
2285 + continue;
2286 + }
2287 if (status === "idle") {
2288 yield* finalizeTurn(state, turn, "completed");
2289 return;
@@ -2344,6 +2378,8 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2378 admissionAccepted: true,
2379 admissionMessageObserved: true,
2380 idleDuringAdmission: false,
2381 + admissionUncertain: false,
2382 + admissionStatusSequence: 0,
2383 admissionSettled: Deferred.makeUnsafe<void>(),
2384 admissionAbortController: null,
2385 };
@@ -2703,6 +2739,9 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2739 }
2740 const state = threads.get(sessionId);
2741 if (state === undefined) return;
2742 + if (state.activeTurn?.admissionPending) {
2743 + state.activeTurn.admissionStatusSequence++;
2744 + }
2745 if (event.properties.status.type === "busy") {
2746 yield* updateProviderThread(state, { status: "active" });
2747 return;
@@ -2725,6 +2764,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
2764 const state = threads.get(event.properties.sessionID);
2765 if (state?.activeTurn !== null && state?.activeTurn !== undefined) {
2766 if (state.activeTurn.admissionPending) {
2767 + state.activeTurn.admissionStatusSequence++;
2768 advanceOpenCodePromptAdmission(state.activeTurn, "idle");
2769 return;
2770 }
@@ -3358,6 +3398,8 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3398 admissionAccepted: isCompaction,
3399 admissionMessageObserved: false,
3400 idleDuringAdmission: false,
3401 + admissionUncertain: false,
3402 + admissionStatusSequence: 0,
3403 admissionSettled: Deferred.makeUnsafe<void>(),
3404 // @effect-diagnostics-next-line abortControllerInEffect:off - Turn interruption owns prompt admission cancellation.
3405 admissionAbortController: new AbortController(),
@@ -3516,6 +3558,8 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3558 `OpenCode turn ${steerInput.providerTurnId} is not active`,
3559 );
3560 }
3561 + // A retry of a steer whose earlier attempt may have reached OpenCode stays uncertain.
3562 + if (!turn.admissionPending) turn.admissionUncertain = false;
3563 turn.admissionGeneration = state.nextAdmissionGeneration++;
3564 turn.admissionMessageId = admissionMessageId;
3565 turn.admissionPending = true;
@@ -3529,6 +3573,15 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3573 turn.usage.promptMessageIds.add(turn.admissionMessageId);
3574 const admissionSettled = turn.admissionSettled;
3575 const admissionAbortController = turn.admissionAbortController;
3576 + const generation = turn.admissionGeneration;
3577 + const acceptAdmission = Effect.suspend(() =>
3578 + state.activeTurn === turn &&
3579 + !turn.finalized &&
3580 + !turn.interrupted &&
3581 + advanceOpenCodePromptAdmission(turn, "accepted") === "reconcile-idle"
3582 + ? reconcilePromptAdmission(state, turn)
3583 + : Effect.void,
3584 + );
3585 yield* submitPrompt(
3586 state,
3587 turn,
@@ -3541,6 +3594,15 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3594 },
3595 admissionAbortController!,
3596 ).pipe(
3597 + Effect.tapError((error) => {
3598 + if (!promptAdmissionIsCurrent(state, turn, generation)) return Effect.void;
3599 + if (isOpenCodePromptRejected(error) && !turn.admissionUncertain) {
3600 + return reconcilePromptAdmission(state, turn);
3601 + }
3602 + // OpenCode may have taken this or an earlier attempt: wait for its output or Stop.
3603 + turn.admissionUncertain = true;
3604 + return acceptAdmission;
3605 + }),
3606 Effect.ensuring(
3607 Effect.all([
3608 Deferred.succeed(admissionSettled, undefined).pipe(Effect.ignore),
@@ -3552,12 +3614,7 @@ export const makeOpenCodeAdapterV2 = Effect.fn("makeOpenCodeAdapterV2")(function
3614 ]).pipe(Effect.asVoid),
3615 ),
3616 );
3555 - if (state.activeTurn === turn && !turn.finalized && !turn.interrupted) {
3556 - const admissionAction = advanceOpenCodePromptAdmission(turn, "accepted");
3557 - if (admissionAction === "reconcile-idle") {
3558 - yield* reconcilePromptAdmission(state, turn);
3559 - }
3560 - }
3617 + yield* acceptAdmission;
3618 },
3619 (effect, steerInput) =>
3620 effect.pipe(