danylokhodus commited on
Commit
e44f847
·
1 Parent(s): 0df49d6

feat(sync): replace polling-based WebRTC with high-performance unified SignalR-bridge UDP WebRTC sync

Browse files
package-lock.json CHANGED
@@ -8,6 +8,7 @@
8
  "name": "flowweb",
9
  "version": "0.0.0",
10
  "dependencies": {
 
11
  "@react-oauth/google": "^0.13.5",
12
  "@xyflow/react": "^12.10.2",
13
  "axios": "^1.16.1",
@@ -577,6 +578,19 @@
577
  "@jridgewell/sourcemap-codec": "^1.4.14"
578
  }
579
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
580
  "node_modules/@napi-rs/wasm-runtime": {
581
  "version": "1.1.4",
582
  "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz",
@@ -1376,6 +1390,18 @@
1376
  "d3-zoom": "^3.0.0"
1377
  }
1378
  },
 
 
 
 
 
 
 
 
 
 
 
 
1379
  "node_modules/acorn": {
1380
  "version": "8.16.0",
1381
  "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
@@ -2080,6 +2106,24 @@
2080
  "node": ">=0.10.0"
2081
  }
2082
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2083
  "node_modules/fast-deep-equal": {
2084
  "version": "3.1.3",
2085
  "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
@@ -2119,6 +2163,16 @@
2119
  }
2120
  }
2121
  },
 
 
 
 
 
 
 
 
 
 
2122
  "node_modules/file-entry-cache": {
2123
  "version": "8.0.0",
2124
  "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
@@ -3024,6 +3078,26 @@
3024
  "dev": true,
3025
  "license": "MIT"
3026
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3027
  "node_modules/node-releases": {
3028
  "version": "2.0.38",
3029
  "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.38.tgz",
@@ -3176,16 +3250,33 @@
3176
  "node": ">=10"
3177
  }
3178
  },
 
 
 
 
 
 
 
 
 
 
 
 
3179
  "node_modules/punycode": {
3180
  "version": "2.3.1",
3181
  "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
3182
  "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
3183
- "dev": true,
3184
  "license": "MIT",
3185
  "engines": {
3186
  "node": ">=6"
3187
  }
3188
  },
 
 
 
 
 
 
3189
  "node_modules/react": {
3190
  "version": "19.2.6",
3191
  "resolved": "https://registry.npmjs.org/react/-/react-19.2.6.tgz",
@@ -3272,6 +3363,12 @@
3272
  "react-dom": ">=18"
3273
  }
3274
  },
 
 
 
 
 
 
3275
  "node_modules/rolldown": {
3276
  "version": "1.0.0-rc.18",
3277
  "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.18.tgz",
@@ -3406,6 +3503,27 @@
3406
  "url": "https://github.com/sponsors/SuperchupuDev"
3407
  }
3408
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3409
  "node_modules/tslib": {
3410
  "version": "2.8.1",
3411
  "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
@@ -3425,6 +3543,15 @@
3425
  "node": ">= 0.8.0"
3426
  }
3427
  },
 
 
 
 
 
 
 
 
 
3428
  "node_modules/update-browserslist-db": {
3429
  "version": "1.2.3",
3430
  "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
@@ -3466,6 +3593,16 @@
3466
  "punycode": "^2.1.0"
3467
  }
3468
  },
 
 
 
 
 
 
 
 
 
 
3469
  "node_modules/use-sync-external-store": {
3470
  "version": "1.6.0",
3471
  "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
@@ -3562,6 +3699,22 @@
3562
  "node": ">=0.10.0"
3563
  }
3564
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3565
  "node_modules/which": {
3566
  "version": "2.0.2",
3567
  "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
@@ -3588,6 +3741,27 @@
3588
  "node": ">=0.10.0"
3589
  }
3590
  },
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3591
  "node_modules/yallist": {
3592
  "version": "3.1.1",
3593
  "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
 
8
  "name": "flowweb",
9
  "version": "0.0.0",
10
  "dependencies": {
11
+ "@microsoft/signalr": "^10.0.0",
12
  "@react-oauth/google": "^0.13.5",
13
  "@xyflow/react": "^12.10.2",
14
  "axios": "^1.16.1",
 
578
  "@jridgewell/sourcemap-codec": "^1.4.14"
579
  }
580
  },
581
+ "node_modules/@microsoft/signalr": {
582
+ "version": "10.0.0",
583
+ "resolved": "https://registry.npmjs.org/@microsoft/signalr/-/signalr-10.0.0.tgz",
584
+ "integrity": "sha512-0BRqz/uCx3JdrOqiqgFhih/+hfTERaUfCZXFB52uMaZJrKaPRzHzMuqVsJC/V3pt7NozcNXGspjKiQEK+X7P2w==",
585
+ "license": "MIT",
586
+ "dependencies": {
587
+ "abort-controller": "^3.0.0",
588
+ "eventsource": "^2.0.2",
589
+ "fetch-cookie": "^2.0.3",
590
+ "node-fetch": "^2.6.7",
591
+ "ws": "^7.5.10"
592
+ }
593
+ },
594
  "node_modules/@napi-rs/wasm-runtime": {
595
  "version": "1.1.4",
596
  "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.4.tgz",
 
1390
  "d3-zoom": "^3.0.0"
1391
  }
1392
  },
1393
+ "node_modules/abort-controller": {
1394
+ "version": "3.0.0",
1395
+ "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz",
1396
+ "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==",
1397
+ "license": "MIT",
1398
+ "dependencies": {
1399
+ "event-target-shim": "^5.0.0"
1400
+ },
1401
+ "engines": {
1402
+ "node": ">=6.5"
1403
+ }
1404
+ },
1405
  "node_modules/acorn": {
1406
  "version": "8.16.0",
1407
  "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
 
2106
  "node": ">=0.10.0"
2107
  }
