@devries-cameron20 / t3code Mirror · read-only / commits / efd683ccc3
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 21, 19:45 UTC

fix(web): a failed send leaves the timeline when a new draft was typed (#35102)

Julius Marminge committed Nov 12, 2026 at 02:47 UTC efd683ccc3508719b13f977b3ad3898cfbd76635
3 files changed +107 -9
apps/web/src/components/ChatView.browser.test.tsx
+38
@@ -18,7 +18,9 @@ import { getRouter } from "~/router";
18 import {
19 ENVIRONMENT_ID,
20 PROJECT_ID,
21 + dispatchedCommands,
22 installFakeEnvironment,
23 + rejectPendingCommand,
24 threadWithHistory,
25 type FakeDriver,
26 } from "../../test/fakeEnvironment";
@@ -191,3 +193,39 @@ it("a stashed prompt ending in a file chip restores with the chip", async () =>
193 expect(editor.element().textContent).not.toContain("[package.json](package.json)");
194 await expect.element(chip).toBeVisible();
195 });
196 +
197 +it("a rejected send leaves the timeline when a new draft was typed meanwhile", async () => {
198 + const thread = threadWithHistory("rejected-send", 1);
199 + using _environment = installFakeEnvironment([thread], {
200 + acceptCommands: true,
201 + holdCommand: (command) => command.type === "message.dispatch",
202 + });
203 + __setClientSettingsForTests({
204 + ...DEFAULT_CLIENT_SETTINGS,
205 + onboardingCompletedAt: "2026-01-01T00:00:00.000Z",
206 + });
207 + const router = getRouter(
208 + createMemoryHistory({ initialEntries: [`/${ENVIRONMENT_ID}/${thread.id}`] }),
209 + );
210 + await router.load();
211 + await using _app = await render(<AppRoot router={router} />, {
212 + // AppRoot brings its own router.
213 + router: false,
214 + });
215 + await expect.element(page.getByText(`Answer 0 for ${thread.id}.`)).toBeVisible();
216 +
217 + const editor = page.getByTestId("composer-editor");
218 + await userEvent.click(editor);
219 + await userEvent.keyboard("Failed prompt{Enter}");
220 + await vi.waitFor(() =>
221 + expect(dispatchedCommands().map((command) => command.type)).toContain("message.dispatch"),
222 + );
223 + await expect.element(page.getByText("Failed prompt")).toBeVisible();
224 + await userEvent.keyboard("Next draft");
225 +
226 + await rejectPendingCommand("Attachment 'sample.png' cannot be sent.");
227 +
228 + await expect.element(page.getByText("Attachment 'sample.png' cannot be sent.")).toBeVisible();
229 + await expect.element(page.getByText("Failed prompt")).not.toBeInTheDocument();
230 + expect(editor.element().textContent).toContain("Next draft");
231 +});
apps/web/src/components/chat/useComposerSend.ts
+32 -7
@@ -60,6 +60,7 @@ import {
60 import { type ChatMessage, DEFAULT_INTERACTION_MODE } from "../../types";
61 import { recordPromptSent } from "../GitHubStarPrompt";
62 import { stackedThreadToast, toastManager } from "../ui/toast";
63 +import { writeTextToClipboard } from "~/hooks/useCopyToClipboard";
64 import { newMessageId, newThreadId } from "~/lib/utils";
65 import { useNewThreadHandler } from "../../hooks/useHandleNewThread";
66 import { buildThreadRouteParams } from "../../threadRoutes";
@@ -1385,17 +1386,41 @@ export function useComposerSend(input: ComposerSendInput) {
1386 );
1387 clearBackgroundDraftSubmissionByRef(scopeThreadRef(environmentId, threadIdForSend));
1388 }
1389 + // Only an acknowledged send replaces its optimistic row, so a failed one leaves here.
1390 + setOptimisticUserMessages((existing) => {
1391 + const next = existing.filter((message) => message.id !== messageIdForSend);
1392 + return next.length === existing.length ? existing : next;
1393 + });
1394 + // A restored draft clones its images, so the sent copies are no longer used.
1395 + optimisticBlobPreviews.release(optimisticMessage);
1396 if (
1389 - !composerDraftHasUserContent(
1397 + composerDraftHasUserContent(
1398 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget),
1399 )
1400 ) {
1393 - setOptimisticUserMessages((existing) => {
1394 - const next = existing.filter((message) => message.id !== messageIdForSend);
1395 - return next.length === existing.length ? existing : next;
1396 - });
1397 - // The restored draft clones its images, so the sent copies are no longer used.
1398 - optimisticBlobPreviews.release(optimisticMessage);
1401 + // A draft typed meanwhile keeps the composer, so the failed text stays reachable here.
1402 + const failedText = sendSnapshot.draftText;
1403 + if (failedText.trim().length > 0) {
1404 + toastManager.add(
1405 + stackedThreadToast({
1406 + type: "error",
1407 + title: isAtomCommandInterrupted(failure)
1408 + ? "Message may not have been sent"
1409 + : "Message not sent",
1410 + description: "Your new draft was kept. Copy the failed message to send it again.",
1411 + // The toast holds the only copy of the failed text, so it stays until dismissed.
1412 + timeout: 0,
1413 + data: { hideCopyButton: true },
1414 + actionProps: {
1415 + children: "Copy message",
1416 + onClick: () => {
1417 + void writeTextToClipboard(failedText, "failed message").catch(() => undefined);
1418 + },
1419 + },
1420 + }),
1421 + );
1422 + }
1423 + } else {
1424 const retryComposerImages = restoreComposerDraft(composerDraftTarget, sendSnapshot);
1425 if (currentRouteThreadKeyRef.current === routeThreadKey) {
1426 promptRef.current = sendSnapshot.draftText;
apps/web/test/fakeEnvironment.ts
+37 -2
@@ -7,6 +7,7 @@ import {
7 EventId,
8 ExecutionEnvironmentDescriptor,
9 MessageId,
10 + OrchestrationV2DispatchCommandError,
11 ORCHESTRATION_PROTOCOL_VERSION,
12 ORCHESTRATION_V2_WS_METHODS,
13 ProjectId,
@@ -41,6 +42,7 @@ import type { WsRpcProtocolClient } from "@t3tools/client-runtime/rpc";
42 import { DEFAULT_RESOLVED_KEYBINDINGS } from "@t3tools/shared/keybindings";
43 import { APP_VERSION } from "~/branding";
44 import * as DateTime from "effect/DateTime";
45 +import * as Deferred from "effect/Deferred";
46 import * as Effect from "effect/Effect";
47 import * as Queue from "effect/Queue";
48 import type * as Scope from "effect/Scope";
@@ -361,6 +363,11 @@ let terminalMetadataSubscriber: Queue.Queue<TerminalMetadataStreamEvent> | null
363 let threads: ReadonlyArray<FakeThread> = [];
364 let dispatched: OrchestrationV2Command[] = [];
365 let acceptCommands = false;
366 +let holdCommand: (command: OrchestrationV2Command) => boolean = () => false;
367 +let pendingDispatches: Array<{
368 + readonly command: OrchestrationV2Command;
369 + readonly reply: Deferred.Deferred<never, OrchestrationV2DispatchCommandError>;
370 +}> = [];
371 let sequence = 1;
372 let vcsStatusSubscriber: Queue.Queue<VcsStatusStreamEvent> | null = null;
373
@@ -383,7 +390,11 @@ const handlers: Record<string, (input: never) => unknown> = {
390 [ORCHESTRATION_V2_WS_METHODS.dispatchCommand]: (command: OrchestrationV2Command) =>
391 Effect.suspend(() => {
392 dispatched.push(command);
386 - return acceptCommands ? Effect.succeed({ sequence: sequence + 1 }) : Effect.never;
393 + if (acceptCommands && !holdCommand(command))
394 + return Effect.succeed({ sequence: sequence + 1 });
395 + const reply = Deferred.makeUnsafe<never, OrchestrationV2DispatchCommandError>();
396 + pendingDispatches.push({ command, reply });
397 + return Deferred.await(reply);
398 }),
399 [WS_METHODS.subscribeTerminalMetadata]: () =>
400 subscribe<TerminalMetadataStreamEvent>([{ type: "snapshot", terminals: [] }], (queue) => {
@@ -495,12 +506,18 @@ const encodedDescriptor = Schema.encodeSync(ExecutionEnvironmentDescriptor)(
506 /** Serves the environment's HTTP API and these threads until disposed. */
507 export function installFakeEnvironment(
508 fixtures: ReadonlyArray<FakeThread>,
498 - options?: { readonly acceptCommands?: boolean; readonly providers?: ReadonlyArray<unknown> },
509 + options?: {
510 + readonly acceptCommands?: boolean;
511 + /** Commands left unanswered even when accepting, until `rejectPendingCommand`. */
512 + readonly holdCommand?: (command: OrchestrationV2Command) => boolean;
513 + readonly providers?: ReadonlyArray<unknown>;
514 + },
515 ): Disposable {
516 threads = fixtures;
517 baseServerConfig = makeServerConfig(options?.providers ?? [CODEX_PROVIDER]);
518 dispatched = [];
519 acceptCommands = options?.acceptCommands === true;
520 + holdCommand = options?.holdCommand ?? (() => false);
521 globalThis.fetch = async (input, init) => {
522 const url = new URL(input instanceof Request ? input.url : String(input), window.location.href);
523 if (url.origin !== window.location.origin) return realFetch(input, init);
@@ -525,10 +542,28 @@ export function installFakeEnvironment(
542 baseServerConfig = makeServerConfig([CODEX_PROVIDER]);
543 dispatched = [];
544 acceptCommands = false;
545 + holdCommand = () => false;
546 + pendingDispatches = [];
547 },
548 };
549 }
550
551 +/** Answers the oldest unanswered command with the server's rejection. */
552 +export async function rejectPendingCommand(message: string): Promise<void> {
553 + const pending = pendingDispatches.shift();
554 + if (!pending) throw new Error("No pending command");
555 + await Effect.runPromise(
556 + Deferred.fail(
557 + pending.reply,
558 + new OrchestrationV2DispatchCommandError({
559 + commandId: pending.command.commandId,
560 + commandType: pending.command.type,
561 + message,
562 + }),
563 + ),
564 + );
565 +}
566 +
567 /** Commands the app dispatched to the environment, oldest first. */
568 export function dispatchedCommands(): ReadonlyArray<OrchestrationV2Command> {
569 return dispatched;