File size: 1,120 Bytes
abcf568
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { createStudioTextPart } from '../../domain/factories'
import type {
  StudioAssistantMessage,
  StudioPartStore
} from '../../domain/types'
import { StudioPartSynchronizer } from './part-synchronizer'

export class StudioTextStreamAccumulator {
  constructor(
    private readonly partStore: StudioPartStore,
    private readonly sync: StudioPartSynchronizer
  ) {}

  async startPart(
    assistantMessage: StudioAssistantMessage,
    type: 'text' | 'reasoning'
  ): Promise<string> {
    const part = createStudioTextPart({
      messageId: assistantMessage.id,
      sessionId: assistantMessage.sessionId,
      type
    })
    const created = await this.sync.appendPart(assistantMessage, part)
    return created.id
  }

  async appendDelta(
    partId: string | null,
    text: string,
    expectedType: 'text' | 'reasoning'
  ): Promise<void> {
    if (!partId) {
      return
    }

    const current = await this.partStore.getById(partId)
    if (!current || current.type !== expectedType) {
      return
    }

    await this.sync.updatePart(partId, {
      text: `${current.text}${text}`
    })
  }
}