Open History to see the last commit
1import { RegistryContext } from "@effect/atom-react";
2import type { EnvironmentThreadState } from "@t3tools/client-runtime/state/threads";
3import {
4 CommandId,
5 EnvironmentId,
6 MessageId,
7 OrchestrationV2DispatchCommandError,
8 ThreadId,
9} from "@t3tools/contracts";
10import { serializeAssistantCitation } from "@t3tools/shared/assistantCitations";
11import {
12 formatComposerContextReference,
13 toComposerContextId,
14} from "@t3tools/shared/composerContextReferences";
15import * as Cause from "effect/Cause";
16import * as DateTime from "effect/DateTime";
17import * as Option from "effect/Option";
18import { AsyncResult, type Atom, AtomRegistry } from "effect/reactivity";
19import { createRef, Profiler, useState, type ComponentProps } from "react";
20import { expect, it, vi } from "vite-plus/test";
21import { page, userEvent } from "vite-plus/test/browser";
22
23const state = vi.hoisted(() => ({
24 threadState: null as unknown as Atom.Writable<AsyncResult.AsyncResult<EnvironmentThreadState>>,
25 workflow: null as unknown,
26 commandResult: undefined as unknown,
27 commandCalls: 0,
28}));
29
30vi.mock(import("@t3tools/client-runtime/state/thread-workflows"), async (importOriginal) => ({
31 ...(await importOriginal()),
32 deriveThreadQueueWorkflowState: (() => state.workflow) as never,
33}));
34
35vi.mock(import("../../state/entities"), async (importOriginal) => ({
36 ...(await importOriginal()),
37 // The linked environment is connected, but its thread is not in the loaded shell.
38 useQuietThreadShell: ((target: { readonly environmentId: string } | null) =>
39 target === null || target.environmentId === "environment:linked"
40 ? null
41 : { title: "Release lead" }) as never,
42}));
43
44vi.mock(import("../../state/environments"), async (importOriginal) => ({
45 ...(await importOriginal()),
46 useEnvironment: ((environmentId: string | null) =>
47 environmentId === "environment:linked" ? { environmentId } : null) as never,
48}));
49
50vi.mock(import("../../state/query"), async (importOriginal) => ({
51 ...(await importOriginal()),
52 useEnvironmentQuery: (() => ({
53 data: { tasks: [{ id: "task:webhook", title: "PR dispatcher" }] },
54 })) as never,
55}));
56
57// The thread detail atoms are real, fed by one state atom the test writes.
58vi.mock(import("../../state/threads"), async (importOriginal) => {
59 const { createEnvironmentThreadDetailAtoms, EMPTY_ENVIRONMENT_THREAD_STATE } =
60 await import("@t3tools/client-runtime/state/threads");
61 const { AsyncResult, Atom } = await import("effect/reactivity");
62 const Option = await import("effect/Option");
63 const { makeThreadProjectionFixture } = await import("../../test-fixtures");
64 state.threadState = Atom.make<AsyncResult.AsyncResult<EnvironmentThreadState>>(
65 AsyncResult.success({
66 ...EMPTY_ENVIRONMENT_THREAD_STATE,
67 data: Option.some(makeThreadProjectionFixture()),
68 }),
69 ).pipe(Atom.keepAlive);
70 return {
71 ...(await importOriginal()),
72 environmentThreadDetails: createEnvironmentThreadDetailAtoms(() => state.threadState),
73 };
74});
75
76vi.mock(import("../../state/use-atom-command"), async (importOriginal) => ({
77 ...(await importOriginal()),
78 useAtomCommand: (() => async () => {
79 state.commandCalls += 1;
80 return state.commandResult;
81 }) as never,
82}));
83
84vi.mock(import("../../assets/assetUrls"), async (importOriginal) => ({
85 ...(await importOriginal()),
86 useAssetUrls: ((_environmentId: never, resources: ReadonlyArray<{ attachmentId: string }>) =>
87 resources.map((resource) => `https://assets.test/${resource.attachmentId}`)) as never,
88}));
89
90import "~/index.css";
91import { EMPTY_ENVIRONMENT_THREAD_STATE } from "@t3tools/client-runtime/state/threads";
92
93import { act, fakeTimers, render as renderUi } from "../../../test/render";
94import { makeStreamingTimelineFixture, makeThreadProjectionFixture } from "../../test-fixtures";
95import { SharedTooltipProvider } from "../ui/shared-tooltip";
96import { ToastProvider } from "../ui/toast";
97import { QueuedRunsControl, type QueuedRunsControlHandle } from "./QueuedRunsControl";
98import { ExpandedImageDialog } from "./ExpandedImageDialog";
99import type { ExpandedImagePreview } from "./ExpandedImagePreview";
100
101function setup() {
102 state.workflow = null;
103 state.commandResult = undefined;
104 state.commandCalls = 0;
105}
106
107const baseProps = {
108 environmentId: "environment:test" as never,
109 optimisticMessages: [],
110 threadId: "thread:test" as never,
111 editingRunId: null,
112 editBlockedReason: null,
113 onEditQueuedRun: () => undefined,
114 onCancelEdit: () => undefined,
115 timestampFormat: "locale",
116 onOpenThread: () => undefined,
117 onImageExpand: () => undefined,
118} satisfies ComponentProps<typeof QueuedRunsControl>;
119
120async function renderQueue(props: Partial<ComponentProps<typeof QueuedRunsControl>> = {}) {
121 return renderUi(<QueuedRunsControl {...baseProps} {...props} />);
122}
123
124it.each([false, true])(
125 "opens queued images in the existing gallery, pending=%s",
126 async (pending) => {
127 setup();
128 const attachments = ["first.png", "second.png"].map((name) => ({
129 type: "image" as const,
130 id: name,
131 name,
132 mimeType: "image/png",
133 sizeBytes: 128,
134 }));
135 state.workflow = {
136 activeRun: null,
137 queuedRuns: pending
138 ? []
139 : [
140 {
141 run: { id: "run:queued", userMessageId: "message:queued" },
142 text: "Later",
143 attachments,
144 },
145 ],
146 };
147 function QueueWithGallery() {
148 const [preview, setPreview] = useState<ExpandedImagePreview | null>(null);
149 return (
150 <>
151 <QueuedRunsControl
152 {...baseProps}
153 optimisticMessages={
154 pending
155 ? [
156 {
157 id: MessageId.make("message:pending"),
158 inputIntent: "queued_turn",
159 text: "Later",
160 attachments: attachments.map((attachment) => ({
161 ...attachment,
162 previewUrl: `https://assets.test/${attachment.id}`,
163 })),
164 },
165 ]
166 : []
167 }
168 onImageExpand={setPreview}
169 />
170 {preview ? (
171 <ExpandedImageDialog preview={preview} onClose={() => setPreview(null)} />
172 ) : null}
173 </>
174 );
175 }
176 await using _screen = await renderUi(<QueueWithGallery />);
177
178 await page.getByRole("button", { name: "Preview second.png", exact: true }).click();
179 await expect.element(page.getByRole("dialog")).toBeVisible();
180 await expect.element(page.getByText("second.png (2/2)", { exact: true })).toBeVisible();
181 await page.getByRole("button", { name: "Previous media", exact: true }).click();
182 await expect.element(page.getByText("first.png (1/2)", { exact: true })).toBeVisible();
183 await page.getByRole("button", { name: "Close image preview", exact: true }).click();
184 await expect.element(page.getByRole("dialog")).not.toBeInTheDocument();
185 await expect.element(page.getByText("Later", { exact: true })).toBeVisible();
186 },
187);
188
189it("links queued assistant quotes to their source and preserves the citation when editing", async () => {
190 setup();
191 const quotedText = "Cache the parsed config per worktree.";
192 const citation = {
193 version: 1,
194 environmentId: EnvironmentId.make("environment:linked"),
195 threadId: ThreadId.make("thread:test"),
196 messageId: MessageId.make("message:assistant"),
197 text: quotedText,
198 start: 0,
199 end: quotedText.length,
200 prefix: "",
201 suffix: "",
202 } as const;
203 const quote = serializeAssistantCitation(citation);
204 const comment = "What happens when a worktree is removed?";
205 const commentedQuote = serializeAssistantCitation({ ...citation, comment });
206 const quoteAndText = `About this decision:\n\n${commentedQuote}\n\nWhy per worktree?`;
207 const inlineImage = formatComposerContextReference({
208 kind: "image",
209 contextId: toComposerContextId("header"),
210 label: "header.png",
211 });
212 state.workflow = {
213 activeRun: { id: "run:active" },
214 canPromoteToSteer: true,
215 queuedRuns: [
216 {
217 run: { id: "run:quote-and-text", userMessageId: "message:quote-and-text" },
218 text: quoteAndText,
219 attachments: [],
220 },
221 {
222 run: { id: "run:inline-image", userMessageId: "message:inline-image" },
223 text: `Make the header look like ${inlineImage} and keep the logo.`,
224 attachments: [{ type: "image", id: "attachment:header", name: "header.png" }],
225 },
226 ],
227 };
228 const onEditQueuedRun = vi.fn();
229 await using _screen = await renderQueue({
230 onEditQueuedRun,
231 optimisticMessages: [
232 { id: MessageId.make("message:pending"), inputIntent: "queued_turn", text: quote },
233 ],
234 });
235
236 const commentedChip = page.getByRole("link", { name: `View cited assistant text: ${comment}` });
237 await expect.element(commentedChip).toBeVisible();
238 expect(commentedChip.element().getAttribute("href")).toMatch(
239 /^\/environment%3Alinked\/thread%3Atest#assistant-citation=/,
240 );
241 await expect
242 .element(page.getByRole("link", { name: `View cited assistant text: ${quotedText}` }))
243 .toBeVisible();
244 await expect
245 .element(
246 page.getByText("Make the header look like header.png and keep the logo.", { exact: true }),
247 )
248 .toBeVisible();
249
250 await page.getByRole("button", { name: "Edit queued message", exact: true }).nth(0).click();
251 expect(onEditQueuedRun).toHaveBeenCalledExactlyOnceWith(
252 expect.objectContaining({ text: quoteAndText }),
253 );
254});
255
256it("shows who sent a queued message and folds automation and agent prompts", async () => {
257 setup();
258 const message = (id: string, fields: Record<string, unknown>) => ({
259 id,
260 role: "user",
261 createdAt: DateTime.makeUnsafe("2026-10-27T12:00:00.000Z"),
262 ...fields,
263 });
264 state.workflow = {
265 activeRun: { id: "run:active" },
266 canPromoteToSteer: true,
267 queuedRuns: [
268 [
269 "run:automation",
270 "GitHub labeled a pull request.\nFollow the runbook.",
271 {
272 createdBy: "agent",
273 scheduledTaskId: "task:webhook",
274 },
275 ],
276 [
277 "run:agent",
278 "Review finished.",
279 {
280 createdBy: "agent",
281 creationSource: "provider",
282 senderThreadId: "thread:lead",
283 },
284 ],
285 [
286 "run:linked",
287 "Linked review finished.",
288 {
289 createdBy: "agent",
290 creationSource: "mcp",
291 linkedSender: {
292 environmentId: "environment:linked",
293 threadId: "thread:linked-lead",
294 title: "Title when sent",
295 },
296 },
297 ],
298 [
299 "run:server",
300 "Continue where you left off.",
301 {
302 createdBy: "agent",
303 creationSource: "server",
304 },
305 ],
306 ].map(([runId, text, fields]) => ({
307 run: { id: runId, userMessageId: `${runId}:message` },
308 text,
309 attachments: [],
310 message: message(`${runId}:message`, { text, ...(fields as object) }),
311 })),
312 };
313 const onOpenThread = vi.fn();
314 await using _screen = await renderQueue({ onOpenThread });
315 // Four rows collapse the queue.
316 await page.getByRole("button", { name: "Show all 4 queued" }).click();
317
318 const automation = page.getByRole("button", { name: /PR dispatcher/ });
319 await expect.element(automation).toHaveAttribute("aria-expanded", "false");
320 await expect.element(page.getByText(/Follow the runbook/)).not.toBeInTheDocument();
321 await automation.click();
322 await expect.element(page.getByText(/Follow the runbook/)).toBeVisible();
323 await expect.element(page.getByRole("link", { name: "Open automation" })).toBeInTheDocument();
324
325 await expect.element(page.getByRole("button", { name: /Release lead/ })).toBeVisible();
326 await page.getByRole("button", { name: "Open thread" }).nth(0).click({ force: true });
327 expect(onOpenThread).toHaveBeenCalledExactlyOnceWith("thread:lead", "environment:test");
328 // A sender in a connected linked environment keeps the title it sent and opens there.
329 await expect.element(page.getByRole("button", { name: /Title when sent/ })).toBeVisible();
330 await page.getByRole("button", { name: "Open thread" }).nth(1).click({ force: true });
331 expect(onOpenThread).toHaveBeenLastCalledWith("thread:linked-lead", "environment:linked");
332
333 await expect.element(page.getByText("Sent by T3 Code")).toBeVisible();
334 await expect.element(page.getByText("Continue where you left off.")).toBeVisible();
335});
336
337it("stays inside the timeline scroller instead of growing the chat column", async () => {
338 setup();
339 state.workflow = {
340 activeRun: { id: "run:active" },
341 canPromoteToSteer: true,
342 queuedRuns: [
343 {
344 run: { id: "run:queued", userMessageId: "message:queued" },
345 text: "Later",
346 attachments: [],
347 },
348 ],
349 };
350 // Mirrors ChatView: a scrollable column, a positioned wrapper, then a non-positioned scroller.
351 await using screen = await renderUi(
352 <div data-testid="column" style={{ height: 200, overflowY: "auto" }}>
353 <div style={{ position: "relative", height: "100%" }}>
354 <div style={{ height: "100%", overflowY: "auto" }}>
355 <div style={{ height: 1000 }} />
356 <QueuedRunsControl {...baseProps} />
357 </div>
358 </div>
359 </div>,
360 );
361 await expect.element(page.getByText("Later", { exact: true })).toBeInTheDocument();
362 const column = screen.getByTestId("column").element();
363 expect(column.scrollHeight).toBe(column.clientHeight);
364});
365
366it("does not re-render while assistant text streams into the thread", async () => {
367 setup();
368 state.workflow = {
369 activeRun: { id: "run:active" },
370 canPromoteToSteer: true,
371 canReorder: true,
372 queuedRuns: [
373 {
374 run: { id: "run:queued", userMessageId: "message:queued" },
375 text: "Run the tests next",
376 attachments: [],
377 },
378 ],
379 };
380 const base = makeThreadProjectionFixture();
381 // Each delta replaces only the streaming reply; every other item keeps its identity.
382 const timeline = makeStreamingTimelineFixture().visibleTurnItems;
383 const thread = (text: string, done = false) => {
384 const items = timeline.map((entry) =>
385 entry.item.type === "assistant_message" && entry.item.streaming
386 ? {
387 ...entry,
388 item: done
389 ? { ...entry.item, text, streaming: false, status: "completed" as const }
390 : { ...entry.item, text },
391 }
392 : entry,
393 );
394 return AsyncResult.success<EnvironmentThreadState>({
395 ...EMPTY_ENVIRONMENT_THREAD_STATE,
396 data: Option.some({
397 ...base,
398 turnItems: items.map(({ item }) => item),
399 visibleTurnItems: items,
400 }),
401 });
402 };
403 const registry = AtomRegistry.make();
404 await using stack = new AsyncDisposableStack();
405 stack.defer(() => registry.dispose());
406 registry.set(state.threadState, thread("Hel"));
407 let renders = 0;
408 await using _screen = await renderUi(
409 <RegistryContext.Provider value={registry}>
410 <Profiler id="queue" onRender={() => (renders += 1)}>
411 <QueuedRunsControl {...baseProps} />
412 </Profiler>
413 </RegistryContext.Provider>,
414 );
415 await expect.element(page.getByText("Run the tests next", { exact: true })).toBeVisible();
416 const settled = renders;
417
418 await act(() => registry.set(state.threadState, thread("Hello")));
419 await act(() => registry.set(state.threadState, thread("Hello there")));
420 expect(renders).toBe(settled);
421
422 await act(() => registry.set(state.threadState, thread("Hello there", true)));
423 expect(renders).toBeGreaterThan(settled);
424});
425
426it("tells the user why Send now was rejected", async () => {
427 setup();
428 const reason = "Target run run:active is stopping and cannot be steered.";
429 state.workflow = {
430 activeRun: { id: "run:active" },
431 canPromoteToSteer: true,
432 queuedRuns: [
433 {
434 run: { id: "run:queued", userMessageId: "message:queued" },
435 text: "Follow up",
436 attachments: [],
437 },
438 ],
439 };
440 state.commandResult = AsyncResult.failure(
441 Cause.fail(
442 new OrchestrationV2DispatchCommandError({
443 commandId: CommandId.make("command:promote"),
444 commandType: "queued-message.promote-to-steer",
445 message: reason,
446 detail: reason,
447 }),
448 ),
449 );
450 await using _screen = await renderUi(
451 <ToastProvider timeout={0}>
452 <QueuedRunsControl {...baseProps} />
453 </ToastProvider>,
454 );
455
456 await page.getByRole("button", { name: "Send now" }).click();
457 await vi.waitFor(() => expect(page.getByText(reason).element()).toBeVisible());
458});
459
460it("keeps the send shortcut from the composer while Stop blocks the queued message", async () => {
461 setup();
462 state.workflow = {
463 activeRun: { id: "run:active" },
464 canPromoteToSteer: true,
465 queuedRuns: [
466 {
467 run: { id: "run:queued", userMessageId: "message:queued" },
468 text: "Follow up",
469 attachments: [],
470 stopBlocksPromotion: true,
471 },
472 ],
473 };
474 const ref = createRef<QueuedRunsControlHandle>();
475 await using _screen = await renderQueue({ ref });
476
477 await expect.element(page.getByText("Follow up", { exact: true })).toBeVisible();
478 expect(ref.current?.steerNext(false)).toBe(true);
479 expect(state.commandCalls).toBe(0);
480});
481
482it("shares the hover tooltip between Remove and Edit and keeps it when Edit is disabled", async () => {
483 setup();
484 const reason = "Answer the question to edit queued messages";
485 state.workflow = {
486 activeRun: { id: "run:active" },
487 canPromoteToSteer: true,
488 queuedRuns: [
489 {
490 run: { id: "run:queued", userMessageId: "message:queued" },
491 text: "Follow up",
492 attachments: [],
493 },
494 ],
495 };
496 await using screen = await renderUi(
497 <SharedTooltipProvider>
498 <QueuedRunsControl {...baseProps} editBlockedReason={reason} />
499 </SharedTooltipProvider>,
500 );
501 using _timers = fakeTimers();
502
503 const editButton = screen.getByRole("button", { name: "Edit queued message", exact: true });
504 const removeButton = screen.getByRole("button", { name: "Remove queued message", exact: true });
505 expect(editButton.element()).toBeDisabled();
506
507 await userEvent.hover(editButton.element().parentElement!);
508 await act(() => vi.advanceTimersByTime(600));
509 expect(page.getByText(reason).element()).toBeVisible();
510
511 await userEvent.hover(removeButton);
512 await act(() => vi.advanceTimersByTime(1));
513 expect(page.getByText("Remove from queue").element()).toBeVisible();
514 expect(page.getByText(reason).query()).toBeNull();
515
516 await screen.rerender(
517 <SharedTooltipProvider>
518 <QueuedRunsControl {...baseProps} />
519 </SharedTooltipProvider>,
520 );
521 await userEvent.hover(editButton);
522 await act(() => vi.advanceTimersByTime(1));
523 expect(page.getByText("Edit in the composer").element()).toBeVisible();
524 expect(page.getByText("Remove from queue").query()).toBeNull();
525});