Repository navigation
Remove duplicated blocks from the remaining sources (4 of 4), fix a hang in CollaborativeSession - #34
Conversation
Fourth and last batch of the files left unformatted because the copy/paste detector rejects them. - collaboration_protocol.hpp: ProtocolMessage and CollaborationProtocol share detail::escapeJsonString / detail::extractJsonInt. - collaborative_session.hpp: findDocumentLocked(). - editor_store.hpp: findDocumentOrThrowLocked(). - widgets.hpp, widgets.cpp: TextInput and TextArea share a TextEntryWidget base for their text, placeholder, read-only flag and change callback. - test_framework.hpp: runAllTests and runTestsInSuite share runSingleTest(). Macro names, arguments and messages are unchanged. - tensor_utils.hpp: extractComparableData(). - plugin_system.cpp: appendAllBuckets() and erasePluginFromBuckets(). - drawkern/ai_integration.cpp: finish_successful_inference() and model_not_found_response(). - yacc_grammar.cpp: lex_and_parse(). - widget_registration.cpp: the built-in themes share one style table. - network_buffer.cpp: concatenateSegments(). Three headers are deliberately left as they were, unformatted and still failing the detector: core/code_analyzer.hpp, drawkern/ai_integration.hpp and drawkern/drawkern.hpp. What it flags there is sibling classes each declaring the same list of overrides, which C++ requires; there is no implementation to share without changing the class hierarchy. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011vmiZ7F3rQu7dith9sQw71
joinDocument, leaveDocument, applyOperation, removeDocument and cleanupInactiveUsers invoke the user callbacks while holding documentsMutex_. The callbacks CollaborationProtocol::initialize installs call broadcastToDocument, which calls CollaborativeSession::getActiveUsers, which locks documentsMutex_ again on the same thread. With a plain std::mutex every join, leave or operation after initialize() hung. Make the mutex recursive so that re-entry from the same thread is allowed. Locking between threads is unchanged. Found by reading during the refactor; there is no test that drives the protocol and the session together, and this change does not add one. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011vmiZ7F3rQu7dith9sQw71
There was a problem hiding this comment.
🔍 Formatting rules disagree on indentation
TextEntryWidget follows the formatter’s four-space indentation. The contribution guide requires two spaces, so the checked-in rules conflict.
Was this helpful? React with 👍 or 👎 to provide feedback.
| auto docIt = documents_.find(documentId); | ||
| if (docIt == documents_.end()) { | ||
| std::lock_guard<std::recursive_mutex> lock(documentsMutex_); |
There was a problem hiding this comment.
🔴 First local collaborative edit hangs
After collaboration starts, applyOperation invokes the editor callback before applyTextEdit releases its mutex. findFilePathForDocId tries to acquire that same nonrecursive mutex on the same thread. The edit never returns.
Learn more
The editor example enables collaboration before accepting commands. The recursive session mutex now lets the startup join complete. The insert handler passes the edit to applyTextEdit, which holds the editor's file-to-document mapping mutex while calling the session. After applying the edit to the session, the session calls the editor synchronization callback inline. The callback calls findFilePathForDocId, which reacquires the mapping mutex before it can mirror the edit to the editor. The session's recursive lock does not make the mapping mutex recursive.
Example: Start the collaborative editor and enter insert 0 0 // shared. The session applies the insert, but the editor freezes before mirroring it or accepting another command.
Recommended fix: Copy the document ID while holding collaborativeDocsMutex_, then release it before calling into the session. Audit the other integration calls for the same lock ordering, and dispatch session callbacks outside the session lock using copied event data so a remote callback cannot invert that ordering. Add a bounded test that initializes collaboration and applies a local edit.
Was this helpful? React with 👍 or 👎 to provide feedback.
| if (docIt == documents_.end()) { | ||
| return false; // Document doesn't exist | ||
| bool joinDocument(const std::string& userId, const std::string& userName, const std::string& documentId) { | ||
| std::lock_guard<std::recursive_mutex> lock(documentsMutex_); |
There was a problem hiding this comment.
🔴 Collaborative editor hangs on quit
Now that joinDocument returns, quitting the collaborative editor reaches WebSocketServer::stop. On Linux, closing the listener from another thread does not wake its blocked accept. The editor hangs waiting for the listener thread.
Learn more
The editor example enables collaboration before accepting commands, and main calls stop when the command loop returns. The recursive mutex now lets the startup join finish, so a normal quit reaches shutdown. The server thread blocks in accept waiting for a client. WebSocketServer::stop clears the running flag and closes the listener from the editor thread, then joins the server thread. On Linux the pending accept can outlive that close, leaving the server thread unable to check the flag again.
Example: Start the editor on Linux, wait for its prompt without connecting a WebSocket client, and enter quit. The process waits for the listener instead of exiting.
Recommended fix: Give the accept loop an explicit wake-up path, or use a nonblocking listener with a pollable shutdown signal. Verify that stopping the server joins the listener even when no client connects.
Was this helpful? React with 👍 or 👎 to provide feedback.
|
|
||
| wsServer.onConnect([this](WebSocketConnection* conn) { handleConnection(conn); }); | ||
|
|
||
| wsServer.onDisconnect([this](WebSocketConnection* conn) { handleDisconnection(conn); }); |
There was a problem hiding this comment.
🟡 Disconnected collaborators stay in the roster
When a joined client closes its socket without leaving, handleDisconnection removes its connection but not its document membership. Nothing calls cleanupInactiveUsers, so later document snapshots still list the departed user and cursor.
Learn more
A successful WebSocket join adds the user to the document and ties the user ID to a connection. When the connection closes, handleClient calls the disconnect handler. The handler removes the connection mapping but leaves the user's document membership intact. Nothing calls cleanupInactiveUsers, and sendDocumentState includes all users still registered in the document.
Example: Alice joins a shared document then closes her client without sending a leave message. Bob opens the same document later and still sees Alice and her cursor.
Recommended fix: Track document membership per connection and remove it on disconnect. Release connectionsMutex_ before invoking any session leave callbacks, since those callbacks acquire it again to notify the remaining peers.
Was this helpful? React with 👍 or 👎 to provide feedback.
| // Recursive on purpose: the user callbacks are invoked with this lock held, | ||
| // and the ones CollaborationProtocol installs call back into this class | ||
| // (getActiveUsers) on the same thread. | ||
| mutable std::recursive_mutex documentsMutex_; |
There was a problem hiding this comment.
| // Returns the state of documentId, or nullptr if unknown. The caller must hold documentsMutex_. | ||
| DocumentState* findDocumentLocked(const std::string& documentId) { |
There was a problem hiding this comment.
🔍 New helper contracts lack Doxygen markup
The refactor uses plain comments for findDocumentLocked, extractJsonInt, and findDocumentOrThrowLocked. The contribution guide requires Doxygen-style documentation.
Was this helpful? React with 👍 or 👎 to provide feedback.
| // Create document state data | ||
| std::string stateData = "{"; | ||
| stateData += "\"content\":\"" + escapeString(content) + "\","; | ||
| stateData += "\"content\":\"" + detail::escapeJsonString(content) + "\","; |
There was a problem hiding this comment.
🟥 Unauthenticated access to shared documents
A network client that knows a shared document ID can join without proving its identity or access. handleJoinDocument now reaches the response that returns the document’s full text.
Was this helpful? React with 👍 or 👎 to provide feedback.
|
|
||
| wsServer.onConnect([this](WebSocketConnection* conn) { handleConnection(conn); }); | ||
|
|
||
| wsServer.onDisconnect([this](WebSocketConnection* conn) { handleDisconnection(conn); }); |
There was a problem hiding this comment.
🟥 Dangling collaboration broadcast connections
When a connection has multiple user IDs, handleDisconnection removes only one mapping before the server frees the connection. Later document broadcasts can dereference a remaining mapping and crash the server.
Was this helpful? React with 👍 or 👎 to provide feedback.
There was a problem hiding this comment.
🟡 Changes recommended
The callback re-entry fix lacks regression tests covering lifecycle and update callbacks, leaving the original deadlock able to recur unnoticed.
1 open issue
What changed in this PR
Completes the four-part duplication cleanup following #29 and fixes CollaborativeSession deadlocking when protocol callbacks re-enter the session.
Changes:
- Extracts shared helpers across collaboration, editor, testing, tensor, plugin, DrawKern and network code, then applies formatting and lint cleanup.
- Introduces a shared text-entry widget base and consolidates built-in theme styling.
- Uses a recursive document mutex to allow same-thread callback re-entry.
| File | Description |
|---|---|
| src/bolt/network/network_buffer.cpp | Shares segment concatenation logic. |
| src/bolt/gui/widgets.cpp | Initializes text widgets through the shared base. |
| src/bolt/gui/widget_registration.cpp | Consolidates built-in theme styling. |
| src/bolt/drawkern/yacc_grammar.cpp | Extracts shared lexing and parsing setup. |
| src/bolt/drawkern/ai_integration.cpp | Shares inference completion and missing-model responses. |
| src/bolt/core/plugin_system.cpp | Shares plugin registry collection and removal helpers. |
| include/bolt/utils/tensor_utils.hpp | Centralizes tensor comparison data preparation. |
| include/bolt/test_framework.hpp | Shares single-test execution logic. |
| include/bolt/gui/widgets.hpp | Introduces TextEntryWidget for common text-entry state. |
| include/bolt/core/editor_store.hpp | Centralizes document lookup and missing-document errors. |
| include/bolt/collaboration/collaborative_session.hpp | Shares document lookup and allows callback lock re-entry. |
| include/bolt/collaboration/collaboration_protocol.hpp | Shares JSON escaping and integer extraction helpers. |
Review effort: Balanced
| // Recursive on purpose: the user callbacks are invoked with this lock held, | ||
| // and the ones CollaborationProtocol installs call back into this class | ||
| // (getActiveUsers) on the same thread. | ||
| mutable std::recursive_mutex documentsMutex_; |

Description
Last of four pull requests that refactor the files left unformatted because the linter's copy/paste detector rejects them (previous: #31, #32, #33). It also fixes a hang found while reading one of the files.
Two commits, meant to be read separately: the refactor (no behaviour change intended) and the bug fix.
Type of Change
Related Issues
Related to #29
Changes Made
Refactor (11 files, plus
widgets.cpp)collaboration_protocol.hpp:ProtocolMessageandCollaborationProtocolsharedetail::escapeJsonString/detail::extractJsonInt.collaborative_session.hpp:findDocumentLocked().editor_store.hpp:findDocumentOrThrowLocked().widgets.hpp,widgets.cpp:TextInputandTextAreashare aTextEntryWidgetbase for their text, placeholder, read-only flag and change callback.test_framework.hpp:runAllTestsandrunTestsInSuitesharerunSingleTest(). Macro names, arguments and messages are unchanged.tensor_utils.hpp:extractComparableData().plugin_system.cpp:appendAllBuckets()anderasePluginFromBuckets().drawkern/ai_integration.cpp:finish_successful_inference()andmodel_not_found_response().yacc_grammar.cpp:lex_and_parse().widget_registration.cpp: the built-in themes share one style table. Every style field of the Dark, Light, HighContrast and a custom theme was dumped before and after and is identical.network_buffer.cpp:concatenateSegments().Three headers deliberately left untouched
core/code_analyzer.hpp,drawkern/ai_integration.hppanddrawkern/drawkern.hppstill fail the detector and are still unformatted. What it flags there is sibling classes each declaring the same list of overrides, which C++ requires; there is no implementation to share without changing the class hierarchy, and I did not want to paper over it. They will failLint Code Basethe next time a PR touches them. Options are listed under Reviewer Notes.Bug fix:
CollaborativeSessiondeadlocked on its own callbacksjoinDocument,leaveDocument,applyOperation,removeDocumentandcleanupInactiveUserscall the user callbacks while holdingdocumentsMutex_. The callbacks thatCollaborationProtocol::initializeinstalls call back intogetActiveUsers, which locks the same mutex on the same thread. With a plainstd::mutex, every join, leave or operation afterinitialize()hung.std::recursive_mutex.Testing
All existing tests pass
Locally on Linux (GCC): 98/98 CTest tests;
scripts/smoke_test.shpasses.clang-format 15.0.7, cpplint 1.6.1 and jscpd 3.5.3 report nothing on the changed files.
Not covered by a test: the deadlock fix. No test drives the protocol and the session together, and this PR does not add one; the fix is by inspection.
Not compiled here: the Windows branch of
plugin_system.cpp(reformatted only; CI builds it) and the no-GGML / no-ImGui configurations oftensor_utils.hpp,widgets.hppandwidget_registration.cpp.Reviewer Notes
TextEntryWidgetchanges the layout ofTextInput/TextAreaand makes the moved members protected instead of private. Public member functions are unchanged. It is an ABI change for anything compiled against the old header.explicit(DocumentState,TabContainer::TabInfoand others). Nothing in the tree relied on the implicit conversions.code_analyzer.cppreworked too, or (c) tune the detector's threshold. I have not done any of these.EditorStore::notifyListenersruns listeners with its mutex held, so a listener that calls back into the store deadlocks;getSelectedFile()andgetCurrentDocument()hand out a reference / pointer after releasing the lock.YaccGrammarSystem::validate_descriptioncan report errors left over from an earlier parse.ProtocolMessagedoes not round-trip:datais escaped on the way out but not unescaped on the way in, anddocumentId/userIdare not escaped at all.tensor_utils.hppdivides by the element count without checking for an empty tensor.TestSuiteonly catchesstd::exception, so a test that throws anything else aborts the run.Generated by Claude Code