File size: 5,547 Bytes
d47b053
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
import { createStudioWorkResult } from '../domain/factories'
import type {
  StudioFileAttachment,
  StudioTask,
  StudioWork,
  StudioWorkResult,
  StudioWorkResultStore,
  StudioWorkStore
} from '../domain/types'
import type { JobResult } from '../../types'
import { resolveJobResultCode, resolveJobResultCodeLanguage } from '../domain/render-result-metadata'
import type { StudioBlobStore } from '../storage/studio-blob-store'

export interface StudioRenderWorkSyncStores {
  workStore: StudioWorkStore
  workResultStore: StudioWorkResultStore
  blobStore?: StudioBlobStore
}

export async function syncRenderWorkFromTask(
  stores: StudioRenderWorkSyncStores,
  task: StudioTask
): Promise<{ work: StudioWork; result?: StudioWorkResult } | null> {
  if (!task.workId) {
    return null
  }

  const work = await stores.workStore.getById(task.workId)
  if (!work) {
    return null
  }

  const nextStatus = toWorkStatus(task.status)
  const nextMetadata = {
    ...(work.metadata ?? {}),
    ...(task.metadata ?? {})
  }

  const renderResult = getRenderResult(task)
  if (!renderResult) {
    const updatedWork = await stores.workStore.update(work.id, {
      latestTaskId: task.id,
      status: nextStatus,
      metadata: nextMetadata
    })
    return updatedWork ? { work: updatedWork } : { work }
  }

  const nextWorkResult = await buildRenderWorkResult(work.id, task, renderResult, stores.blobStore)
  const persistedResult = work.currentResultId
    ? await stores.workResultStore.update(work.currentResultId, nextWorkResult)
    : await stores.workResultStore.create(createStudioWorkResult(nextWorkResult))

  const updatedWork = await stores.workStore.update(work.id, {
    latestTaskId: task.id,
    currentResultId: persistedResult?.id ?? work.currentResultId,
    status: nextStatus,
    metadata: nextMetadata
  })

  return {
    work: updatedWork ?? work,
    result: persistedResult ?? undefined
  }
}

function getRenderResult(task: StudioTask): JobResult | null {
  const candidate = task.metadata?.result
  if (!candidate || typeof candidate !== 'object') {
    return null
  }

  const status = (candidate as { status?: unknown }).status
  if (status !== 'completed' && status !== 'failed') {
    return null
  }

  return candidate as JobResult
}

async function buildRenderWorkResult(
  workId: string,
  task: StudioTask,
  result: JobResult,
  blobStore?: StudioBlobStore
): Promise<Omit<StudioWorkResult, 'id' | 'createdAt'>> {
  if (result.status === 'completed') {
    const outputMode = result.data.outputMode
    const attachments = await buildCompletedAttachments(result, blobStore)
    const summary = outputMode === 'video'
      ? `Render completed${result.data.videoUrl ? `: ${result.data.videoUrl}` : ''}`
      : `Render completed with ${result.data.imageCount ?? result.data.imageUrls?.length ?? 0} image output(s)`

    return {
      workId,
      kind: 'render-output',
      summary,
      attachments,
      metadata: {
        taskId: task.id,
        jobId: task.metadata?.jobId,
        outputMode,
        quality: result.data.quality,
        generationType: result.data.generationType,
        usedAI: result.data.usedAI,
        renderPeakMemoryMB: result.data.renderPeakMemoryMB,
        timings: result.data.timings,
        code: resolveJobResultCode(result),
        codeLanguage: resolveJobResultCodeLanguage(result),
        imageCount: result.data.imageCount,
        workspaceVideoPath: result.data.workspaceVideoPath,
        workspaceImagePaths: result.data.workspaceImagePaths
      }
    }
  }

  return {
    workId,
    kind: 'failure-report',
    summary: result.data.error,
    metadata: {
      taskId: task.id,
      jobId: task.metadata?.jobId,
      outputMode: result.data.outputMode,
      error: result.data.error,
      details: result.data.details,
      cancelReason: result.data.cancelReason,
      stage: task.metadata?.stage,
      bullStatus: task.metadata?.bullStatus
    }
  }
}

async function buildCompletedAttachments(
  result: Extract<JobResult, { status: 'completed' }>,
  blobStore?: StudioBlobStore
): Promise<StudioFileAttachment[] | undefined> {
  const attachments: StudioFileAttachment[] = []

  if (result.data.videoUrl) {
    attachments.push(await resolveAttachment({
      blobStore,
      path: result.data.videoUrl,
      name: fileNameFromPath(result.data.videoUrl),
      mimeType: 'video/mp4'
    }))
  }

  for (const imageUrl of result.data.imageUrls ?? []) {
    attachments.push(await resolveAttachment({
      blobStore,
      path: imageUrl,
      name: fileNameFromPath(imageUrl),
      mimeType: 'image/png'
    }))
  }

  return attachments.length > 0 ? attachments : undefined
}

async function resolveAttachment(input: {
  blobStore?: StudioBlobStore
  path: string
  name?: string
  mimeType?: string
}): Promise<StudioFileAttachment> {
  if (!input.blobStore) {
    return {
      kind: 'file',
      path: input.path,
      name: input.name,
      mimeType: input.mimeType,
    }
  }

  return input.blobStore.resolveAttachment({
    path: input.path,
    name: input.name,
    mimeType: input.mimeType,
  })
}

function toWorkStatus(taskStatus: StudioTask['status']): StudioWork['status'] {
  switch (taskStatus) {
    case 'completed':
      return 'completed'
    case 'failed':
      return 'failed'
    case 'cancelled':
      return 'cancelled'
    default:
      return 'running'
  }
}

function fileNameFromPath(path: string): string {
  const parts = path.split(/[\\/]/)
  return parts[parts.length - 1] || path
}