2108
  },
2109
+ "node_modules/event-target-shim": {
2110
+ "version": "5.0.1",
2111
+ "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz",
2112
+ "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==",
2113
+ "license": "MIT",
2114
+ "engines": {
2115
+ "node": ">=6"
2116
+ }
2117
+ },
2118
+ "node_modules/eventsource": {
2119
+ "version": "2.0.2",
2120
+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-2.0.2.tgz",
2121
+ "integrity": "sha512-IzUmBGPR3+oUG9dUeXynyNmf91/3zUSJg1lCktzKw47OXuhco54U3r9B7O4XX+Rb1Itm9OZ2b0RkTs10bICOxA==",
2122
+ "license": "MIT",
2123
+ "engines": {
2124
+ "node": ">=12.0.0"
2125
+ }
2126
+ },
2127
  "node_modules/fast-deep-equal": {
2128
  "version": "3.1.3",
2129
  "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz",
 
2163
  }
2164
  }
2165
  },
2166
+ "node_modules/fetch-cookie": {
2167
+ "version": "2.2.0",
2168
+ "resolved": "https://registry.npmjs.org/fetch-cookie/-/fetch-cookie-2.2.0.tgz",
2169
+ "integrity": "sha512-h9AgfjURuCgA2+2ISl8GbavpUdR+WGAM2McW/ovn4tVccegp8ZqCKWSBR8uRdM8dDNlx5WdKRWxBYUwteLDCNQ==",
2170
+ "license": "Unlicense",
2171
+ "dependencies": {
2172
+ "set-cookie-parser": "^2.4.8",
2173
+ "tough-cookie": "^4.0.0"
2174
+ }
2175
+ },
2176
  "node_modules/file-entry-cache": {
2177
  "version": "8.0.0",
2178
  "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz",
 
3078
  "dev": true,
3079
  "license": "MIT"
3080
  },
3081
+ "node_modules/node-fetch": {
3082
+ "version": "2.7.0",
3083
+ "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz",
3084
+ "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==",
3085
+ "license": "MIT",
3086
+ "dependencies": {
3087
+ "whatwg-url": "^5.0.0"
3088
+ },
3089
+ "engines": {
3090
+ "node": "4.x || >=6.0.0"
3091
+ },
3092
+ "peerDependencies": {
3093
+ "encoding": "^0.1.0"
3094
+ },
3095
+ "peerDependenciesMeta": {
3096
+ "encoding": {
3097
+ "optional": true
3098
+ }
3099
+ }
3100
+ },
3101
  "node_modules/node-releases": {
3102
  "version": "2.0.38",
3103
  "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.38.tgz",
 
3250
  "node": ">=10"
3251
  }
3252
  },
3253
+ "node_modules/psl": {
3254
+ "version": "1.15.0",
3255
+ "resolved": "https://registry.npmjs.org/psl/-/psl-1.15.0.tgz",
3256
+ "integrity": "sha512-JZd3gMVBAVQkSs6HdNZo9Sdo0LNcQeMNP3CozBJb3JYC/QUYZTnKxP+f8oWRX4rHP5EurWxqAHTSwUCjlNKa1w==",
3257
+ "license": "MIT",
3258
+ "dependencies": {
3259
+ "punycode": "^2.3.1"
3260
+ },
3261
+ "funding": {
3262
+ "url": "https://github.com/sponsors/lupomontero"
3263
+ }
3264
+ },
3265
  "node_modules/punycode": {
3266
  "version": "2.3.1",
3267
  "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
3268
  "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
 
3269
  "license": "MIT",
3270
  "engines": {
3271
  "node": ">=6"
3272
  }
3273
  },
3274
+ "node_modules/querystringify": {
3275
+ "version": "2.2.0",
3276
+ "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz",
3277
+ "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==",
3278
+ "license": "MIT"
3279
+ },
3280
  "node_modules/react": {
3281
  "version": "19.2.6",
3282
  "resolved": "https://registry.npmjs.org/react/-/react-19.2.6.tgz",
 
3363
  "react-dom": ">=18"
3364
  }
3365
  },
3366
+ "node_modules/requires-port": {
3367
+ "version": "1.0.0",
3368
+ "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz",
3369
+ "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==",
3370
+ "license": "MIT"
3371
+ },
3372
  "node_modules/rolldown": {
3373
  "version": "1.0.0-rc.18",
3374
  "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.0-rc.18.tgz",
 
3503
  "url": "https://github.com/sponsors/SuperchupuDev"
3504
  }
3505
  },
3506
+ "node_modules/tough-cookie": {
3507
+ "version": "4.1.4",
3508
+ "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz",
3509
+ "integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==",
3510
+ "license": "BSD-3-Clause",
3511
+ "dependencies": {
3512
+ "psl": "^1.1.33",
3513
+ "punycode": "^2.1.1",
3514
+ "universalify": "^0.2.0",
3515
+ "url-parse": "^1.5.3"
3516
+ },
3517
+ "engines": {
3518
+ "node": ">=6"
3519
+ }
3520
+ },
3521
+ "node_modules/tr46": {
3522
+ "version": "0.0.3",
3523
+ "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
3524
+ "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
3525
+ "license": "MIT"
3526
+ },
3527
  "node_modules/tslib": {
3528
  "version": "2.8.1",
3529
  "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
 
3543
  "node": ">= 0.8.0"
3544
  }
3545
  },
