Skip to content

Commit a403f39

Browse files
test(web): queued-message edit fixes fail on main without them
Browser tests drive useQueuedRunEdit through navigation, a run starting while the user is on another thread, and a run starting mid-save; each fails against main's hook. A store test pins that the exit watcher holds the thread's runs only while an edit is open and not suspended. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 8937faf commit a403f39

2 files changed

Lines changed: 244 additions & 0 deletions

File tree

Lines changed: 195 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,195 @@
1+
import type { ThreadStructure } from "@t3tools/client-runtime/state/shell";
2+
import {
3+
EnvironmentId,
4+
MessageId,
5+
RunId,
6+
ThreadId,
7+
type ScopedThreadRef,
8+
} from "@t3tools/contracts";
9+
import { useImperativeHandle, type RefObject } from "react";
10+
import { describe, expect, it, vi } from "vite-plus/test";
11+
12+
import { act, render } from "../../../test/render";
13+
import { useComposerDraftStore } from "../../composerDraftStore";
14+
import { AppAtomRegistryProvider, appAtomRegistry } from "../../rpc/atomRegistry";
15+
import { useQueuedRunEdit } from "./useQueuedRunEdit";
16+
17+
interface RunStatus {
18+
readonly id: RunId;
19+
readonly status: string;
20+
}
21+
22+
const mocks = await vi.hoisted(async () => {
23+
const { Atom } = await import("effect/reactivity");
24+
return {
25+
editQueuedRun: vi.fn<(value: unknown) => Promise<{ readonly _tag: "Success" | "Failure" }>>(),
26+
// The projection's runs per thread, written by each test to stand in for the server.
27+
threadRuns: Atom.family((_key: string) =>
28+
Atom.make<ReadonlyArray<RunStatus> | null>(null).pipe(Atom.keepAlive),
29+
),
30+
};
31+
});
32+
33+
vi.mock("../../state/use-atom-command", () => ({
34+
useAtomCommand: () => mocks.editQueuedRun,
35+
}));
36+
37+
const runsKey = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`;
38+
39+
vi.mock("../../state/threads", async () => {
40+
const { Atom } = await import("effect/reactivity");
41+
const key = (ref: ScopedThreadRef) => `${ref.environmentId}:${ref.threadId}`;
42+
return {
43+
threadEnvironment: {
44+
snapshotAtom: () => Atom.make(null),
45+
editQueuedRun: {},
46+
},
47+
environmentThreadDetails: {
48+
statusAtom: () => Atom.make("ready"),
49+
quietThreadAtom: (ref: ScopedThreadRef) =>
50+
Atom.make((get) => {
51+
const runs = get(mocks.threadRuns(key(ref)));
52+
return runs === null ? null : { projection: { runs } };
53+
}),
54+
},
55+
environmentThreadShells: {
56+
threadShellAtom: () => Atom.make(null),
57+
},
58+
};
59+
});
60+
61+
const ENV = EnvironmentId.make("env-1");
62+
const THREAD_A: ScopedThreadRef = { environmentId: ENV, threadId: ThreadId.make("thread-a") };
63+
const THREAD_B: ScopedThreadRef = { environmentId: ENV, threadId: ThreadId.make("thread-b") };
64+
const RUN = RunId.make("run-1");
65+
66+
type HookResult = ReturnType<typeof useQueuedRunEdit>;
67+
68+
function projection(runs: ReadonlyArray<RunStatus>) {
69+
return { runs, messages: [] } as unknown as ThreadStructure;
70+
}
71+
72+
function setRuns(ref: ScopedThreadRef, status: string) {
73+
appAtomRegistry.set(mocks.threadRuns(runsKey(ref)), [{ id: RUN, status }]);
74+
}
75+
76+
function Harness(props: {
77+
readonly threadRef: ScopedThreadRef;
78+
readonly runStatus: string;
79+
readonly hookRef: RefObject<HookResult | null>;
80+
}) {
81+
const result = useQueuedRunEdit({
82+
environmentId: ENV,
83+
routeThreadRef: props.threadRef,
84+
threadDraftTarget: props.threadRef,
85+
activeThreadId: props.threadRef.threadId,
86+
serverProjection: projection([{ id: RUN, status: props.runStatus }]),
87+
promptRef: { current: "" },
88+
composerRef: { current: null },
89+
});
90+
useImperativeHandle(props.hookRef, () => result);
91+
return null;
92+
}
93+
94+
function view(threadRef: ScopedThreadRef, runStatus: string, hook: { current: HookResult | null }) {
95+
return (
96+
<AppAtomRegistryProvider>
97+
<Harness threadRef={threadRef} runStatus={runStatus} hookRef={hook} />
98+
</AppAtomRegistryProvider>
99+
);
100+
}
101+
102+
function setup() {
103+
mocks.editQueuedRun.mockReset();
104+
useComposerDraftStore.setState({ draftsByThreadKey: {}, draftThreadsByThreadKey: {} });
105+
setRuns(THREAD_A, "queued");
106+
setRuns(THREAD_B, "queued");
107+
return { hook: { current: null as HookResult | null } };
108+
}
109+
110+
function requireHook(hook: { current: HookResult | null }): HookResult {
111+
if (hook.current === null) throw new Error("hook did not render");
112+
return hook.current;
113+
}
114+
115+
async function beginChangedEdit(hook: { current: HookResult | null }) {
116+
await act(() =>
117+
requireHook(hook).beginEdit({
118+
runId: RUN,
119+
messageId: MessageId.make("message-1"),
120+
text: "original",
121+
attachments: [],
122+
}),
123+
);
124+
await act(() =>
125+
useComposerDraftStore.getState().setPrompt(requireHook(hook).draftTarget, "changed"),
126+
);
127+
}
128+
129+
const promptOf = (ref: ScopedThreadRef) =>
130+
useComposerDraftStore.getState().getComposerDraft(ref)?.prompt ?? "";
131+
132+
describe("useQueuedRunEdit", () => {
133+
it("keeps an open edit when the user leaves the thread and comes back", async () => {
134+
const { hook } = setup();
135+
await using screen = await render(view(THREAD_A, "queued", hook));
136+
await beginChangedEdit(hook);
137+
138+
await screen.rerender(view(THREAD_B, "queued", hook));
139+
expect(requireHook(hook).isEditing).toBe(false);
140+
await screen.rerender(view(THREAD_A, "queued", hook));
141+
142+
expect(requireHook(hook).editingRunId).toBe(RUN);
143+
expect(
144+
useComposerDraftStore.getState().getComposerDraft(requireHook(hook).draftTarget)?.prompt,
145+
).toBe("changed");
146+
});
147+
148+
it("moves a changed edit into the thread draft when its run starts while the user is away", async () => {
149+
const { hook } = setup();
150+
await using screen = await render(view(THREAD_A, "queued", hook));
151+
await beginChangedEdit(hook);
152+
153+
await screen.rerender(view(THREAD_B, "queued", hook));
154+
expect(promptOf(THREAD_A)).toBe("");
155+
await act(() => setRuns(THREAD_A, "running"));
156+
157+
expect(promptOf(THREAD_A)).toBe("changed");
158+
});
159+
160+
it("does not copy a saved edit into the thread draft when the run starts mid-save", async () => {
161+
const { hook } = setup();
162+
let finishSave: (result: { readonly _tag: "Success" }) => void = () => {};
163+
mocks.editQueuedRun.mockReturnValue(
164+
new Promise((resolve) => {
165+
finishSave = resolve;
166+
}),
167+
);
168+
await using screen = await render(view(THREAD_A, "queued", hook));
169+
await beginChangedEdit(hook);
170+
171+
// Not inside act(): act would hold the projection update until the save settles.
172+
const saved = requireHook(hook).saveEdit(
173+
{
174+
prompt: "changed",
175+
images: [],
176+
files: [],
177+
terminalContexts: [],
178+
reviewComments: [],
179+
previewAnnotations: [],
180+
threadContexts: [],
181+
},
182+
() => {},
183+
);
184+
await vi.waitFor(() => expect(mocks.editQueuedRun).toHaveBeenCalledOnce());
185+
// The server applied the edit and then started the run; the projection
186+
// reports the start before the edit's acknowledgement arrives.
187+
await act(() => setRuns(THREAD_A, "running"));
188+
await screen.rerender(view(THREAD_A, "running", hook));
189+
finishSave({ _tag: "Success" });
190+
await act(() => saved);
191+
192+
expect(requireHook(hook).isEditing).toBe(false);
193+
expect(promptOf(THREAD_A)).toBe("");
194+
});
195+
});

‎packages/client-runtime/src/queuedRunEdit.test.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,55 @@ describe("makeQueuedRunEditStore", () => {
8484
store.resumeExitWatch("env:thread");
8585
expect(exits).toHaveLength(1);
8686
});
87+
88+
// The runs read the thread's detail, a live server subscription; a thread
89+
// with no edit open must not keep it.
90+
it("holds the thread's runs only while an edit is open and watching", () => {
91+
// The registry removes idle nodes in a scheduled task; the test runs those tasks itself.
92+
const tasks: Array<() => void> = [];
93+
const registry = AtomRegistry.make({
94+
scheduleTask: (task) => {
95+
tasks.push(task);
96+
return () => {};
97+
},
98+
});
99+
const settle = () => {
100+
for (const task of tasks.splice(0)) task();
101+
};
102+
const source = Atom.make<ReadonlyArray<QueuedRunStatus> | null>(queued());
103+
let mounted = 0;
104+
const runs = Atom.make((get) => {
105+
mounted += 1;
106+
get.addFinalizer(() => {
107+
mounted -= 1;
108+
});
109+
return get(source);
110+
});
111+
const store = makeQueuedRunEditStore<{ readonly runId: RunId }>({
112+
registry,
113+
label: "test-queued-run-edits",
114+
});
115+
const begin = () =>
116+
store.begin("env:thread", { runId: RUN }, { runs, onRunLeftQueue: () => {} });
117+
118+
begin();
119+
expect(mounted).toBe(1);
120+
store.end("env:thread");
121+
settle();
122+
expect(mounted).toBe(0);
123+
124+
begin();
125+
store.suspendExitWatch("env:thread");
126+
settle();
127+
expect(mounted).toBe(0);
128+
store.resumeExitWatch("env:thread");
129+
expect(mounted).toBe(1);
130+
131+
registry.set(source, []);
132+
expect(store.get("env:thread")).toBeNull();
133+
settle();
134+
expect(mounted).toBe(0);
135+
});
87136
});
88137

89138
describe("makeQueuedRunsAtom", () => {

0 commit comments

Comments
 (0)