Skip to content

Commit fe03466

Browse files
fix(web): queued edits keep focus in the current thread (#44237)
Co-authored-by: Julius Marminge <[email protected]>
1 parent 4c72563 commit fe03466

4 files changed

Lines changed: 206 additions & 8 deletions

File tree

‎apps/web/src/components/ChatView.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -565,6 +565,7 @@ export default function ChatView(props: ChatViewProps) {
565565
const queuedRunEdit = useQueuedRunEdit({
566566
environmentId,
567567
routeThreadRef,
568+
currentRouteThreadKeyRef,
568569
threadDraftTarget: baseComposerDraftTarget,
569570
activeThreadId: serverThread !== null || draftThread !== null ? threadId : null,
570571
serverProjection,

‎apps/web/src/components/chat/useQueuedRunEdit.browser.test.tsx‎

Lines changed: 84 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
2+
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
23
import {
34
EnvironmentId,
45
ChatAttachmentId,
@@ -9,7 +10,7 @@ import {
910
ThreadId,
1011
type ScopedThreadRef,
1112
} from "@t3tools/contracts";
12-
import { useImperativeHandle, type RefObject } from "react";
13+
import { useImperativeHandle, useLayoutEffect, useRef, type RefObject } from "react";
1314
import { describe, expect, it, vi } from "vite-plus/test";
1415
import {
1516
ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
@@ -30,6 +31,7 @@ import { deriveComposerSendState } from "../ChatView.logic";
3031
import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
3132
import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
3233
import { useQueuedRunEdit } from "./useQueuedRunEdit";
34+
import type { ChatComposerHandle } from "./ChatComposer";
3335
import { readAttachmentUpload, useAttachmentUploadStore } from "../../lib/attachmentUploadQueue";
3436

3537
interface RunStatus {
@@ -128,23 +130,38 @@ function setRuns(ref: ScopedThreadRef, status: string) {
128130
appAtomRegistry.set(mocks.threadRuns(runsKey(ref)), [{ id: RUN, status }]);
129131
}
130132

133+
interface ComposerRefs {
134+
readonly promptRef: RefObject<string>;
135+
readonly composerRef: Parameters<typeof useQueuedRunEdit>[0]["composerRef"];
136+
}
137+
131138
function Harness(props: {
132139
readonly threadRef: ScopedThreadRef;
133140
readonly runStatus: string;
134141
readonly hookRef: RefObject<HookResult | null>;
135142
readonly messages: ReadonlyArray<unknown>;
143+
readonly composer?: ComposerRefs | undefined;
136144
}) {
145+
const threadKey = scopedThreadKey(props.threadRef);
146+
const currentRouteThreadKeyRef = useRef<string | null>(threadKey);
147+
useLayoutEffect(() => {
148+
currentRouteThreadKeyRef.current = threadKey;
149+
return () => {
150+
currentRouteThreadKeyRef.current = null;
151+
};
152+
}, [threadKey]);
137153
const result = useQueuedRunEdit({
138154
environmentId: ENV,
139155
routeThreadRef: props.threadRef,
156+
currentRouteThreadKeyRef,
140157
threadDraftTarget: props.threadRef,
141158
activeThreadId: props.threadRef.threadId,
142159
serverProjection: projection(
143160
[{ id: RUN, status: props.runStatus, modelSelection: savedContent("").modelSelection }],
144161
props.messages,
145162
),
146-
promptRef: { current: "" },
147-
composerRef: { current: null },
163+
promptRef: props.composer?.promptRef ?? { current: "" },
164+
composerRef: props.composer?.composerRef ?? { current: null },
148165
});
149166
useImperativeHandle(props.hookRef, () => result);
150167
const draft = useComposerThreadDraft(result.draftTarget);
@@ -179,10 +196,17 @@ function view(
179196
runStatus: string,
180197
hook: { current: HookResult | null },
181198
messages: ReadonlyArray<unknown> = [],
199+
composer?: ComposerRefs,
182200
) {
183201
return (
184202
<AppAtomRegistryProvider>
185-
<Harness threadRef={threadRef} runStatus={runStatus} hookRef={hook} messages={messages} />
203+
<Harness
204+
threadRef={threadRef}
205+
runStatus={runStatus}
206+
hookRef={hook}
207+
messages={messages}
208+
composer={composer}
209+
/>
186210
</AppAtomRegistryProvider>
187211
);
188212
}
@@ -232,6 +256,62 @@ const promptOf = (ref: ScopedThreadRef) =>
232256
useComposerDraftStore.getState().getComposerDraft(ref)?.prompt ?? "";
233257

234258
describe("useQueuedRunEdit", () => {
259+
it.each([
260+
{ navigation: "switches before the reply", resets: false, focuses: false },
261+
{ navigation: "switches before the frame", resets: true, focuses: false },
262+
{ navigation: "stays on thread", resets: true, focuses: true },
263+
])("finishes a successful queued edit when the user $navigation", async (scenario) => {
264+
const { hook } = setup();
265+
const requested = Promise.withResolvers<void>();
266+
const reply = Promise.withResolvers<{ readonly _tag: "Success" }>();
267+
mocks.editQueuedRun.mockImplementation(() => {
268+
requested.resolve();
269+
return reply.promise;
270+
});
271+
const focusAtEnd = vi.fn();
272+
const resetCursorState = vi.fn();
273+
const composer: ComposerRefs = {
274+
promptRef: { current: "changed" },
275+
composerRef: { current: null },
276+
};
277+
await using screen = await render(view(THREAD_A, "queued", hook, [], composer));
278+
const frames: FrameRequestCallback[] = [];
279+
using _frame = vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
280+
frames.push(callback);
281+
return 0;
282+
});
283+
await beginChangedEdit(hook);
284+
await act(() => {
285+
for (const frame of frames.splice(0)) frame(0);
286+
});
287+
composer.composerRef.current = {
288+
focusAtEnd,
289+
resetCursorState,
290+
} as unknown as ChatComposerHandle;
291+
292+
const setThreadError = vi.fn();
293+
const saved = requireHook(hook).saveEdit(savedContent("changed"), setThreadError);
294+
await requested.promise;
295+
const openOtherThread = async () => {
296+
await screen.rerender(view(THREAD_B, "queued", hook, [], composer));
297+
composer.promptRef.current = "other thread draft";
298+
};
299+
if (scenario.navigation === "switches before the reply") await openOtherThread();
300+
reply.resolve({ _tag: "Success" });
301+
await act(() => saved);
302+
expect(setThreadError).toHaveBeenCalledExactlyOnceWith(THREAD_A.threadId, null);
303+
expect(resetCursorState).toHaveBeenCalledTimes(Number(scenario.resets));
304+
305+
if (scenario.navigation === "switches before the frame") await openOtherThread();
306+
await act(() => {
307+
for (const frame of frames.splice(0)) frame(0);
308+
});
309+
expect(focusAtEnd).toHaveBeenCalledTimes(Number(scenario.focuses));
310+
expect(composer.promptRef.current).toBe(
311+
scenario.navigation === "stays on thread" ? "" : "other thread draft",
312+
);
313+
});
314+
235315
it.each(["", "Ultrathink:\n"])(
236316
"opens attachment-only edits without the placeholder and preserves effort on save (%j)",
237317
async (prefix) => {

‎apps/web/src/components/chat/useQueuedRunEdit.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -213,6 +213,7 @@ function useEditQueuedRunCommand() {
213213
export function useQueuedRunEdit(input: {
214214
readonly environmentId: EnvironmentId;
215215
readonly routeThreadRef: ScopedThreadRef;
216+
readonly currentRouteThreadKeyRef: { readonly current: string | null };
216217
readonly threadDraftTarget: ComposerThreadTarget;
217218
readonly activeThreadId: ThreadId | null;
218219
readonly serverProjection: ThreadStructure | null;
@@ -222,6 +223,7 @@ export function useQueuedRunEdit(input: {
222223
const {
223224
environmentId,
224225
routeThreadRef,
226+
currentRouteThreadKeyRef,
225227
threadDraftTarget,
226228
activeThreadId,
227229
serverProjection,
@@ -274,7 +276,9 @@ export function useQueuedRunEdit(input: {
274276
}));
275277

276278
const focusComposerSoon = () => {
277-
window.requestAnimationFrame(() => composerRef.current?.focusAtEnd());
279+
window.requestAnimationFrame(() => {
280+
if (currentRouteThreadKeyRef.current === editKey) composerRef.current?.focusAtEnd();
281+
});
278282
};
279283
const clearEditDraft = (runId: RunId) => {
280284
const target = queuedRunEditDraftId(routeThreadRef, runId);
@@ -541,10 +545,12 @@ export function useQueuedRunEdit(input: {
541545
if (error !== null) return;
542546
if (changedAfterSave) return;
543547
releaseDraftAttachments(newAttachments);
544-
promptRef.current = "";
545548
clearEditDraft(editing.runId);
546-
composerRef.current?.resetCursorState();
547-
focusComposerSoon();
549+
if (currentRouteThreadKeyRef.current === editKey) {
550+
promptRef.current = "";
551+
composerRef.current?.resetCursorState();
552+
focusComposerSoon();
553+
}
548554
// A plain submit means "Update queued message"; only the opposite-action shortcut or
549555
// modifier-click asks to steer, as it does for a new follow-up.
550556
if (submission?.submissionIntent === "alternate" && submission.dispatchMode === "steer") {
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
/// <reference lib="dom" />
2+
import type { RuntimeMode } from "@t3tools/contracts";
3+
import { expect } from "e2e";
4+
import * as Effect from "effect/Effect";
5+
6+
import { T3_HOME } from "../e2e.config.ts";
7+
import { makeState, rpcClient, runPromise, test, WEB } from "./t3.ts";
8+
9+
declare global {
10+
interface Window {
11+
pendingQueueEdit: {
12+
requested: Promise<void>;
13+
release: () => Promise<string>;
14+
};
15+
}
16+
}
17+
18+
test(
19+
"Saving a queued edit leaves keyboard focus in the thread just opened",
20+
WEB,
21+
async ({ t3, app, browser, screen }) => {
22+
// Returns the previous mode so the shared scenario server can be put back afterwards.
23+
const setRuntimeMode = (mode: RuntimeMode) =>
24+
runPromise(
25+
Effect.gen(function* () {
26+
const client = yield* rpcClient(T3_HOME, app.baseUrl ?? "");
27+
const previous = (yield* client["server.getSettings"]({})).defaultRuntimeMode;
28+
yield* client["server.updateSettings"]({ patch: { defaultRuntimeMode: mode } });
29+
return previous;
30+
}).pipe(Effect.scoped),
31+
);
32+
// Supervised mode makes the approval recording wait for an answer, which keeps the run queued.
33+
const previousMode = await setRuntimeMode("approval-required");
34+
try {
35+
const project = await t3.project("demo");
36+
const source = await t3.thread({
37+
project,
38+
title: "Queued work",
39+
messages: ["Change the file"],
40+
model: "approval",
41+
});
42+
await t3.thread({ project, title: "Other work", messages: ["Second thread prompt"] });
43+
const { cli } = makeState(T3_HOME);
44+
await runPromise(cli(["thread", "send", source.threadId, "Queued message"]));
45+
46+
await browser.addInitScript(() => {
47+
const requested = Promise.withResolvers<void>();
48+
const replied = Promise.withResolvers<string>();
49+
let forward = () => {};
50+
const send = WebSocket.prototype.send;
51+
WebSocket.prototype.send = function (data) {
52+
if (typeof data !== "string" || !data.includes('"queued-run.edit"')) {
53+
return send.call(this, data);
54+
}
55+
const request = JSON.parse(data);
56+
if (
57+
request.tag !== "orchestration.dispatchCommand" ||
58+
request.payload?.type !== "queued-run.edit" ||
59+
!data.includes("Edited queued message")
60+
) {
61+
return send.call(this, data);
62+
}
63+
this.addEventListener("message", (event) => {
64+
const exit = [JSON.parse(String(event.data))]
65+
.flat()
66+
.find(
67+
(frame) => frame._tag === "Exit" && String(frame.requestId) === String(request.id),
68+
);
69+
if (exit) replied.resolve(String(exit.exit?._tag));
70+
});
71+
forward = () => send.call(this, data);
72+
requested.resolve();
73+
};
74+
window.pendingQueueEdit = {
75+
requested: requested.promise,
76+
release: () => {
77+
forward();
78+
return replied.promise;
79+
},
80+
};
81+
});
82+
83+
await t3.open(source);
84+
const editQueued = screen.getByRole("button", "Edit queued message");
85+
await expect(editQueued).toBeEnabled({ timeout: 60_000 });
86+
await editQueued.tap();
87+
await screen.getByRole("textbox").fill("Edited queued message");
88+
await screen.getByRole("button", "Update queued message", { exact: false }).tap();
89+
await browser.evaluate(() => window.pendingQueueEdit.requested.then(() => null));
90+
await screen.getByRole("button", "Other work", { exact: false }).tap();
91+
await screen.getByText("Second thread prompt", { exact: true }).tap();
92+
const focusedComposer = browser.locator(
93+
'[data-chat-composer-form="true"] [contenteditable="true"]:focus',
94+
);
95+
await focusedComposer.waitFor({ state: "hidden" });
96+
97+
const saved = await browser.evaluate(async () => {
98+
const exit = await window.pendingQueueEdit.release();
99+
await new Promise<void>((resolve) =>
100+
requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
101+
);
102+
return exit;
103+
});
104+
expect(saved).toBe("Success");
105+
await app.screenshot("other-thread-after-queued-edit-saves");
106+
await expect(focusedComposer).toBeHidden({ timeout: 3000 });
107+
} finally {
108+
await setRuntimeMode(previousMode);
109+
}
110+
},
111+
);

0 commit comments

Comments
 (0)