diff --git a/apps/web/src/components/ChatView.browser.test.tsx b/apps/web/src/components/ChatView.browser.test.tsx index cfd06a8864e0d..60c3c24ce5c2d 100644 --- a/apps/web/src/components/ChatView.browser.test.tsx +++ b/apps/web/src/components/ChatView.browser.test.tsx @@ -17,6 +17,7 @@ import { mergeWithDefaultKeybindings, } from "@t3tools/shared/keybindings"; import type * as Context from "effect/Context"; +import * as Schema from "effect/Schema"; import * as Effect from "effect/Effect"; import { expect, it, vi } from "vite-plus/test"; import { cdp, page, userEvent } from "vite-plus/test/browser"; @@ -89,6 +90,8 @@ function acceptAttachmentUploads(): Disposable { const insertText = (text: string) => cdp().send("Input.insertText", { text }); /** Holds every call to `method` until `release`, then ends it with `end`, until disposed. */ +class LaunchRefused extends Schema.TaggedError()("LaunchRefused", {}) {} + function holdRpc(method: string, end: Effect.Effect) { let release = () => {}; const held = new Promise((resolve) => { @@ -406,7 +409,7 @@ it("a new draft does not load its reserved thread before the server lists it", a expect(threadRequests).toEqual([]); }); -it("an interrupted image-only first send of a new thread says it may not have been sent", async () => { +it("a failed image-only first send of a new thread keeps the new draft", async () => { using _environment = installFakeEnvironment([]); __setClientSettingsForTests({ ...DEFAULT_CLIENT_SETTINGS, @@ -418,8 +421,11 @@ it("an interrupted image-only first send of a new thread says it may not have be .setProjectDraftThreadId(scopeProjectRef(ENVIRONMENT_ID, PROJECT_ID), draftId, { threadId: ThreadId.make("thread-image-only-interrupted"), }); - // A dropped connection interrupts a new thread's launch, which is not resent. - using launch = holdRpc(ORCHESTRATION_V2_WS_METHODS.launchThread, Effect.interrupt); + // A refusal fails at once; an interrupted launch would wait for a reconnect and be resent. + using launch = holdRpc( + ORCHESTRATION_V2_WS_METHODS.launchThread, + Effect.fail(new LaunchRefused()), + ); const router = getRouter(createMemoryHistory({ initialEntries: [`/draft/${draftId}`] })); await router.load(); await using _app = await render(, { @@ -445,7 +451,7 @@ it("an interrupted image-only first send of a new thread says it may not have be await expect.element(editor).toHaveTextContent("next draft"); launch.release(); - await expect.element(page.getByText("Message may not have been sent")).toBeVisible(); + await expect.element(page.getByText("Message not sent")).toBeVisible(); await expect.element(editor).toHaveTextContent("next draft"); // With no text there is nothing to copy. expect(page.getByText("Copy message", { exact: true }).query()).toBeNull(); diff --git a/packages/client-runtime/src/operations/commands.test.ts b/packages/client-runtime/src/operations/commands.test.ts index b2535a81123e1..941fdcd9b389e 100644 --- a/packages/client-runtime/src/operations/commands.test.ts +++ b/packages/client-runtime/src/operations/commands.test.ts @@ -28,6 +28,7 @@ import * as Exit from "effect/Exit"; import * as Fiber from "effect/Fiber"; import * as Layer from "effect/Layer"; import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; import * as SubscriptionRef from "effect/SubscriptionRef"; import * as TestClock from "effect/testing/TestClock"; import { RpcClientError } from "effect/rpc"; @@ -45,6 +46,7 @@ import { v2Now, v2Projection, v2ThreadId } from "../state/orchestrationV2TestFix import { archiveThread, interruptThreadTurn, + promoteQueuedRun, revertThreadCheckpoint, resumeThreadQueue, startThreadTurn, @@ -55,6 +57,8 @@ const layerTestRandom = Layer.succeed( SecureRandom.make((size) => new Uint8Array(size)), ); +class Refused extends Schema.TaggedError()("Refused", {}) {} + const TARGET = new PrimaryConnectionTarget({ environmentId: EnvironmentId.make("environment-1"), label: "Test environment", @@ -634,6 +638,121 @@ describe("V2 environment commands", () => { }).pipe(Effect.provide(layerTestRandom)), ); + const turnSends = [ + { + name: "new thread's first message", + method: ORCHESTRATION_V2_WS_METHODS.launchThread, + send: (commandId: CommandId) => + startThreadTurn({ + commandId, + threadId: v2ThreadId, + message: { + messageId: MessageId.make(commandId), + role: "user", + text: "hi", + attachments: [], + }, + runtimeMode: "full-access", + interactionMode: "default", + bootstrap: { + createThread: { + projectId: ProjectId.make("project-1"), + title: "Thread", + modelSelection: v2Projection.thread.modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + createdAt: "2026-06-20T00:00:00.000Z", + }, + }, + }), + }, + { + name: "queued message sent now", + method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + send: (commandId: CommandId) => + resumeThreadQueue({ commandId, threadId: v2ThreadId, runId: RunId.make("queued") }), + }, + { + name: "queued message steered", + method: ORCHESTRATION_V2_WS_METHODS.dispatchCommand, + send: (commandId: CommandId) => + promoteQueuedRun({ + commandId, + threadId: v2ThreadId, + queuedRunId: RunId.make("queued"), + targetRunId: RunId.make("running"), + }), + }, + ] as const; + + const sendFailingFirstAttempt = Effect.fn("TestEnvironmentCommands.sendFailingFirstAttempt")( + function* (turnSend: (typeof turnSends)[number], failure: Effect.Effect) { + const supervisor = yield* makeSupervisor({ commands: [], projects: [], launches: [] }); + const healthySession = Option.getOrThrow(yield* SubscriptionRef.get(supervisor.session)); + const attempts: string[] = []; + const firstAttemptFailed = yield* Deferred.make(); + const healthyMethod = ( + healthySession.client as unknown as Record< + string, + (input: unknown) => Effect.Effect + > + )[turnSend.method]!; + const failingClient = { + ...healthySession.client, + [turnSend.method]: (input: { readonly commandId: CommandId }) => + Effect.gen(function* () { + attempts.push(input.commandId); + if (attempts.length > 1) return yield* healthyMethod(input); + yield* SubscriptionRef.set(supervisor.session, Option.none()); + yield* Deferred.succeed(firstAttemptFailed, undefined); + return yield* failure; + }), + } as unknown as WsRpcProtocolClient; + yield* SubscriptionRef.set( + supervisor.session, + Option.some({ ...healthySession, client: failingClient }), + ); + const sendFiber = yield* turnSend + .send(CommandId.make("command-turn-send")) + .pipe( + Effect.provideService(EnvironmentSupervisor.EnvironmentSupervisor, supervisor), + Effect.forkChild, + ); + yield* Deferred.await(firstAttemptFailed); + yield* SubscriptionRef.set( + supervisor.session, + Option.some({ ...healthySession, client: failingClient }), + ); + return { exit: yield* Fiber.await(sendFiber), attempts }; + }, + ); + + it.effect.each(turnSends)("resends a $name lost to a session close", (turnSend) => + Effect.gen(function* () { + const { exit, attempts } = yield* sendFailingFirstAttempt( + turnSend, + Effect.failCause(Cause.interrupt()), + ); + + expect(attempts).toEqual(["command-turn-send", "command-turn-send"]); + expect(Exit.isSuccess(exit)).toBe(true); + }).pipe(Effect.provide(layerTestRandom)), + ); + + it.effect("doesn't resend a new thread's first message the server refused", () => + Effect.gen(function* () { + const { exit, attempts } = yield* sendFailingFirstAttempt( + turnSends[0], + Effect.fail(new Refused()), + ); + + expect(attempts).toEqual(["command-turn-send"]); + expect(Exit.isFailure(exit)).toBe(true); + }).pipe(Effect.provide(layerTestRandom)), + ); + it.effect("Stop with no run left ends the thread's pull request watches", () => Effect.gen(function* () { const link = { diff --git a/packages/client-runtime/src/operations/commands.ts b/packages/client-runtime/src/operations/commands.ts index ee17123e8839f..50e1449e3d5fc 100644 --- a/packages/client-runtime/src/operations/commands.ts +++ b/packages/client-runtime/src/operations/commands.ts @@ -315,28 +315,12 @@ const MAX_LOST_TRANSPORT_RESENDS = 2; // alone would leave the send pending forever. const MESSAGE_DISPATCH_TIMEOUT = "60 seconds"; -const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( - command: Extract, - resendAfterSocketLoss: boolean, -) { +const resendAfterSocketLoss = Effect.fn("EnvironmentCommands.resendAfterSocketLoss")(function* < + A, + E, + R, +>(attempt: Effect.Effect) { const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; - const attempt = dispatch(command).pipe( - Effect.timeoutOrElse({ - duration: MESSAGE_DISPATCH_TIMEOUT, - orElse: () => - Effect.fail( - new EnvironmentRpcUnavailableError({ - environmentId: supervisor.target.environmentId, - ...translatableMessage( - msg("{host} did not confirm the message within 60 seconds.", { - host: supervisor.target.label, - }), - ), - }), - ), - }), - ); - if (!resendAfterSocketLoss) return yield* attempt; for (let resends = 0; ; resends += 1) { const attemptSession = yield* SubscriptionRef.get(supervisor.session); const exit = yield* Effect.exit(attempt); @@ -365,6 +349,30 @@ const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(functio } }); +const dispatchMessage = Effect.fn("EnvironmentCommands.dispatchMessage")(function* ( + command: Extract, + resend: boolean, +) { + const supervisor = yield* EnvironmentSupervisor.EnvironmentSupervisor; + const attempt = dispatch(command).pipe( + Effect.timeoutOrElse({ + duration: MESSAGE_DISPATCH_TIMEOUT, + orElse: () => + Effect.fail( + new EnvironmentRpcUnavailableError({ + environmentId: supervisor.target.environmentId, + ...translatableMessage( + msg("{host} did not confirm the message within 60 seconds.", { + host: supervisor.target.label, + }), + ), + }), + ), + }), + ); + return yield* resend ? resendAfterSocketLoss(attempt) : attempt; +}); + const getProjection = (threadId: ThreadId) => request(ORCHESTRATION_V2_WS_METHODS.getThreadProjection, { threadId }); @@ -784,6 +792,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( input.message.attachments, attachments, ); + const resend = input.resendAfterSocketLoss ?? true; const bootstrap = input.bootstrap?.createThread; const prepareWorktree = input.bootstrap?.prepareWorktree; if (bootstrap !== undefined || prepareWorktree !== undefined) { @@ -815,7 +824,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ? {} : { branch: bootstrap.branch }), }; - return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, { + const launch = request(ORCHESTRATION_V2_WS_METHODS.launchThread, { commandId, creationSource: input.creationSource ?? "web", threadId: input.threadId, @@ -834,10 +843,10 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( attachments, }, }); + return yield* resend ? resendAfterSocketLoss(launch) : launch; } const requestedMode = input.dispatchMode ?? "auto"; - const resendAfterSocketLoss = input.resendAfterSocketLoss ?? true; if (requestedMode === "start") { return yield* dispatchMessage( { @@ -868,7 +877,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(input.freshContext ? { freshContext: true } : {}), dispatchMode: { type: "start_immediately" }, }, - resendAfterSocketLoss, + resend, ); } @@ -899,7 +908,7 @@ export const startThreadTurn = Effect.fn("EnvironmentCommands.startThreadTurn")( ...(requestedMode !== "queue" ? { deliveryIntent: requestedMode } : {}), dispatchMode, }, - resendAfterSocketLoss, + resend, ); }); @@ -1156,25 +1165,29 @@ export const mergeThreadBack = Effect.fn("EnvironmentCommands.mergeThreadBack")( export const resumeThreadQueue = Effect.fn("EnvironmentCommands.resumeThreadQueue")(function* ( input: ResumeThreadQueueInput, ) { - return yield* dispatch({ - ...(input.runId === undefined - ? { type: "queue.resume" as const } - : { type: "queued-run.start" as const, runId: input.runId }), - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - }); + return yield* resendAfterSocketLoss( + dispatch({ + ...(input.runId === undefined + ? { type: "queue.resume" as const } + : { type: "queued-run.start" as const, runId: input.runId }), + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + }), + ); }); export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun")(function* ( input: PromoteQueuedRunInput, ) { - return yield* dispatch({ - type: "queued-message.promote-to-steer", - commandId: yield* allocateCommandId(input), - threadId: input.threadId, - queuedRunId: input.queuedRunId, - targetRunId: input.targetRunId, - }); + return yield* resendAfterSocketLoss( + dispatch({ + type: "queued-message.promote-to-steer", + commandId: yield* allocateCommandId(input), + threadId: input.threadId, + queuedRunId: input.queuedRunId, + targetRunId: input.targetRunId, + }), + ); }); export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* (