Repository navigation
Store AI chat messages as ai-chat-message child nodes with real edges (closes #3448) - #3491
Conversation
Pragmatic Code Review: PR #3491Review Type: Initial Review The type, schema, behaviour, wire type, generated TypeScript and docs are consistent with each other, the old What I ran: Requirements Check
Code Review Findings🔴 Critical1. After a cancelled turn, the next send answers the cancelled message and never answers the new one 📁 The viewer creates the message and then sets the status, but the two writes do not reach the daemon in that order: appendUserMessage(nodeId, trimmed, VIEWER_ID); // setNode, viewer source, new node
sharedNodeStore.updateNode(nodeId, { properties: { turn_status: 'processing' } }, ...);// shared-node-store.svelte.ts:3062
mode: source.type === 'viewer' && isNewNode ? 'debounce' : 'immediate',
The daemon's two-sided trigger covers that when the last stored message is the assistant's. It does not when the last stored message is already the user's:
Stop-then-rephrase is an ordinary flow. Before this PR the message and the status were one update, so this could not happen. The existing test Same root cause, second symptom: if the message create fails (the store only raises a write-failure notification), the status write has already gone out. The chat sits in Recommendation:
Principle: a request made of two non-atomic writes needs a defined order or an explicit link between them; otherwise the reader acts on a half-made request. 🟡 Important2. A turn's edges to a chat or a message are refused, so an agent delete of a chat can never be confirmed 📁
tracing::debug!(message_id, relationship, target_id, %error,
"an ai-chat-message edge was not recorded");Consequences when the target is an
I confirmed this by reading the code path and from that existing test; I did not write a failing test for the delete loop. Recommendation:
Principle: a confirmation that cannot be answered is worse than a refusal; fail at the point the invariant is known. 3. A message and its edges are separate transactions, and a lost 📁
Recommendation:
Principle: evidence a later step relies on should commit atomically with the thing it describes, and its loss should be visible. 4. The held-delete subtree check no longer checks anything on the chat path, and the comments still say it does 📁
Ok(Some(now)) if now.descendant_count != target.descendant_count => { /* "changed after you were asked" */ }
Recommendation: either store Principle: a destructive action should remove only what the user confirmed; comments must not claim a check the code no longer makes. 🟢 Suggestions5. 📁 A participation flag ("left out of lists") is used to mean "never a page of its own". A future core type that is excluded from default queries but is a root would never hydrate, and its tab would be closed by 6. 📁 It runs on every native-chat and message event, three or more times per turn, plus 7. Mention sync on create covers two of the create paths 📁
Nitpicks
RecommendationREQUEST CHANGES Finding 1 must be fixed before merge. Findings 2 to 4 are small and same-shaped, so they are worth folding into this PR. The rest is optional. |
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review: REQUEST CHANGES (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.
Review addressed (
|
Pragmatic Code Review: PR #3491 (re-review of
|
| # | Previous finding | Status | What I verified |
|---|---|---|---|
| 1 | 🔴 Send order: the status write reached the daemon before the message | ✅ Addressed | The viewer awaits flushNodeSaves([messageId]) before the status write and skips the status write on failure. The daemon triggers on the chat's status write only. a_send_after_a_cancelled_turn_answers_the_new_message and the backend-call-order test cover it. |
| 2 | 🟡 Edges to a chat or message refused; a chat delete could never be confirmed | ✅ Addressed | write_relationship_in_tx allows the target when the source is itself a chat or message. a_yes_to_deleting_a_chat_deletes_it, a_held_delete_of_a_chat_is_recorded. Scope note in new finding A. |
| 3 | 🟡 Message and edges not atomic; lost edge logged at debug | ✅ Addressed | create_node_with_relationships is one transaction; a missing target is skipped by index; any other failure rolls back. The fallback logs at warn. Note in new finding C. |
| 4 | 🟡 Held-delete subtree check was vacuous | ✅ Addressed | descendant_count is a declared, required edge field on pending_delete, on the wire type and in the generated TS; load_messages reads it from the edge. a_yes_does_not_delete_a_node_that_gained_children_since_the_question. |
| 5 | 🟢 isOwnedByParentViewer keyed on one flag |
✅ Addressed | Now requires the list flag and !canBeRoot. |
| 6 | 🟢 last_message_role loads every child |
⏭ Skipped, accepted | It now runs once per chat status write, not per message event. Fine to leave. |
| 7 | 🟢 Mention sync wording | ✅ Addressed | Doc comment and docs now say single-node creates. |
| Nits | sheet wording, schema.rs comment, sleep-based test |
✅ Addressed | The remaining watcher test asserts that nothing happens, so load cannot fail it. |
Requirements Check
Unchanged from the initial review: all eleven acceptance criteria are met. One criterion's wording has moved: the issue says the descendant count is "computed when shown", and it is now stored on the edge. ADR-088 §3 and the ai-chat-message sheet record that, and it is the stronger guarantee.
Checks on the areas you asked about
- (a) Viewer send. Order is correct and tested against the backend calls.
isSendingcovers the model check and the flush, and disables the composer and the option chips. See finding B for the failed-create path. - (b) Daemon claim-then-reset. I found no path where the reset fires wrongly:
- Running turn: the token is held until after the idle write, so a concurrent event gets
Nonefrombegin_turnand returns. - Between the reply's create and its idle write: same token, same result.
- Recovery:
recover_stuck_turnsclaims before the watcher subscribes, and applies the same rule. - Second window or client: any client that stores its message before the status write is handled the same way; one that writes the status first gets a usable
idlechat and awarn, not a stuck one. - One theoretical gap: the status is read before the claim, so a stale
processingread could claim just after a turn ends. The window is a mutex acquisition wide, and the outcome is a redundant idle write. Re-reading the status afterbegin_turnwould close it.
- Running turn: the token is held until after the idle write, so a concurrent event gets
- (c)
create_node_with_relationships. Atomic throughwith_transaction; embedding queue and mention sync run after commit, ascreate_placed_nodedoes. See finding C for the fallback. - (d) Reference-rule exemption. The non-transactional builtin path and
create_mentionstill refuse. See finding A for the transactional path. - (e)
descendant_count. Declared, typed, generated, stored and compared. Correct.
Code Review Findings
No critical or important findings.
🟢 Suggestions
A. The exemption also covers builtin relationships on the transactional path
📁 packages/core/src/services/node_service/relationship.rs:1189-1215
Self::refuse_ai_chat_target(relationship_name, &target, accepts_references || from_inside)?;from_insideis not gated on the relationship being declared, so amentionsorhas_roleedge from a chat or message to a chat or message passes when it comes throughcreate_relationship_in_tx(a Play'sadd_relationshipaction is the caller I can see).- The doc comment on
refuse_ai_chat_targetsays "Amentionsedge never is". - I did not confirm that a Play action can name a builtin, so reachability is unverified.
Recommendation: compute from_inside only when !is_builtin, and add one assertion to a_messages_own_edges_may_point_at_a_chat_or_a_message. Computing it only when the target is unreferenceable also removes a second source read from every declared relationship write. Principle: an exemption should be exactly as wide as its stated rule.
B. A failed send leaves the optimistic message in the conversation
📁 packages/desktop-app/src/lib/components/viewers/ai-chat-native-node-viewer.svelte:285-291
const failed = await sharedNodeStore.flushNodeSaves([messageId]);
if (failed.has(messageId)) {
sendError = 'The message could not be saved, so it was not sent.';
return;
}- The optimistic node and its structure-tree entry stay. The transcript shows a user message that is not stored, and
hasMessageslocks the model selector on it. It disappears on reload. flushNodeSavesalso reports a 5-second timeout as a failure. In that case the create may still land, so "could not be saved" can be untrue and the chat ends with a stored user message and no turn. The daemon side is safe either way.- The test for this path asserts the alert and the absent status write, not what the transcript shows.
Recommendation: on failure remove the optimistic node (or mark it failed) and put the text back in the composer; word the timeout case separately. Principle: optimistic UI should roll back when the write it anticipated fails.
C. The fallback drops every record when one edge is invalid
📁 packages/daemon/src/services/chat_messages.rs:414-441
- Any edge failure other than a missing target rolls back the transaction, and the message is then stored with no edges at all.
- That loses the turn's
wroterecords (the duplicate guard) and itspending_deleteedges. A confirmation question stored this way cannot be answered, which is the loop from the earlier finding 2, now logged atwarn. - I know of no input that triggers it today; it needs a refused edge that is not a missing target.
Recommendation: when the fallback runs for a message that held deletes, replace the question with a notice that the delete could not be held. Optional. Principle: degrade to a state the user can act on.
Recommendation
APPROVE
The suggestions are optional and none needs a further review round.
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.
Re-review addressed
|
56e5c54 to
cc54fe2
Compare
…closes #3448) A chat's messages are ai-chat-message children of its ai-chat-native node, and what a turn wrote, looked up or asked to delete is on wrote, resolved and pending_delete edges from its message (ADR-088 §3). The messages[] property, its write buffering and the soft cap are removed. Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
cc54fe2 to
15bed7d
Compare
Closes #3448.
Chat messages are now
ai-chat-messagechild nodes of theirai-chat-nativechat, and what a turn wrote, looked up or asked to delete is on edges from its message (ADR-088 §3). Themessages[]property, its write buffering, the frontend-as-source-of-truth period and the 500-message soft cap are gone. No migration: reset the database.The type
ai-chat-messageis a concrete, flat core type (node type sequence followed).role(user|assistant|system, defaultuser),timestamp,reasoning,outcome(acted|clarified|replied, assistant only),options(string[])wrote/written_by(edge fieldwrites),resolved/resolved_by(tool),pending_delete/pending_delete_of(version); all untypednone; parentmust_have_parent_of [ai-chat-native]AiChatMessageNode, no typed updateai-chat-nativelosesmessagesand becomes flat. The nested wire typesAiChatMessage,AiChatCompletedWrite,AiChatResolvedEntityandAiChatPendingDeletionare deleted;AiChatWrite/AiChatWroteEdge/AiChatResolvedEdge/AiChatPendingDeleteEdgeare the edge shapes.Where this departs from the ADRs as they were written
Each of these is now in the docs (nodespace-docs
3b3e77a,43a1cc9): ADR-088 §3, ADR-070,ai-chat-node.md,node-types.md,typed-relationships.md,participation.md,mentions-and-references.md.wroteholds a list. The relationship table allows one edge per (source, target, type), and a turn often writes one node twice (creates it, then links it). The edge'swritesfield holds each call'sseq,tool,summary,canonical_argsandreplaced, instead of three scalar fields.create_schemawrites unrecorded. A schema node still can't be an edge's source, which is what every declaration read keys on, and a typed relationship still can't reach one.pending_deletestoresdescendant_countbesideversion. The issue has the count computed when shown; storing it keeps the check that a yes deletes only what the user saw.mentionsedges.ai-chat-nativeonly;ai-chat-acpjoins when it exists.Backend
accepts_inbound_referencesin the registry replaces sixis_a(AiChat)checks so the no-reference rule covers messages too.get_child_edges: one read of the edges leaving a node's children. "What did this chat create?" is that read overwrote.create_node_with_relationships: a node and the edges from it in one transaction.chat_messages.rs): load a conversation in two reads; append a message and its edges in one transaction. A turn is asked for by the chat'sprocessingwrite, sent after the user's message is stored; aprocessingchat with no user message to answer is reset toidle.scripts/aichat.tsand the eval snapshot follow the new shape.Frontend
turn_status.get_parentlookup when the chat isn't loaded), and a chat row in a page outline never lists its messages.excludedFromDefaultQueries; "is this type an outline row" keys on it, not on the parent rule, so a user-defined type with a parent rule stays an ordinary row.Dev proxy (browser mode)
Found by running the app:
Tests
ai_chat_message_test.rs(fields, closed bucket, parent/children rules, edges, schema target, mentions, references, participation, cascade delete), registry and schema tests, the narrowed schema-target rule.canonical_argsfromwroteedges, delete confirmation across turns, the trigger for both write orders.No model-facing text changed; the prompt goldens pass unmodified.
🤖 Generated with Claude Code