Repository navigation
feat(coderd/chatd): unify chat storage on SDK parts and fix file-reference rendering - #22958
Merged
Merged
Conversation
mafredri
force-pushed
the
mafredri/feat-unify-chat-storage
branch
2 times, most recently
from
March 12, 2026 16:52
f91f256 to
4ba3848
Compare
Switch ParseContent to return []codersdk.ChatMessagePart with role-aware parsing: - system: JSON string → single text part - assistant: try SDK parts first, fall back to fantasy envelope - tool: try SDK parts first, fall back to legacy tool result rows - user: structural heuristic (isLegacyUserContentFormat) to distinguish fantasy envelope from SDK parts Rewrite ConvertMessagesWithFiles to use ParseContent (SDK parts) and partsToMessageParts for LLM dispatch. Simplify db2sdk.chatMessageParts to delegate to ParseContent and strip internal-only fields (ProviderMetadata, inline file Data). Key additions: - ProviderMetadata and ProviderExecuted fields on ChatMessagePart - MarshalParts, marshalProviderMetadata, providerMetadataToOptions - partsToMessageParts for SDK→fantasy conversion at LLM dispatch - isLegacyUserContentFormat for format discrimination - PartFromContent now preserves ProviderMetadata and ProviderExecuted Removals: - extractFileIDs, patchFileContent, ToMessageParts (replaced by partsToMessageParts) - toToolResultPart method (replaced by toolResultPartToMessagePart) - parseSystemContent (inlined into parseSystemRole) - db2sdk: parseContentBlocks, contentBlockToPart, parseSystemContent, toolResultOutputToRawJSON, toolResultOutputIsError Refs #22821
Change createChatInputFromParts to return []codersdk.ChatMessagePart instead of ([]fantasy.Content, map[int]uuid.UUID). File-reference input parts are now preserved as structured ChatMessagePart with type file-reference instead of being flattened to fantasy.TextContent. This is the commit that fixes the file-reference rendering bug. Update CreateOptions, SendMessageOptions, EditMessageOptions to use []codersdk.ChatMessagePart. All three call MarshalParts instead of MarshalContent. Update subagent.go callers to build SDK parts directly. Refs #22821
Change persistStep to convert fantasy.Content to ChatMessagePart via PartFromContent before serializing with MarshalParts. The streaming accumulation layer (chatloop) is untouched, only the final serialization step changes. Change persistChatContextSummary to build ChatMessagePart directly and serialize via MarshalParts instead of using MarshalContent and MarshalToolResult. Remove MarshalToolResultContent, injectFileID, marshalContentBlock (no longer needed). MarshalContent is retained for test fixtures that create legacy-format DB rows. Refs #22821
…at detection Replace the try/fallback approach in parseAssistantRole with the same structural heuristic used for user messages. The try/fallback relied on json.Unmarshal failing when a JSON object hits a []byte field, which is a brittle invariant tied to Go's decoder behavior. If Data were ever changed to json.RawMessage, legacy assistant messages would silently parse with correct Type but empty Text. Rename isLegacyUserContentFormat to isFantasyEnvelopeFormat since it's now shared between user and assistant parsing paths. Add TestSDKPartsNeverProduceFantasyEnvelopeShape guard test that verifies no SDK part type serializes with a data field containing a JSON object, protecting the structural invariant. Refs #22821
Add tests covering the key risks of the storage unification: - ParseContent backward compatibility: 13 cases covering every legacy and new format variant (system string, fantasy envelope text/file/reasoning/tool-call for user and assistant roles, legacy tool result rows, new SDK parts for all roles) - ProviderMetadata round-trip: legacy fantasy DB row with Anthropic cache hints → ParseContent → SDK part → ConvertMessagesWithFiles → fantasy part with typed ProviderOptions. Verifies the highest-risk data path. - File-reference preservation: MarshalParts → ParseContent round-trip with all fields intact, plus LLM dispatch producing TextPart - Assistant write round-trip: PartFromContent → MarshalParts → DB → ParseContent → ConvertMessagesWithFiles with ProviderMetadata surviving the full cycle - Mixed-format conversation: realistic post-deploy scenario with system (string), old user (fantasy+file_id), old assistant (fantasy tool-call), old tool (result rows), new user (SDK+file-reference), new assistant (SDK+metadata) in a single ConvertMessagesWithFiles call Refs #22821
…-trip test Remove 'Internal only' from ProviderExecuted comment since the streaming path already exposes it to frontends via ChatStreamMessagePart. The field indicates whether the LLM provider executed a tool call (e.g. Anthropic computer use), which is useful for UI rendering. Add TestQueuedMessageRoundTrip covering the queue → promote cycle: MarshalParts → db2sdk.ChatQueuedMessage (display while queued) → ParseContent (after promote) → ConvertMessagesWithFiles (LLM dispatch). Verifies file-reference parts survive all three stages. Refs #22821
Add typescript:"-" tag to ChatMessagePart.ProviderMetadata. This field is always stripped to nil by db2sdk before API responses, so it should not appear in the generated TypeScript types. The json tag is retained for internal DB serialization via MarshalParts.
TestChatMessageWithFileReferences subtests previously expected file-reference input to be stored as ChatMessagePartTypeText with formatted text. Now that the write path preserves file-reference parts as structured ChatMessagePartTypeFileReference, update all subtests to check for the correct part type and structured fields (FileName, StartLine, EndLine, Content). This is the observable behavior change from the storage unification: the API now returns typed file-reference parts that the frontend can render as styled chips, instead of plain text. Refs #22821
…ructors ProviderMetadata was leaking to clients via SSE message_part events. PartFromContent populates it for DB persistence fidelity, but publishMessagePart passed parts to clients with no stripping. Add StripInternal() to ChatMessagePart, centralizing the "which fields are internal" decision. Use it in both db2sdk.chatMessageParts (REST) and publishMessagePart (SSE) to ensure consistent stripping. Add missing constructors ChatMessageFile, ChatMessageFileReference, and ChatMessageSource, completing the set for all 7 part types. Update createChatInputFromParts call sites and 10 enterprise test sites to use constructors instead of inline struct literals.
mafredri
force-pushed
the
mafredri/feat-unify-chat-storage
branch
from
March 13, 2026 11:05
4ba3848 to
d92161f
Compare
Add missing backward-compat tests for ParseContent: - user/plain_string: bare JSON string format (very old) - assistant/fantasy_source: legacy SourceContent envelope Remove dead tc := tc loop variable shadow (Go 1.22+). Document in StripInternal why ArgsDelta and ResultDelta are intentionally preserved (consumed by frontend via SSE).
mafredri
force-pushed
the
mafredri/feat-unify-chat-storage
branch
2 times, most recently
from
March 13, 2026 13:40
197cd81 to
4929d83
Compare
Add ChatMessageRole type and constants (System, User, Assistant, Tool) to codersdk, replacing magic strings and fantasy.MessageRole casts at the persistence/parsing boundary. ParseContent now takes ChatMessageRole instead of string. Call sites in chatd, quickgen, subagent, and db2sdk cast the DB string at the boundary. This removes the fantasy import from db2sdk entirely. Also fixes MarshalToolResult doc comment (test-only, not production) and adds TestParseContent_ErrorPaths covering null content, unknown role, and malformed JSON for all four roles.
mafredri
force-pushed
the
mafredri/feat-unify-chat-storage
branch
from
March 13, 2026 13:44
4929d83 to
516309f
Compare
…hat-storage # Conflicts: # coderd/chatd/chatd_test.go # coderd/chats_test.go
mafredri
marked this pull request as ready for review
March 13, 2026 14:10
kylecarbs
approved these changes
Mar 13, 2026
kylecarbs
left a comment
Member
There was a problem hiding this comment.
LGTM. Lovely you did backwards compatibility. Hopefully we can remove that in a week or two ish!
Comment on lines
+97
to
+102
| // WARNING: This type is both an API wire type and a database | ||
| // persistence format. Its JSON layout is stored in the | ||
| // chat_messages.content column. Field additions, renames, type | ||
| // changes, and omitempty behavior all affect backward-compatible | ||
| // deserialization of stored rows. Treat changes to this struct | ||
| // with the same care as a database migration. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
File-reference parts in user messages were flattened to
TextContentat write time because fantasy has no file-reference content type. The frontend never saw them as structured parts.This moves all write paths (user, assistant, tool) from fantasy envelope format to
codersdk.ChatMessagePart. The streaming layer (chatloop) is untouched, the conversion happens at the serialization boundary inpersistStep.Old rows are still readable.
ParseContentuses a structural heuristic (isFantasyEnvelopeFormat) to distinguish legacy envelopes from SDK parts. We chose this over try/fallback because fantasy envelopes partially unmarshal intoChatMessagePart(thetypefield matches) while silently losing content. A guard test enforces that no SDK part can produce the envelope shape.This is forward-only: new rows are unreadable by old code. Chat is behind a feature flag so rollback risk is contained.
Also adds a typed
ChatMessageRoleto replace raw strings andfantasy.MessageRole*casts at the persistence boundary. The type coversChatMessage.Role,ChatStreamMessagePart.Role, thePublishMessagePartcallback chain, and all DB write sites.fantasy.MessageRole*remains only where we buildfantasy.Messagestructs for LLM dispatch.Separately,
ProviderMetadatawas leaking to SSE clients viapublishMessagePart.StripInternalnow runs on both the SSE and REST paths, covering this.Other cleanup:
db2sdk.contentBlockToPartsilently dropped metadata on text/reasoning/tool-call content. New code preserves it.providerMetadataToOptionsnow logs warnings instead of silently returning nil.db2sdkshrinks from ~250 lines of parallel conversion to ~15 lines delegating tochatprompt.ParseContent(), removing thefantasyimport entirely.Follow-up:
content_versioncolumn to replace the structural heuristic, and a Postgres enum forchat_messages.roleto eliminatestring()casts at the DB boundary. Both touch the same table and could ship together.Refs #22821