| 14 | ) |
| 15 | |
| 16 | func buildAssistantPartsForPersist( |
| 17 | ctx context.Context, |
| 18 | logger slog.Logger, |
| 19 | assistantBlocks []fantasy.Content, |
| 20 | toolResults []fantasy.ToolResultContent, |
| 21 | step chatloop.PersistedStep, |
| 22 | toolNameToConfigID map[string]uuid.UUID, |
| 23 | ) []codersdk.ChatMessagePart { |
| 24 | parts := make([]codersdk.ChatMessagePart, 0, len(assistantBlocks)+len(toolResults)) |
| 25 | // reasoningIdx walks reasoning blocks in occurrence order so we |
| 26 | // can apply the matching ReasoningStartedAt/ReasoningCompletedAt |
| 27 | // entry from step onto each reasoning part's CreatedAt and |
| 28 | // CompletedAt. |
| 29 | reasoningIdx := 0 |
| 30 | for _, block := range assistantBlocks { |
| 31 | part := chatprompt.PartFromContentWithLogger(ctx, logger, block) |
| 32 | if part.ToolName != "" { |
| 33 | if configID, ok := toolNameToConfigID[part.ToolName]; ok { |
| 34 | part.MCPServerConfigID = uuid.NullUUID{UUID: configID, Valid: true} |
| 35 | } |
| 36 | } |
| 37 | if part.Type == codersdk.ChatMessagePartTypeToolCall && part.ToolCallID != "" && step.ToolCallCreatedAt != nil { |
| 38 | if ts, ok := step.ToolCallCreatedAt[part.ToolCallID]; ok { |
| 39 | part.CreatedAt = &ts |
| 40 | } |
| 41 | } |
| 42 | if part.Type == codersdk.ChatMessagePartTypeToolResult && part.ToolCallID != "" && step.ToolResultCreatedAt != nil { |
| 43 | if ts, ok := step.ToolResultCreatedAt[part.ToolCallID]; ok { |
| 44 | part.CreatedAt = &ts |
| 45 | } |
| 46 | } |
| 47 | if part.Type == codersdk.ChatMessagePartTypeReasoning { |
| 48 | if reasoningIdx < len(step.ReasoningStartedAt) { |
| 49 | if ts := step.ReasoningStartedAt[reasoningIdx]; !ts.IsZero() { |
| 50 | part.CreatedAt = &ts |
| 51 | } |
| 52 | } |
| 53 | if reasoningIdx < len(step.ReasoningCompletedAt) { |
| 54 | if ts := step.ReasoningCompletedAt[reasoningIdx]; !ts.IsZero() { |
| 55 | part.CompletedAt = &ts |
| 56 | } |
| 57 | } |
| 58 | reasoningIdx++ |
| 59 | } |
| 60 | parts = append(parts, part) |
| 61 | } |
| 62 | for _, tr := range toolResults { |
| 63 | attachments, err := chattool.AttachmentsFromMetadata(tr.ClientMetadata) |
| 64 | if err != nil { |
| 65 | logger.Warn(ctx, "skipping malformed tool attachment metadata", |
| 66 | slog.F("tool_name", tr.ToolName), |
| 67 | slog.F("tool_call_id", tr.ToolCallID), |
| 68 | slog.Error(err), |
| 69 | ) |
| 70 | continue |
| 71 | } |
| 72 | for _, attachment := range attachments { |
| 73 | parts = append(parts, codersdk.ChatMessageFile( |