Open History to see the last commit
1import { describe, expect, it } from "vite-plus/test";
2import type { OrchestrationV2ThreadProjection } from "@t3tools/contracts";
3
4import {
5 canForkProjectedAssistantItem,
6 deriveThreadQueueWorkflowState,
7 describeSideChatVisibility,
8 resolveLatestMergeBackRun,
9 resolveSideChatHistoryAvailability,
10 threadSupportsProviderHandoff,
11} from "./threadWorkflows.ts";
12
13const capabilities = (input?: {
14 readonly queued?: boolean;
15 readonly steer?: boolean;
16 readonly restartSteer?: boolean;
17 readonly nativeFork?: boolean;
18 readonly portableFork?: boolean;
19}) =>
20 ({
21 turns: {
22 supportsQueuedMessages: input?.queued ?? false,
23 supportsActiveSteering: input?.steer ?? false,
24 supportsSteeringByInterruptRestart: input?.restartSteer ?? false,
25 },
26 threads: {
27 canForkThread: input?.nativeFork ?? false,
28 canForkFromTurn: input?.nativeFork ?? false,
29 },
30 identity: { nativeThreadIds: input?.nativeFork ? "strong" : "none" },
31 context: { supportsFullThreadHandoff: input?.portableFork ?? false },
32 }) as never;
33
34describe("thread workflows", () => {
35 it("allows a completed thread to switch providers after its session detaches", () => {
36 const projection = {
37 thread: {
38 id: "thread",
39 activeProviderThreadId: "provider-thread",
40 modelSelection: { instanceId: "cursor", model: "grok-4.7" },
41 },
42 runs: [{ id: "run", status: "completed" }],
43 providerSessions: [],
44 providerThreads: [
45 {
46 id: "provider-thread",
47 appThreadId: "thread",
48 providerInstanceId: "cursor",
49 providerSessionId: "detached-session",
50 nativeThreadRef: { driver: "cursor", nativeId: "agent-123", strength: "strong" },
51 },
52 ],
53 } as unknown as OrchestrationV2ThreadProjection;
54
55 expect(threadSupportsProviderHandoff(projection)).toBe(true);
56 expect(
57 threadSupportsProviderHandoff({
58 ...projection,
59 runs: [{ ...projection.runs[0]!, status: "running" }],
60 }),
61 ).toBe(false);
62 expect(
63 threadSupportsProviderHandoff({
64 ...projection,
65 providerThreads: [{ ...projection.providerThreads[0]!, nativeThreadRef: null }],
66 }),
67 ).toBe(false);
68 });
69
70 it("sorts queued messages and gates promotion from capabilities", () => {
71 const state = deriveThreadQueueWorkflowState({
72 thread: { id: "thread", activeProviderThreadId: "provider-thread" },
73 runs: [
74 {
75 id: "active",
76 status: "running",
77 providerThreadId: "provider-thread",
78 activeAttemptId: "attempt-active",
79 ordinal: 1,
80 },
81 { id: "later", status: "queued", userMessageId: "message-later", ordinal: 3 },
82 {
83 id: "first",
84 status: "queued",
85 userMessageId: "message-first",
86 ordinal: 2,
87 queuePosition: 1,
88 },
89 ],
90 messages: [
91 {
92 id: "message-first",
93 text: "First",
94 attachments: [
95 {
96 type: "image",
97 id: "attachment-first",
98 name: "first.png",
99 mimeType: "image/png",
100 sizeBytes: 64,
101 },
102 ],
103 },
104 { id: "message-later", text: "Later" },
105 ],
106 providerTurns: [
107 {
108 id: "provider-turn-active",
109 runAttemptId: "attempt-active",
110 status: "running",
111 },
112 ],
113 providerThreads: [
114 {
115 id: "provider-thread",
116 appThreadId: "thread",
117 providerSessionId: "provider-session",
118 },
119 ],
120 providerSessions: [
121 {
122 id: "provider-session",
123 status: "running",
124 capabilities: capabilities({ queued: true, restartSteer: true }),
125 },
126 ],
127 } as never);
128
129 expect(state.queuedRuns.map(({ run, text }) => [run.id, text])).toEqual([
130 ["first", "First"],
131 ["later", "Later"],
132 ]);
133 expect(state.queuedRuns.map(({ attachments }) => attachments.map(({ id }) => id))).toEqual([
134 ["attachment-first"],
135 [],
136 ]);
137 expect(state.activeRun?.id).toBe("active");
138 expect(state.canPromoteToSteer).toBe(true);
139 expect(state.canSendNow).toBe(false);
140 });
141
142 it.each(["completed", "interrupted", "cancelled", "failed"])(
143 "allows sending a held message after a %s turn without a live session",
144 (status) => {
145 const state = deriveThreadQueueWorkflowState({
146 thread: { id: "thread", activeProviderThreadId: null },
147 runs: [
148 { id: "previous", status, ordinal: 1 },
149 { id: "queued", status: "queued", userMessageId: "message", ordinal: 2, queueHeld: true },
150 ],
151 messages: [{ id: "message", text: "Send this" }],
152 providerThreads: [],
153 providerTurns: [],
154 providerSessions: [],
155 } as never);
156
157 expect(state.canSendNow).toBe(true);
158 expect(state.canPromoteToSteer).toBe(false);
159 expect(state.isHeld).toBe(true);
160 },
161 );
162
163 it.each(["preparing", "starting", "running", "waiting"])(
164 "does not offer send now while a turn is %s",
165 (status) => {
166 const state = deriveThreadQueueWorkflowState({
167 thread: { id: "thread", activeProviderThreadId: null },
168 runs: [{ id: "active", status, ordinal: 1 }],
169 messages: [],
170 providerThreads: [],
171 providerTurns: [],
172 providerSessions: [],
173 } as never);
174
175 expect(state.canSendNow).toBe(false);
176 },
177 );
178
179 it("offers to skip a running compaction even when the provider cannot steer", () => {
180 const state = deriveThreadQueueWorkflowState({
181 thread: { id: "thread", activeProviderThreadId: null },
182 runs: [
183 { id: "compact", status: "running", userMessageId: "message-compact", ordinal: 1 },
184 { id: "queued", status: "queued", userMessageId: "message-queued", ordinal: 2 },
185 ],
186 messages: [
187 { id: "message-compact", role: "user", text: "/compact", attachments: [] },
188 { id: "message-queued", role: "user", text: "Next", attachments: [] },
189 ],
190 providerThreads: [],
191 providerTurns: [],
192 providerSessions: [],
193 } as never);
194
195 expect(state.canPromoteToSteer).toBe(true);
196 expect(state.promoteSkipsCompaction).toBe(true);
197 });
198
199 it("keeps held messages visible and clears the hold when they leave the queue", () => {
200 for (const status of ["queued", "cancelled", "starting"] as const) {
201 const state = deriveThreadQueueWorkflowState({
202 thread: { id: "thread", activeProviderThreadId: null },
203 runs: [{ id: "held", status, userMessageId: "message", ordinal: 1, queueHeld: true }],
204 messages: [{ id: "message", text: "Saved message" }],
205 providerThreads: [],
206 providerTurns: [],
207 providerSessions: [],
208 } as never);
209 expect(state.isHeld).toBe(status === "queued");
210 expect(state.queuedRuns.map(({ text }) => text)).toEqual(
211 status === "queued" ? ["Saved message"] : [],
212 );
213 }
214 });
215
216 it("hides automatic completion delivery from the visible queue", () => {
217 const state = deriveThreadQueueWorkflowState({
218 thread: { id: "thread", activeProviderThreadId: null },
219 runs: [
220 {
221 id: "provider-wake",
222 status: "queued",
223 userMessageId: "provider-wake",
224 ordinal: 4,
225 queuePosition: 3,
226 },
227 {
228 id: "automatic",
229 status: "queued",
230 userMessageId: "message-automatic",
231 ordinal: 2,
232 queuePosition: 1,
233 },
234 {
235 id: "visible",
236 status: "queued",
237 userMessageId: "message-visible",
238 ordinal: 3,
239 queuePosition: 2,
240 },
241 ],
242 messages: [
243 {
244 id: "provider-wake",
245 text: "Model-facing text",
246 notification: {
247 source: { kind: "monitor" },
248 outcome: "updated",
249 summary: "Monitor updated",
250 },
251 },
252 {
253 id: "message-automatic",
254 text: "A delegated task reached a terminal state.",
255 delegatedCompletion: {
256 generation: 1,
257 parentRunId: "run:parent",
258 taskIds: ["task:child"],
259 },
260 },
261 { id: "message-visible", text: "Visible queued message" },
262 ],
263 providerTurns: [],
264 providerThreads: [],
265 providerSessions: [],
266 } as never);
267
268 expect(state.queuedRuns.map(({ run, text }) => [run.id, text])).toEqual([
269 ["visible", "Visible queued message"],
270 ]);
271 });
272
273 it("removes only the promoted head from the visible queue", () => {
274 const state = deriveThreadQueueWorkflowState({
275 thread: { id: "thread", activeProviderThreadId: "provider-thread" },
276 runs: [
277 {
278 id: "promoted",
279 status: "starting",
280 userMessageId: "message-promoted",
281 providerThreadId: "provider-thread",
282 ordinal: 2,
283 queuePosition: null,
284 },
285 {
286 id: "still-queued",
287 status: "queued",
288 userMessageId: "message-still-queued",
289 providerThreadId: "provider-thread",
290 ordinal: 3,
291 queuePosition: 2,
292 },
293 ],
294 messages: [
295 { id: "message-promoted", text: "Run now" },
296 { id: "message-still-queued", text: "Wait longer" },
297 ],
298 providerTurns: [],
299 providerThreads: [],
300 providerSessions: [],
301 } as never);
302
303 expect(state.activeRun?.id).toBe("promoted");
304 expect(state.queuedRuns.map(({ run, text }) => [run.id, text])).toEqual([
305 ["still-queued", "Wait longer"],
306 ]);
307 });
308
309 it.each(["preparing", "starting", "waiting"] as const)(
310 "does not promote queued work into a %s run",
311 (status) => {
312 const state = deriveThreadQueueWorkflowState({
313 thread: { id: "thread", activeProviderThreadId: "provider-thread" },
314 runs: [
315 {
316 id: "active",
317 status,
318 providerThreadId: "provider-thread",
319 activeAttemptId: "attempt-active",
320 ordinal: 1,
321 },
322 { id: "queued", status: "queued", userMessageId: "message", ordinal: 2 },
323 ],
324 messages: [{ id: "message", text: "Queued" }],
325 providerTurns: [
326 {
327 id: "provider-turn-active",
328 runAttemptId: "attempt-active",
329 status: status === "waiting" ? "completed" : "starting",
330 },
331 ],
332 providerThreads: [
333 {
334 id: "provider-thread",
335 appThreadId: "thread",
336 providerSessionId: "provider-session",
337 },
338 ],
339 providerSessions: [
340 {
341 id: "provider-session",
342 status: "running",
343 capabilities: capabilities({ queued: true, steer: true }),
344 },
345 ],
346 } as never);
347
348 expect(state.canPromoteToSteer).toBe(false);
349 },
350 );
351
352 it("allows native, portable, and capability-unknown exact-run forks", () => {
353 const projectedItem = {
354 item: { type: "assistant_message", runId: "run", status: "completed" },
355 } as never;
356
357 expect(
358 canForkProjectedAssistantItem({
359 projectedItem,
360 capabilities: capabilities({ nativeFork: true }),
361 }),
362 ).toBe(true);
363 expect(
364 canForkProjectedAssistantItem({
365 projectedItem,
366 capabilities: capabilities({ portableFork: true }),
367 }),
368 ).toBe(true);
369 expect(canForkProjectedAssistantItem({ projectedItem })).toBe(true);
370 expect(
371 canForkProjectedAssistantItem({
372 projectedItem: {
373 item: { type: "assistant_message", runId: "run", status: "running" },
374 } as never,
375 }),
376 ).toBe(false);
377 });
378
379 it("merges the newest provider-finished run while checkpoint capture is pending", () => {
380 const projection = {
381 runs: [
382 { id: "newest-queued", status: "queued", ordinal: 3 },
383 { id: "older-completed", status: "completed", ordinal: 1 },
384 { id: "newest-finished", status: "waiting", ordinal: 2 },
385 ],
386 } as never;
387
388 expect(resolveLatestMergeBackRun(projection)?.id).toBe("newest-finished");
389 });
390
391 it.each(["preparing", "starting", "running"] as const)(
392 "does not merge older history while a newer run is %s",
393 (status) => {
394 const projection = {
395 runs: [
396 { id: "older-completed", status: "completed", ordinal: 1 },
397 { id: "newer-active", status, ordinal: 2 },
398 ],
399 } as never;
400
401 expect(resolveLatestMergeBackRun(projection)).toBeNull();
402 },
403 );
404});
405
406describe("side chat history", () => {
407 const sessionProjection = (
408 runs: ReadonlyArray<Record<string, unknown>>,
409 sessionCapabilities?: ReturnType<typeof capabilities>,
410 ) =>
411 ({
412 thread: { id: "thread", activeProviderThreadId: "provider-thread" },
413 runs,
414 providerThreads: [
415 { id: "provider-thread", appThreadId: "thread", providerSessionId: "session" },
416 ],
417 providerSessions: [
418 {
419 id: "session",
420 status: "ready",
421 ...(sessionCapabilities === undefined ? {} : { capabilities: sessionCapabilities }),
422 },
423 ],
424 }) as unknown as OrchestrationV2ThreadProjection;
425
426 it("forks at the latest completed checkpointed run, ignoring one still streaming", () => {
427 const result = resolveSideChatHistoryAvailability(
428 sessionProjection(
429 [
430 { id: "r1", ordinal: 1, status: "completed", checkpointId: "c1" },
431 { id: "r2", ordinal: 2, status: "completed", checkpointId: "c2" },
432 { id: "r3", ordinal: 3, status: "running", checkpointId: null },
433 ],
434 capabilities({ nativeFork: true }),
435 ),
436 );
437 expect(result).toEqual({ available: true, upToRunOrdinal: 2 });
438 });
439
440 it("explains why history is unavailable", () => {
441 expect(
442 resolveSideChatHistoryAvailability(
443 sessionProjection([{ id: "r1", ordinal: 1, status: "running", checkpointId: null }]),
444 ),
445 ).toMatchObject({ available: false, reason: expect.stringContaining("Nothing to share") });
446 expect(
447 resolveSideChatHistoryAvailability(
448 sessionProjection(
449 [{ id: "r1", ordinal: 1, status: "completed", checkpointId: "c1" }],
450 capabilities(),
451 ),
452 ),
453 ).toMatchObject({ available: false, reason: expect.stringContaining("provider") });
454 expect(
455 resolveSideChatHistoryAvailability(
456 sessionProjection(
457 [{ id: "r1", ordinal: 1, status: "completed", checkpointId: "c1" }],
458 capabilities({ portableFork: true }),
459 ),
460 ),
461 ).toEqual({ available: true, upToRunOrdinal: 1 });
462 });
463
464 it("names what a side chat can see", () => {
465 const parentRuns = [{ id: "r4", ordinal: 4 }] as never;
466 expect(
467 describeSideChatVisibility({
468 forkedFrom: { type: "run", threadId: "thread", runId: "r4" } as never,
469 parentRuns,
470 }),
471 ).toBe("Sees up to run 4");
472 expect(describeSideChatVisibility({ forkedFrom: null, parentRuns })).toBe("Sees no history");
473 });
474});