3546
+ "node_modules/universalify": {
3547
+ "version": "0.2.0",
3548
+ "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz",
3549
+ "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==",
3550
+ "license": "MIT",
3551
+ "engines": {
3552
+ "node": ">= 4.0.0"
3553
+ }
3554
+ },
3555
  "node_modules/update-browserslist-db": {
3556
  "version": "1.2.3",
3557
  "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
 
3593
  "punycode": "^2.1.0"
3594
  }
3595
  },
3596
+ "node_modules/url-parse": {
3597
+ "version": "1.5.10",
3598
+ "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz",
3599
+ "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==",
3600
+ "license": "MIT",
3601
+ "dependencies": {
3602
+ "querystringify": "^2.1.1",
3603
+ "requires-port": "^1.0.0"
3604
+ }
3605
+ },
3606
  "node_modules/use-sync-external-store": {
3607
  "version": "1.6.0",
3608
  "resolved": "https://registry.npmjs.org/use-sync-external-store/-/use-sync-external-store-1.6.0.tgz",
 
3699
  "node": ">=0.10.0"
3700
  }
3701
  },
3702
+ "node_modules/webidl-conversions": {
3703
+ "version": "3.0.1",
3704
+ "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
3705
+ "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
3706
+ "license": "BSD-2-Clause"
3707
+ },
3708
+ "node_modules/whatwg-url": {
3709
+ "version": "5.0.0",
3710
+ "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
3711
+ "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
3712
+ "license": "MIT",
3713
+ "dependencies": {
3714
+ "tr46": "~0.0.3",
3715
+ "webidl-conversions": "^3.0.0"
3716
+ }
3717
+ },
3718
  "node_modules/which": {
3719
  "version": "2.0.2",
3720
  "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
 
3741
  "node": ">=0.10.0"
3742
  }
3743
  },
3744
+ "node_modules/ws": {
3745
+ "version": "7.5.10",
3746
+ "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz",
3747
+ "integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==",
3748
+ "license": "MIT",
3749
+ "engines": {
3750
+ "node": ">=8.3.0"
3751
+ },
3752
+ "peerDependencies": {
3753
+ "bufferutil": "^4.0.1",
3754
+ "utf-8-validate": "^5.0.2"
3755
+ },
3756
+ "peerDependenciesMeta": {
3757
+ "bufferutil": {
3758
+ "optional": true
3759
+ },
3760
+ "utf-8-validate": {
3761
+ "optional": true
3762
+ }
3763
+ }
3764
+ },
3765
  "node_modules/yallist": {
3766
  "version": "3.1.1",
3767
  "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz",
package.json CHANGED
@@ -10,6 +10,7 @@
10
  "preview": "vite preview"
11
  },
12
  "dependencies": {
 
13
  "@react-oauth/google": "^0.13.5",
14
  "@xyflow/react": "^12.10.2",
15
  "axios": "^1.16.1",
 
10
  "preview": "vite preview"
11
  },
12
  "dependencies": {
13
+ "@microsoft/signalr": "^10.0.0",
14
  "@react-oauth/google": "^0.13.5",
15
  "@xyflow/react": "^12.10.2",
16
  "axios": "^1.16.1",
src/features/canvas/hooks/useCanvasLogic.js CHANGED
@@ -11,7 +11,7 @@ import {
11
  getIncomers,
12
  useReactFlow,
13
  } from '@xyflow/react';
14
- import { useWebRTC } from './useWebRTC';
15
 
16
  export const getConditionSourceHandle = (sourceNode, condition) => {
17
  if (!sourceNode) return null;
@@ -246,8 +246,8 @@ export const useCanvasLogic = (projectId, user) => {
246
  }
247
  }, [setNodes, setEdges, updateNodeDataCallback]);
248
 
249
- // Hook up WebRTC Data Channels
250
- const { peers, activeUsers, broadcastMessage } = useWebRTC(projectId, user, onRemoteMessage);
251
 
252
  // Sync activeUsers to the Ref for safe use inside onRemoteMessage callbacks without dependency cycles
253
  useEffect(() => {
 
11
  getIncomers,
12
  useReactFlow,
13
  } from '@xyflow/react';
14
+ import { useSignalR } from './useSignalR';
15
 
16
  export const getConditionSourceHandle = (sourceNode, condition) => {
17
  if (!sourceNode) return null;
 
246
  }
247
  }, [setNodes, setEdges, updateNodeDataCallback]);
248
 
249
+ // Hook up SignalR Hub connection for real-time collaboration
250
+ const { peers, activeUsers, broadcastMessage } = useSignalR(projectId, user, onRemoteMessage);
251
 
252
  // Sync activeUsers to the Ref for safe use inside onRemoteMessage callbacks without dependency cycles
