Skip to content

Remove duplicated blocks from the remaining sources (4 of 4), fix a hang in CollaborativeSession - #34

Merged
drzo merged 2 commits into
mainfrom
claude/loving-archimedes-r7fcwy
Nov 21, 2026
Merged

drzo merged 2 commits into
mainfrom
claude/loving-archimedes-r7fcwy

Conversation

@drzo

@drzo drzo commented Nov 21, 2026

Copy link
Copy Markdown
Contributor

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

  • Bug fix (non-breaking change which fixes an issue)
  • Code refactoring

Related Issues

Related to #29

Changes Made

Refactor (11 files, plus widgets.cpp)

  • 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. Every style field of the Dark, Light, HighContrast and a custom theme was dumped before and after and is identical.
  • network_buffer.cpp: concatenateSegments().
  • All of these are then formatted and made cpplint-clean.

Three headers deliberately left untouched
core/code_analyzer.hpp, drawkern/ai_integration.hpp and drawkern/drawkern.hpp still 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 fail Lint Code Base the next time a PR touches them. Options are listed under Reviewer Notes.

Bug fix: CollaborativeSession deadlocked on its own callbacks

  • joinDocument, leaveDocument, applyOperation, removeDocument and cleanupInactiveUsers call the user callbacks while holding documentsMutex_. The callbacks that CollaborationProtocol::initialize installs call back into getActiveUsers, which locks the same mutex on the same thread. With a plain std::mutex, every join, leave or operation after initialize() hung.
  • The mutex is now a std::recursive_mutex.

Testing

  • All existing tests pass

  • Locally on Linux (GCC): 98/98 CTest tests; scripts/smoke_test.sh passes.

  • 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 of tensor_utils.hpp, widgets.hpp and widget_registration.cpp.

Reviewer Notes

  • TextEntryWidget changes the layout of TextInput / TextArea and 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.
  • Ten single-argument constructors became explicit (DocumentState, TabContainer::TabInfo and others). Nothing in the tree relied on the implicit conversions.
  • For the three untouched headers the choices are: (a) leave them, (b) introduce a shared intermediate base class per family, which changes the hierarchy and needs code_analyzer.cpp reworked too, or (c) tune the detector's threshold. I have not done any of these.
  • Found and not fixed here:
    • EditorStore::notifyListeners runs listeners with its mutex held, so a listener that calls back into the store deadlocks; getSelectedFile() and getCurrentDocument() hand out a reference / pointer after releasing the lock.
    • YaccGrammarSystem::validate_description can report errors left over from an earlier parse.
    • ProtocolMessage does not round-trip: data is escaped on the way out but not unescaped on the way in, and documentId / userId are not escaped at all.
    • tensor_utils.hpp divides by the element count without checking for an empty tensor.
    • TestSuite only catches std::exception, so a test that throws anything else aborts the run.

Generated by Claude Code

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
@drzo
drzo marked this pull request as ready for review November 21, 2026 19:11
Copilot AI balanced review requested due to automatic review settings November 21, 2026 19:11
@drzo
drzo merged commit c8d2171 into main Nov 21, 2026
53 of 54 checks passed

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 8 potential issues.

Devin Review

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 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.

Devin Review


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_);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 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.

Devin Review


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_);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.


wsServer.onConnect([this](WebSocketConnection* conn) { handleConnection(conn); });

wsServer.onDisconnect([this](WebSocketConnection* conn) { handleDisconnection(conn); });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +311 to +314
// 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_;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 No regression test for callback reentry

The collaboration tests do not exercise a join after CollaborationProtocol::initialize registers its callbacks. A timeout-bounded integration test would cover the lock reentry directly.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines +290 to +291
// Returns the state of documentId, or nullptr if unknown. The caller must hold documentsMutex_.
DocumentState* findDocumentLocked(const std::string& documentId) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 New helper contracts lack Doxygen markup

The refactor uses plain comments for findDocumentLocked, extractJsonInt, and findDocumentOrThrowLocked. The contribution guide requires Doxygen-style documentation.

Devin Review


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) + "\",";

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟥 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.


wsServer.onConnect([this](WebSocketConnection* conn) { handleConnection(conn); });

wsServer.onDisconnect([this](WebSocketConnection* conn) { handleDisconnection(conn); });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟥 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.

Devin Review


Was this helpful? React with 👍 or 👎 to provide feedback.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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_;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants