Open History to see the last commit
1import { RegistryContext } from "@effect/atom-react";
2import type { EnvironmentThreadState } from "@t3tools/client-runtime/state/threads";
3import { EnvironmentId, MessageId, ThreadId } from "@t3tools/contracts";
4import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
5import {
6 formatComposerContextReference,
7 toComposerContextId,
8} from "@t3tools/shared/composerContextReferences";
9import * as DateTime from "effect/DateTime";
10import * as Option from "effect/Option";
11import { AsyncResult, type Atom, AtomRegistry } from "effect/reactivity";
12import { Profiler, type ComponentProps } from "react";
13import { expect, it, vi } from "vite-plus/test";
14import { page } from "vite-plus/test/browser";
15
16const state = vi.hoisted(() => ({
17 threadState: null as unknown as Atom.Writable<AsyncResult.AsyncResult<EnvironmentThreadState>>,
18 workflow: null as unknown,
19}));
20
21vi.mock(import("@t3tools/client-runtime/state/thread-workflows"), async (importOriginal) => ({
22 ...(await importOriginal()),
23 deriveThreadQueueWorkflowState: (() => state.workflow) as never,
24}));
25
26vi.mock(import("../../state/entities"), async (importOriginal) => ({
27 ...(await importOriginal()),
28 // The linked environment is connected, but its thread is not in the loaded shell.
29 useQuietThreadShell: ((target: { readonly environmentId: string } | null) =>
30 target === null || target.environmentId === "environment:linked"
31 ? null
32 : { title: "Release lead" }) as never,
33}));
34
35vi.mock(import("../../state/environments"), async (importOriginal) => ({
36 ...(await importOriginal()),
37 useEnvironment: ((environmentId: string | null) =>
38 environmentId === "environment:linked" ? { environmentId } : null) as never,
39}));
40
41vi.mock(import("../../state/query"), async (importOriginal) => ({
42 ...(await importOriginal()),
43 useEnvironmentQuery: (() => ({
44 data: { tasks: [{ id: "task:webhook", title: "PR dispatcher" }] },
45 })) as never,
46}));
47
48// The thread detail atoms are real, fed by one state atom the test writes.
49vi.mock(import("../../state/threads"), async (importOriginal) => {
50 const { createEnvironmentThreadDetailAtoms, EMPTY_ENVIRONMENT_THREAD_STATE } =
51 await import("@t3tools/client-runtime/state/threads");
52 const { AsyncResult, Atom } = await import("effect/reactivity");
53 const Option = await import("effect/Option");
54 const { makeThreadProjectionFixture } = await import("../../test-fixtures");
55 state.threadState = Atom.make<AsyncResult.AsyncResult<EnvironmentThreadState>>(
56 AsyncResult.success({
57 ...EMPTY_ENVIRONMENT_THREAD_STATE,
58 data: Option.some(makeThreadProjectionFixture()),
59 }),
60 ).pipe(Atom.keepAlive);
61 return {
62 ...(await importOriginal()),
63 environmentThreadDetails: createEnvironmentThreadDetailAtoms(() => state.threadState),
64 };
65});
66
67vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({
68 ...(await importOriginal()),
69 useAtomCommand: (() => async () => undefined) as never,
70}));
71
72vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({
73 ...(await importOriginal()),
74 useAssetUrls: ((_environmentId: never, resources: ReadonlyArray<{ attachmentId: string }>) =>
75 resources.map((resource) => `https://assets.test/${resource.attachmentId}`)) as never,
76}));
77
78import "~/index.css";
79import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/threads";
80
81import { act, render as renderUi } from "../../../test/render";
82import { makeStreamingTimelineFixture, makeThreadProjectionFixture } from "../../test-fixtures";
83import { QueuedRunsControl } from "./QueuedRunsControl";
84
85function setup() {
86 state.workflow = null;
87}
88
89const baseProps = {
90 environmentId: "environment:test" as never,
91 optimisticMessages: [],
92 threadId: "thread:test" as never,
93 editingRunId: null,
94 editBlockedReason: null,
95 onEditQueuedRun: () => undefined,
96 onCancelEdit: () => undefined,
97 timestampFormat: "locale",
98 onOpenThread: () => undefined,
99} satisfies ComponentProps<typeof QueuedRunsControl>;
100
101async function renderQueue(props: Partial<ComponentProps<typeof QueuedRunsControl>> = {}) {
102 return renderUi(<QueuedRunsControl {...baseProps} {...props} />);
103}
104
105it("previews assistant quotes as readable text and preserves the citation when editing", async () => {
106 setup();
107 const quotedText = "Cache the parsed config per worktree.";
108 const quote = serializeAssistantCitation({
109 version: 1,
110 environmentId: EnvironmentId.make("environment:test"),
111 threadId: ThreadId.make("thread:test"),
112 messageId: MessageId.make("message:assistant"),
113 text: quotedText,
114 start: 0,
115 end: quotedText.length,
116 prefix: "",
117 suffix: "",
118 });
119 const quoteAndText = `${quote}\n\nWhy per worktree?`;
120 const inlineImage = formatComposerContextReference({
121 kind: "image",
122 contextId: toComposerContextId("header"),
123 label: "header.png",
124 });
125 state.workflow = {
126 activeRun: { id: "run:active" },
127 canPromoteToSteer: true,
128 queuedRuns: [
129 {
130 run: { id: "run:quote-only", userMessageId: "message:quote-only" },
131 text: quote,
132 attachments: [],
133 },
134 {
135 run: { id: "run:quote-and-text", userMessageId: "message:quote-and-text" },
136 text: quoteAndText,
137 attachments: [],
138 },
139 {
140 run: { id: "run:inline-image", userMessageId: "message:inline-image" },
141 text: `Make the header look like ${inlineImage} and keep the logo.`,
142 attachments: [{ type: "image", id: "attachment:header", name: "header.png" }],
143 },
144 ],
145 };
146 const onEditQueuedRun = vi.fn();
147 await using _screen = await renderQueue({ onEditQueuedRun });
148
149 await expect.element(page.getByText(quotedText, { exact: true })).toBeVisible();
150 await expect
151 .element(page.getByText(`${quotedText} Why per worktree?`, { exact: true }))
152 .toBeVisible();
153 await expect
154 .element(
155 page.getByText("Make the header look like header.png and keep the logo.", { exact: true }),
156 )
157 .toBeVisible();
158
159 await page.getByRole("button", { name: "Edit queued message", exact: true }).nth(1).click();
160 expect(onEditQueuedRun).toHaveBeenCalledExactlyOnceWith(
161 expect.objectContaining({ text: quoteAndText }),
162 );
163});
164
165it("shows who sent a queued message and folds automation and agent prompts", async () => {
166 setup();
167 const message = (id: string, fields: Record<string, unknown>) => ({
168 id,
169 role: "user",
170 createdAt: DateTime.makeUnsafe("2026-10-27T12:00:00.000Z"),
171 ...fields,
172 });
173 state.workflow = {
174 activeRun: { id: "run:active" },
175 canPromoteToSteer: true,
176 queuedRuns: [
177 [
178 "run:automation",
179 "GitHub labeled a pull request.\nFollow the runbook.",
180 {
181 createdBy: "agent",
182 scheduledTaskId: "task:webhook",
183 },
184 ],
185 [
186 "run:agent",
187 "Review finished.",
188 {
189 createdBy: "agent",
190 creationSource: "provider",
191 senderThreadId: "thread:lead",
192 },
193 ],
194 [
195 "run:linked",
196 "Linked review finished.",
197 {
198 createdBy: "agent",
199 creationSource: "mcp",
200 linkedSender: {
201 environmentId: "environment:linked",
202 threadId: "thread:linked-lead",
203 title: "Title when sent",
204 },
205 },
206 ],
207 [
208 "run:server",
209 "Continue where you left off.",
210 {
211 createdBy: "agent",
212 creationSource: "server",
213 },
214 ],
215 ].map(([runId, text, fields]) => ({
216 run: { id: runId, userMessageId: `${runId}:message` },
217 text,
218 attachments: [],
219 message: message(`${runId}:message`, { text, ...(fields as object) }),
220 })),
221 };
222 const onOpenThread = vi.fn();
223 await using _screen = await renderQueue({ onOpenThread });
224 // Four rows collapse the queue.
225 await page.getByRole("button", { name: "Show all 4 queued" }).click();
226
227 const automation = page.getByRole("button", { name: /PR dispatcher/ });
228 await expect.element(automation).toHaveAttribute("aria-expanded", "false");
229 await expect.element(page.getByText(/Follow the runbook/)).not.toBeInTheDocument();
230 await automation.click();
231 await expect.element(page.getByText(/Follow the runbook/)).toBeVisible();
232 await expect.element(page.getByRole("link", { name: "Open automation" })).toBeInTheDocument();
233
234 await expect.element(page.getByRole("button", { name: /Release lead/ })).toBeVisible();
235 await page.getByRole("button", { name: "Open thread" }).nth(0).click({ force: true });
236 expect(onOpenThread).toHaveBeenCalledExactlyOnceWith("thread:lead", "environment:test");
237 // A sender in a connected linked environment keeps the title it sent and opens there.
238 await expect.element(page.getByRole("button", { name: /Title when sent/ })).toBeVisible();
239 await page.getByRole("button", { name: "Open thread" }).nth(1).click({ force: true });
240 expect(onOpenThread).toHaveBeenLastCalledWith("thread:linked-lead", "environment:linked");
241
242 await expect.element(page.getByText("Sent by T3 Code")).toBeVisible();
243 await expect.element(page.getByText("Continue where you left off.")).toBeVisible();
244});
245
246it("stays inside the timeline scroller instead of growing the chat column", async () => {
247 setup();
248 state.workflow = {
249 activeRun: { id: "run:active" },
250 canPromoteToSteer: true,
251 queuedRuns: [
252 {
253 run: { id: "run:queued", userMessageId: "message:queued" },
254 text: "Later",
255 attachments: [],
256 },
257 ],
258 };
259 // Mirrors ChatView: a scrollable column, a positioned wrapper, then a non-positioned scroller.
260 await using screen = await renderUi(
261 <div data-testid="column" style={{ height: 200, overflowY: "auto" }}>
262 <div style={{ position: "relative", height: "100%" }}>
263 <div style={{ height: "100%", overflowY: "auto" }}>
264 <div style={{ height: 1000 }} />
265 <QueuedRunsControl {...baseProps} />
266 </div>
267 </div>
268 </div>,
269 );
270 await expect.element(page.getByText("Later", { exact: true })).toBeInTheDocument();
271 const column = screen.getByTestId("column").element();
272 expect(column.scrollHeight).toBe(column.clientHeight);
273});
274
275it("does not re-render while assistant text streams into the thread", async () => {
276 setup();
277 state.workflow = {
278 activeRun: { id: "run:active" },
279 canPromoteToSteer: true,
280 canReorder: true,
281 queuedRuns: [
282 {
283 run: { id: "run:queued", userMessageId: "message:queued" },
284 text: "Run the tests next",
285 attachments: [],
286 },
287 ],
288 };
289 const base = makeThreadProjectionFixture();
290 // Each delta replaces only the streaming reply; every other item keeps its identity.
291 const timeline = makeStreamingTimelineFixture().visibleTurnItems;
292 const thread = (text: string, done = false) => {
293 const items = timeline.map((entry) =>
294 entry.item.type === "assistant_message" && entry.item.streaming
295 ? {
296 ...entry,
297 item: done
298 ? { ...entry.item, text, streaming: false, status: "completed" as const }
299 : { ...entry.item, text },
300 }
301 : entry,
302 );
303 return AsyncResult.success<EnvironmentThreadState>({
304 ...EMPTY_ENVIRONMENT_THREAD_STATE,
305 data: Option.some({
306 ...base,
307 turnItems: items.map(({ item }) => item),
308 visibleTurnItems: items,
309 }),
310 });
311 };
312 const registry = AtomRegistry.make();
313 await using stack = new AsyncDisposableStack();
314 stack.defer(() => registry.dispose());
315 registry.set(state.threadState, thread("Hel"));
316 let renders = 0;
317 await using _screen = await renderUi(
318 <RegistryContext.Provider value={registry}>
319 <Profiler id="queue" onRender={() => (renders += 1)}>
320 <QueuedRunsControl {...baseProps} />
321 </Profiler>
322 </RegistryContext.Provider>,
323 );
324 await expect.element(page.getByText("Run the tests next", { exact: true })).toBeVisible();
325 const settled = renders;
326
327 await act(() => registry.set(state.threadState, thread("Hello")));
328 await act(() => registry.set(state.threadState, thread("Hello there")));
329 expect(renders).toBe(settled);
330
331 await act(() => registry.set(state.threadState, thread("Hello there", true)));
332 expect(renders).toBeGreaterThan(settled);
333});