253
  useEffect(() => {
src/features/canvas/hooks/{useWebRTC.js → useSignalR.js} RENAMED
@@ -1,14 +1,15 @@
1
  import { useEffect, useRef, useState } from 'react';
2
- import axios from 'axios';
3
 
4
- export const useWebRTC = (projectId, user, onRemoteMessage) => {
5
  const [peers, setPeers] = useState({});
6
  const [activeUsers, setActiveUsers] = useState([]);
7
 
 
8
  const peerConnectionsRef = useRef({}); // userId -> RTCPeerConnection
9
  const dataChannelsRef = useRef({}); // userId -> RTCDataChannel
10
- const activeUsersRef = useRef([]);
11
  const pendingCandidatesRef = useRef({}); // userId -> RTCIceCandidate[]
 
12
 
13
  const onRemoteMessageRef = useRef(onRemoteMessage);
14
  useEffect(() => {
@@ -18,17 +19,15 @@ export const useWebRTC = (projectId, user, onRemoteMessage) => {
18
  const API_URL = import.meta.env.VITE_API_URL;
19
  const token = localStorage.getItem('token') || '';
20
 
21
- // Standard RTC Configuration with public Google STUN servers for local/NAT traversing
22
  const rtcConfig = {
23
  iceServers: [
24
- // Standard Google STUN
25
  { urls: 'stun:stun.l.google.com:19302' },
26
  { urls: 'stun:stun1.l.google.com:19302' },
27
  { urls: 'stun:stun2.l.google.com:19302' },
28
  { urls: 'stun:stun3.l.google.com:19302' },
29
  { urls: 'stun:stun4.l.google.com:19302' },
30
 
31
- // OpenRelay Public STUN/TURN (relays WebRTC traffic through firewalls/NATs)
32
  { urls: 'stun:openrelay.metered.ca:80' },
33
  {
34
  urls: 'turn:openrelay.metered.ca:80',
@@ -49,54 +48,7 @@ export const useWebRTC = (projectId, user, onRemoteMessage) => {
49
  iceCandidatePoolSize: 10
50
  };
51
 
52
- // Helper to get authenticated headers
53
- const getHeaders = () => ({
54
- headers: {
55
- Authorization: `Bearer ${token}`
56
- }
57
- });
58
-
59
- // --- 1. Heartbeat Presence & Poll Online Users ---
60
- useEffect(() => {
61
- if (!projectId || !user || !user.id || !token) return;
62
-
63
- const runPresenceCycle = async () => {
64
- try {
65
- // Register local presence
66
- await axios.post(`${API_URL}/sync/${projectId}/presence`, {}, getHeaders());
67
-
68
- // Get active users in the project
69
- const res = await axios.get(`${API_URL}/sync/${projectId}/presence`, getHeaders());
70
- const onlineUsers = res.data.filter(u => u.userId !== user.id); // exclude self
71
-
72
- setActiveUsers(onlineUsers);
73
- activeUsersRef.current = onlineUsers;
74
-
75
- // Check if any peer has gone offline and clean up
76
- const onlineUserIds = new Set(onlineUsers.map(u => u.userId));
77
- Object.keys(peerConnectionsRef.current).forEach(peerId => {
78
- if (!onlineUserIds.has(peerId)) {
79
- console.log(`Peer ${peerId} went offline. Cleaning up.`);
80
- cleanupPeer(peerId);
81
- }
82
- });
83
- } catch (err) {
84
- console.error('Error in WebRTC presence cycle', err);
85
- }
86
- };
87
-
88
- // Run immediately and then every 3 seconds
89
- runPresenceCycle();
90
- const interval = setInterval(runPresenceCycle, 3000);
91
-
92
- return () => {
93
- clearInterval(interval);
94
- // Clean up all peer connections on unmount
95
- Object.keys(peerConnectionsRef.current).forEach(cleanupPeer);
96
- };
97
- }, [projectId, user, token, API_URL]);
98
-
99
- // --- 2. Clean Up Specific Peer Connection ---
100
  const cleanupPeer = (peerId) => {
101
  if (dataChannelsRef.current[peerId]) {
102
  try { dataChannelsRef.current[peerId].close(); } catch (e) {}
@@ -113,39 +65,36 @@ export const useWebRTC = (projectId, user, onRemoteMessage) => {
113
  });
114
  };
115
 
116
- // --- 3. Send Signal to Peer via Backend ---
117
- const sendSignal = async (receiverId, type, data) => {
 
118
  try {
119
- await axios.post(`${API_URL}/sync/${projectId}/signal`, {
120
- receiverId,
121
- type,
122
- data: JSON.stringify(data)
123
- }, getHeaders());
124
  } catch (err) {
125
- console.error(`Failed to send signal ${type} to ${receiverId}`, err);
126
  }
127
  };
128
 
129
- // --- 4. Setup Local RTCPeerConnection Event Handlers ---
130
- const createPeerConnection = (peerId, info) => {
131
  if (peerConnectionsRef.current[peerId]) {
132
  return peerConnectionsRef.current[peerId];
133
  }
134
 
135
- console.log(`Creating RTCPeerConnection for peer ${peerId}`);
136
  const pc = new RTCPeerConnection(rtcConfig);
137
  peerConnectionsRef.current[peerId] = pc;
138
 
139
  // Handle ICE Candidates
140
  pc.onicecandidate = (event) => {
141
  if (event.candidate) {
142
- sendSignal(peerId, 'candidate', event.candidate);
143
  }
144
  };
145
 
146
  // Monitor Connection State
147
  pc.onconnectionstatechange = () => {
148
- console.log(`Connection state with peer ${peerId}: ${pc.connectionState}`);
149
  if (pc.connectionState === 'disconnected' || pc.connectionState === 'failed') {
150
  cleanupPeer(peerId);
151
  } else {
@@ -174,12 +123,12 @@ export const useWebRTC = (projectId, user, onRemoteMessage) => {
174
  return pc;
175
  };
176
 
177
- // --- 5. Configure Data Channel Events ---
178
  const setupDataChannel = (peerId, channel) => {
179
  dataChannelsRef.current[peerId] = channel;
180
 
181
  channel.onopen = () => {
182
- console.log(`RTC Data Channel opened with peer ${peerId}`);
183
  setPeers(prev => ({
184
  ...prev,
185
  [peerId]: {
@@ -190,7 +139,7 @@ export const useWebRTC = (projectId, user, onRemoteMessage) => {
190
  };
191
 
192
  channel.onclose = () => {
193
- console.log(`RTC Data Channel closed with peer ${peerId}`);
194
  setPeers(prev => ({
195
  ...prev,
196
  [peerId]: {
@@ -201,7 +150,7 @@ export const useWebRTC = (projectId, user, onRemoteMessage) => {
201
  };
202
 
203
  channel.onerror = (err) => {
204
- console.error(`RTC Data Channel error with peer ${peerId}`, err);
205
  };
206
 
207
  channel.onmessage = (event) => {
@@ -211,142 +160,283 @@ export const useWebRTC = (projectId, user, onRemoteMessage) => {
211
  onRemoteMessageRef.current(peerId, message);
212
  }
213
  } catch (e) {
214
- console.error('Failed to parse WebRTC incoming message', e);
215
  }
216
  };
217
  };
218
 
219
- // --- 6. Active Connection Initiator Logic ---
220
- // A tie-breaker initiates connection: the user with the lexicographically higher ID initiates!
221
  useEffect(() => {
222
- if (activeUsers.length === 0 || !user || !user.id) return;
223
 
224
- activeUsers.forEach(async (peer) => {
225
- const peerId = peer.userId;
226
-
227
- // If we are the initiator (our ID is greater) and connection doesn't exist yet
228
- if (user.id > peerId && !peerConnectionsRef.current[peerId]) {
229
- console.log(`Initiating WebRTC connection to peer ${peerId}`);
230
- const pc = createPeerConnection(peerId, peer);
231
-
232
- // Create the outgoing P2P Data Channel
233
- const channel = pc.createDataChannel('taskflow-sync-channel', {
234
- ordered: true
235
- });
236
- setupDataChannel(peerId, channel);
237
-
238
- try {
239
- const offer = await pc.createOffer();
240
- await pc.setLocalDescription(offer);
241
- await sendSignal(peerId, 'offer', offer);
242
- } catch (err) {
243
- console.error(`Failed to create offer for ${peerId}`, err);
 
 
 
 
 
 
 
244
  }
245
- }
246
- });
247
- }, [activeUsers, user]);
248
 
249
- // --- 7. Poll Backend Signaling for Incoming Signaling Packets ---
250
- useEffect(() => {
251
- if (!projectId || !user || !user.id || !token) return;
 
 
 
 
 
 
 
 
 
252
 
253
- const processPendingCandidates = async (peerId, pc) => {
254
- const candidates = pendingCandidatesRef.current[peerId];
255
- if (candidates && candidates.length > 0) {
256
- console.log(`Applying ${candidates.length} queued ICE candidates for peer ${peerId}`);
257
- while (candidates.length > 0) {
258
- const cand = candidates.shift();
259
  try {
260
- await pc.addIceCandidate(new RTCIceCandidate(cand));
261
- } catch (e) {
262
- console.error('Error adding queued ICE candidate', e);
 
 
263
  }
264
  }
265
- }
266
- };
267
 
268
- const pollSignals = async () => {
 
269
  try {
270
- const res = await axios.get(`${API_URL}/sync/${projectId}/signal`, getHeaders());
271
- const signals = res.data;
272
-
273
- for (const signal of signals) {
274
- const peerId = signal.senderId;
275
- const type = signal.type;
276
-
277
- // Guard: Never process own signals
278
- if (peerId === user.id) {
279
- continue;
 
 
 
 
 
280
  }
 
281
 
282
- const signalData = JSON.parse(signal.data);
283
-
284
- const peerInfo = activeUsersRef.current.find(u => u.userId === peerId);
285
-
286
- if (type === 'offer') {
287
- console.log(`Received WebRTC SDP Offer from peer ${peerId}`);
288
- const pc = createPeerConnection(peerId, peerInfo);
289
 
290
- // Set up receiving Data Channel when offered
291
- pc.ondatachannel = (event) => {
292
- setupDataChannel(peerId, event.channel);
293
- };
294
 
 
 
 
 
 
 
 
 
 
 
 
295
  await pc.setRemoteDescription(new RTCSessionDescription(signalData));
296
- await processPendingCandidates(peerId, pc);
297
- const answer = await pc.createAnswer();
298
- await pc.setLocalDescription(answer);
299
- await sendSignal(peerId, 'answer', answer);
300
- }
301
- else if (type === 'answer') {
302
- console.log(`Received WebRTC SDP Answer from peer ${peerId}`);
303
- const pc = peerConnectionsRef.current[peerId];
304
- if (pc) {
305
- await pc.setRemoteDescription(new RTCSessionDescription(signalData));
306
- await processPendingCandidates(peerId, pc);
307
  }
308
- }
309
- else if (type === 'candidate') {
310
- console.log(`Received WebRTC ICE Candidate from peer ${peerId}`);
311
- const pc = peerConnectionsRef.current[peerId];
312
- if (pc && pc.remoteDescription) {
313
- try {
314
- await pc.addIceCandidate(new RTCIceCandidate(signalData));
315
- } catch (e) {
316
- console.error('Error adding received ICE candidate', e);
317
- }
318
- } else {
319
- if (!pendingCandidatesRef.current[peerId]) {
320
- pendingCandidatesRef.current[peerId] = [];
321
- }
322
- pendingCandidatesRef.current[peerId].push(signalData);
323
- console.log(`Queued ICE candidate for peer ${peerId} (remoteDescription is null)`);
324
  }
 
 
325
  }
326
  }
327
  } catch (err) {
328
- console.error('Error polling WebRTC signals', err);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
  }
330
  };
331
 
332
- // Poll signals aggressively every 1.5 seconds for instant room joins
333
- const interval = setInterval(pollSignals, 1500);
334
- return () => clearInterval(interval);
 
 
 
 
 
 
 
335
  }, [projectId, user, token, API_URL]);
336
 
337
- // --- 8. Broadcast Message to All Connected Peers ---
338
- const broadcastMessage = (msg) => {
339
- const payload = JSON.stringify(msg);
340
- Object.keys(dataChannelsRef.current).forEach(peerId => {
341
- const channel = dataChannelsRef.current[peerId];
342
- if (channel && channel.readyState === 'open') {
343
- try {
344
- channel.send(payload);
345
- } catch (e) {
346
- console.error(`Failed to broadcast message to peer ${peerId}`, e);
 
 
 
 
 
 
 
 
 
 
347
  }
 
 
 
 
 
 
 
348
  }
349
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
350
  };
351
 
352
  return {
 
1
  import { useEffect, useRef, useState } from 'react';
2
+ import * as signalR from '@microsoft/signalr';
3
 
4
+ export const useSignalR = (projectId, user, onRemoteMessage) => {
5
  const [peers, setPeers] = useState({});
6
  const [activeUsers, setActiveUsers] = useState([]);
7
 
8
+ const connectionRef = useRef(null);
9
  const peerConnectionsRef = useRef({}); // userId -> RTCPeerConnection
10
  const dataChannelsRef = useRef({}); // userId -> RTCDataChannel
 
11
  const pendingCandidatesRef = useRef({}); // userId -> RTCIceCandidate[]
12
+ const activeUsersRef = useRef([]);
13
 
14
  const onRemoteMessageRef = useRef(onRemoteMessage);
15
  useEffect(() => {
 
19
  const API_URL = import.meta.env.VITE_API_URL;
20
  const token = localStorage.getItem('token') || '';
21
 
22
+ // Standard RTC Configuration with public Google STUN and openrelay TURN servers for robust NAT traversing
23
  const rtcConfig = {
24
  iceServers: [
 
25
  { urls: 'stun:stun.l.google.com:19302' },
26
  { urls: 'stun:stun1.l.google.com:19302' },
27
  { urls: 'stun:stun2.l.google.com:19302' },
28
  { urls: 'stun:stun3.l.google.com:19302' },
29
  { urls: 'stun:stun4.l.google.com:19302' },
30
 
 
31
  { urls: 'stun:openrelay.metered.ca:80' },
32
  {
33
  urls: 'turn:openrelay.metered.ca:80',
 
48
  iceCandidatePoolSize: 10
49
  };
50
 
51
+ // Clean Up Specific Peer Connection
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  const cleanupPeer = (peerId) => {
53
  if (dataChannelsRef.current[peerId]) {
54
  try { dataChannelsRef.current[peerId].close(); } catch (e) {}
 
65
  });
66
  };
67
 
68
+ // Send WebRTC Signaling Packet to Peer via SignalR BoardHub
69
+ const sendSignal = async (connection, receiverId, type, data) => {
70
+ if (!connection || connection.state !== signalR.HubConnectionState.Connected) return;
71
  try {
72
+ await connection.invoke('SendSignal', projectId, receiverId, type, JSON.stringify(data));
 
 
 
 
73
  } catch (err) {
74
+ console.error(`[WebRTC] Failed to send signal ${type} to ${receiverId}`, err);
75
  }
76
  };
77
 
78
+ // Setup Local RTCPeerConnection Event Handlers
79
+ const createPeerConnection = (connection, peerId, info) => {
80
  if (peerConnectionsRef.current[peerId]) {
81
  return peerConnectionsRef.current[peerId];
82
  }
83
 
84
+ console.log(`[WebRTC] Creating RTCPeerConnection for peer ${peerId}`);
85
  const pc = new RTCPeerConnection(rtcConfig);
86
  peerConnectionsRef.current[peerId] = pc;
87
 
88
  // Handle ICE Candidates
89
  pc.onicecandidate = (event) => {
90
  if (event.candidate) {
91
+ sendSignal(connection, peerId, 'candidate', event.candidate);
92
  }
93
  };
94
 
95
  // Monitor Connection State
96
  pc.onconnectionstatechange = () => {
97
+ console.log(`[WebRTC] Connection state with peer ${peerId}: ${pc.connectionState}`);
98
  if (pc.connectionState === 'disconnected' || pc.connectionState === 'failed') {
99
  cleanupPeer(peerId);
100
  } else {
 
123
  return pc;
124
  };
125
 
126
+ // Configure Data Channel Events
127
  const setupDataChannel = (peerId, channel) => {
128
  dataChannelsRef.current[peerId] = channel;
129
 
130
  channel.onopen = () => {
131
+ console.log(`[WebRTC] RTC Data Channel opened with peer ${peerId}`);
132
  setPeers(prev => ({
133
  ...prev,
134
  [peerId]: {
 
139
  };
140
 
141
  channel.onclose = () => {
142
+ console.log(`[WebRTC] RTC Data Channel closed with peer ${peerId}`);
143
  setPeers(prev => ({
144
  ...prev,
145
  [peerId]: {
 
150
  };
151
 
152
  channel.onerror = (err) => {
153
+ console.error(`[WebRTC] RTC Data Channel error with peer ${peerId}`, err);
154
  };
155
 
156
  channel.onmessage = (event) => {
 
160
  onRemoteMessageRef.current(peerId, message);
161
  }
162
  } catch (e) {
163
+ console.error('[WebRTC] Failed to parse incoming message', e);
164
  }
165
  };
166
  };
167
 
 
 
168
  useEffect(() => {
169
+ if (!projectId || !user || !user.id || !token) return;
170
 
171
+ const hubUrl = API_URL.replace(/\/api$/, '') + '/hubs/board';
172
+
173
+ console.log('[SignalR] Connecting to hub at:', hubUrl);
174
+ const connection = new signalR.HubConnectionBuilder()
175
+ .withUrl(hubUrl, {
176
+ accessTokenFactory: () => token,
177
+ skipNegotiation: true,
178
+ transport: signalR.HttpTransportType.WebSockets
179
+ })
180
+ .withAutomaticReconnect()
181
+ .build();
182
+
183
+ connectionRef.current = connection;
184
+
185
+ // Presence updates
186
+ connection.on('PresenceUpdated', (uniquePresences) => {
187
+ console.log('[SignalR] Presence updated:', uniquePresences);
188
+ const onlineUsers = uniquePresences.filter(u => u.userId !== user.id);
189
+ setActiveUsers(onlineUsers);
190
+ activeUsersRef.current = onlineUsers;
191
+
192
+ // 1. Clean up offline peers
193
+ const onlineUserIds = new Set(onlineUsers.map(u => u.userId));
194
+ Object.keys(peerConnectionsRef.current).forEach(peerId => {
195
+ if (!onlineUserIds.has(peerId)) {
196
+ console.log(`[WebRTC] Peer ${peerId} went offline. Cleaning up.`);
197
+ cleanupPeer(peerId);
198
  }
199
+ });
 
 
200
 
201
+ // 2. Initiate connection with peers where we are the initiator (tie-breaker: our user ID is lexicographically greater)
202
+ onlineUsers.forEach(async (peer) => {
203
+ const peerId = peer.userId;
204
+ if (user.id > peerId && !peerConnectionsRef.current[peerId]) {
205
+ console.log(`[WebRTC] Initiating connection to peer ${peerId}`);
206
+ const pc = createPeerConnection(connection, peerId, peer);
207
+
208
+ // Create outgoing data channel
209
+ const channel = pc.createDataChannel('taskflow-sync-channel', {
210
+ ordered: true
211
+ });
212
+ setupDataChannel(peerId, channel);
213
 
 
 
 
 
 
 
214
  try {
215
+ const offer = await pc.createOffer();
216
+ await pc.setLocalDescription(offer);
217
+ await sendSignal(connection, peerId, 'offer', offer);
218
+ } catch (err) {
219
+ console.error(`[WebRTC] Failed to create offer for ${peerId}`, err);
220
  }
221
  }
222
+ });
223
+ });
224
 
225
+ // WebRTC Signaling Bridge receiver
226
+ connection.on('ReceiveSignal', async (senderUserId, type, dataJson) => {
227
  try {
228
+ const signalData = JSON.parse(dataJson);
229
+ const peerInfo = activeUsersRef.current.find(u => u.userId === senderUserId);
230
+
231
+ const processPendingCandidates = async (peerId, pc) => {
232
+ const candidates = pendingCandidatesRef.current[peerId];
233
+ if (candidates && candidates.length > 0) {
234
+ console.log(`[WebRTC] Applying ${candidates.length} queued ICE candidates for peer ${peerId}`);
235
+ while (candidates.length > 0) {
236
+ const cand = candidates.shift();
237
+ try {
238
+ await pc.addIceCandidate(new RTCIceCandidate(cand));
239
+ } catch (e) {
240
+ console.error('[WebRTC] Error adding queued ICE candidate', e);
241
+ }
242
+ }
243
  }
244
+ };
245
 
246
+ if (type === 'offer') {
247
+ console.log(`[WebRTC] Received SDP Offer from peer ${senderUserId}`);
248
+ const pc = createPeerConnection(connection, senderUserId, peerInfo);
 
 
 
 
249
 
250
+ // Capture incoming data channel
251
+ pc.ondatachannel = (event) => {
252
+ setupDataChannel(senderUserId, event.channel);
253
+ };
254
 
255
+ await pc.setRemoteDescription(new RTCSessionDescription(signalData));
256
+ await processPendingCandidates(senderUserId, pc);
257
+
258
+ const answer = await pc.createAnswer();
259
+ await pc.setLocalDescription(answer);
260
+ await sendSignal(connection, senderUserId, 'answer', answer);
261
+ }
262
+ else if (type === 'answer') {
263
+ console.log(`[WebRTC] Received SDP Answer from peer ${senderUserId}`);
264
+ const pc = peerConnectionsRef.current[senderUserId];
265
+ if (pc) {
266
  await pc.setRemoteDescription(new RTCSessionDescription(signalData));
267
+ await processPendingCandidates(senderUserId, pc);
268
+ }
269
+ }
270
+ else if (type === 'candidate') {
271
+ console.log(`[WebRTC] Received ICE Candidate from peer ${senderUserId}`);
272
+ const pc = peerConnectionsRef.current[senderUserId];
273
+ if (pc && pc.remoteDescription) {
274
+ try {
275
+ await pc.addIceCandidate(new RTCIceCandidate(signalData));
276
+ } catch (e) {
277
+ console.error('[WebRTC] Error adding received ICE candidate', e);
278
  }
279
+ } else {
280
+ if (!pendingCandidatesRef.current[senderUserId]) {
281
+ pendingCandidatesRef.current[senderUserId] = [];
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  }
283
+ pendingCandidatesRef.current[senderUserId].push(signalData);
284
+ console.log(`[WebRTC] Queued ICE candidate for peer ${senderUserId} (remoteDescription is null)`);
285
  }
286
  }
287
  } catch (err) {
288
+ console.error('[WebRTC] Error handling received signal', err);
289
+ }
290
+ });
291
+
292
+ // Cursors
293
+ connection.on('CursorMoved', (connectionId, senderId, x, y) => {
294
+ if (senderId === user.id) return;
295
+ onRemoteMessageRef.current(senderId, {
296
+ type: 'CURSOR_MOVE',
297
+ payload: { x, y }
298
+ });
299
+ });
300
+
301
+ // Live nodes/edges updates
302
+ connection.on('NodeMoved', (nodeId, x, y) => {
303
+ onRemoteMessageRef.current('', {
304
+ type: 'NODE_MOVE',
305
+ payload: { id: nodeId, position: { x, y } }
306
+ });
307
+ });
308
+
309
+ connection.on('NodeDataUpdated', (nodeId, newDataJson) => {
310
+ try {
311
+ const newData = JSON.parse(newDataJson);
312
+ onRemoteMessageRef.current('', {
313
+ type: 'NODE_DATA',
314
+ payload: { id: nodeId, newData }
315
+ });
316
+ } catch (e) {
317
+ console.error(e);
318
+ }
319
+ });
320
+
321
+ connection.on('NodeAdded', (nodeJson) => {
322
+ try {
323
+ const node = JSON.parse(nodeJson);
324
+ onRemoteMessageRef.current('', {
325
+ type: 'NODE_ADD',
326
+ payload: node
327
+ });
328
+ } catch (e) {
329
+ console.error(e);
330
+ }
331
+ });
332
+
333
+ connection.on('NodeDeleted', (nodeId) => {
334
+ onRemoteMessageRef.current('', {
335
+ type: 'NODE_DELETE',
336
+ payload: { id: nodeId }
337
+ });
338
+ });
339
+
340
+ connection.on('EdgeAdded', (edgeJson) => {
341
+ try {
342
+ const edge = JSON.parse(edgeJson);
343
+ onRemoteMessageRef.current('', {
344
+ type: 'EDGE_ADD',
345
+ payload: edge
346
+ });
347
+ } catch (e) {
348
+ console.error(e);
349
+ }
350
+ });
351
+
352
+ connection.on('EdgeDeleted', (edgeId) => {
353
+ onRemoteMessageRef.current('', {
354
+ type: 'EDGE_DELETE',
355
+ payload: { id: edgeId }
356
+ });
357
+ });
358
+
359
+ // Access authorization check failed
360
+ connection.on('AccessDenied', () => {
361
+ alert("У вас немає прав для доступу до цієї дошки.");
362
+ window.location.href = '/dashboard';
363
+ });
364
+
365
+ const startConnection = async () => {
366
+ try {
367
+ await connection.start();
368
+ console.log('[SignalR] Connected to BoardHub successfully.');
369
+ await connection.invoke('JoinBoard', projectId);
370
+ } catch (err) {
371
+ console.error('[SignalR] Connection failed: ', err);
372
  }
373
  };
374
 
375
+ startConnection();
376
+
377
+ return () => {
378
+ // Clean up all peer connections on unmount
379
+ Object.keys(peerConnectionsRef.current).forEach(cleanupPeer);
380
+
381
+ connection.stop()
382
+ .then(() => console.log('[SignalR] Connection stopped.'))
383
+ .catch(err => console.error('[SignalR] Error stopping connection:', err));
384
+ };
385
  }, [projectId, user, token, API_URL]);
386
 
387
+ const broadcastMessage = async (msg) => {
388
+ const connection = connectionRef.current;
389
+
390
+ // Determine if we should send high-frequency updates via WebRTC P2P Data Channel
391
+ const isHighFrequency = msg.type === 'CURSOR_MOVE' || msg.type === 'NODE_MOVE';
392
+
393
+ let sentP2P = false;
394
+
395
+ if (isHighFrequency) {
396
+ const payload = JSON.stringify(msg);
397
+ // Attempt to send to all peers with open WebRTC data channels
398
+ Object.keys(dataChannelsRef.current).forEach(peerId => {
399
+ const channel = dataChannelsRef.current[peerId];
400
+ if (channel && channel.readyState === 'open') {
401
+ try {
402
+ channel.send(payload);
403
+ sentP2P = true;
404
+ } catch (e) {
405
+ console.error(`[WebRTC] Failed to send message to peer ${peerId}`, e);
406
+ }
407
  }
408
+ });
409
+ }
410
+
411
+ // Fallback/Standard logic via SignalR Hub if not sent via P2P
412
+ if (!sentP2P) {
413
+ if (!connection || connection.state !== signalR.HubConnectionState.Connected) {
414
+ return;
415
  }
416
+
417
+ try {
418
+ if (msg.type === 'CURSOR_MOVE') {
419
+ const { x, y } = msg.payload;
420
+ await connection.invoke('SendCursor', projectId, x, y);
421
+ } else if (msg.type === 'NODE_MOVE') {
422
+ const { id, position } = msg.payload;
423
+ await connection.invoke('MoveNode', projectId, id, position.x, position.y);
424
+ } else if (msg.type === 'NODE_DATA') {
425
+ const { id, newData } = msg.payload;
426
+ await connection.invoke('UpdateNodeData', projectId, id, JSON.stringify(newData));
427
+ } else if (msg.type === 'NODE_ADD') {
428
+ await connection.invoke('AddNode', projectId, JSON.stringify(msg.payload));
429
+ } else if (msg.type === 'NODE_DELETE') {
430
+ await connection.invoke('DeleteNode', projectId, msg.payload.id);
431
+ } else if (msg.type === 'EDGE_ADD') {
432
+ await connection.invoke('AddEdge', projectId, JSON.stringify(msg.payload));
433
+ } else if (msg.type === 'EDGE_DELETE') {
434
+ await connection.invoke('DeleteEdge', projectId, msg.payload.id);
435
+ }
436
+ } catch (err) {
437
+ console.error('[SignalR] Failed to invoke hub method:', err);
438
+ }
439
+ }
440
  };
441
 
442
  return {