1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
import type { ChatMessage, Chunk, TurnProviderRetryEvent } from "@dispatch/wire";
import type { RenderedChunk, TranscriptState } from "./types";
/**
* Select all chunks for rendering: committed first (seq order),
* then provisional (seq: null).
*/
export function selectChunks(state: TranscriptState): readonly RenderedChunk[] {
const result: RenderedChunk[] = [];
for (const c of state.committed) {
result.push(
c.turnId !== undefined
? { seq: c.seq, role: c.role, chunk: c.chunk, provisional: false, turnId: c.turnId }
: { seq: c.seq, role: c.role, chunk: c.chunk, provisional: false },
);
}
for (const p of state.provisional) {
result.push(
p.turnId !== undefined
? { seq: null, role: p.role, chunk: p.chunk, provisional: true, turnId: p.turnId }
: { seq: null, role: p.role, chunk: p.chunk, provisional: true },
);
}
const acc = state.accumulating;
if (acc !== null) {
const chunk: Chunk =
acc.kind === "text" ? { type: "text", text: acc.text } : { type: "thinking", text: acc.text };
result.push({
seq: null,
role: "assistant",
chunk,
provisional: true,
streaming: true,
...(acc.turnId !== undefined ? { turnId: acc.turnId } : {}),
});
}
return result;
}
/**
* Whether a turn is currently generating (for a "generating…" indicator). True
* for ANY client watching the conversation — the sender, a second device, or a
* reconnected client whose in-flight turn was replayed.
*/
export function selectGenerating(state: TranscriptState): boolean {
return state.generating;
}
/**
* The latest `provider-retry` event for the current turn, or `null` when no retry
* is pending. Drives the transient yellow "retrying…" warning banner (rendered
* by ChatView). Never persisted — see `TranscriptState.providerRetry`.
*/
export function selectProviderRetry(state: TranscriptState): TurnProviderRetryEvent | null {
return state.providerRetry;
}
/**
* Group consecutive same-role rendered chunks into ChatMessages.
*/
export function selectMessages(state: TranscriptState): readonly ChatMessage[] {
const rendered = selectChunks(state);
const first = rendered[0];
if (first === undefined) return [];
const messages: ChatMessage[] = [];
let role = first.role;
let chunks: Chunk[] = [first.chunk];
for (let i = 1; i < rendered.length; i++) {
const rc = rendered[i];
if (rc === undefined) continue;
if (rc.role === role) {
chunks.push(rc.chunk);
} else {
messages.push({ role, chunks });
role = rc.role;
chunks = [rc.chunk];
}
}
messages.push({ role, chunks });
return messages;
}
|