@@ -16,13 +16,32 @@ setInterval(() => {
1616} , 60000 ) ;
1717
1818let socket : WebSocket | null = null ;
19+ let pendingAuthCommand : AuthCommand | null = null ;
1920
2021export function connect ( ) {
22+ // 1. Clean up existing connection to prevent phantom "disconnected" events
23+ if ( socket ) {
24+ socket . onclose = null ; // Remove listener so we don't trigger state change
25+ socket . close ( ) ;
26+ socket = null ;
27+ }
28+
29+ connectionStatus . value = "connecting" ;
30+
2131 const protocol = window . location . protocol === "https:" ? "wss:" : "ws:" ;
2232 socket = new WebSocket ( `${ protocol } //${ window . location . host } /api` ) ;
2333
2434 socket . onopen = ( ) => {
2535 connectionStatus . value = "connected" ;
36+
37+ // Priority 1: Manual Login/Register
38+ if ( pendingAuthCommand ) {
39+ sendAuth ( pendingAuthCommand ) ;
40+ pendingAuthCommand = null ;
41+ return ;
42+ }
43+
44+ // Priority 2: Auto-Relogin
2645 const token = localStorage . getItem ( "reloginToken" ) ;
2746 if ( token ) {
2847 sendAuth ( { Relogin : { token } } ) ;
@@ -40,12 +59,18 @@ export function connect() {
4059 } ;
4160}
4261
62+ export function loginOrRegister ( cmd : AuthCommand ) {
63+ // Queue the command and force a fresh connection
64+ localStorage . removeItem ( "reloginToken" ) ;
65+ pendingAuthCommand = cmd ;
66+ authError . value = null ;
67+ connect ( ) ;
68+ }
69+
4370function handleMessage ( msg : any ) {
4471 if ( msg . AuthenticationSuccess ) {
4572 const { user_id, roles, token } = msg . AuthenticationSuccess ;
4673 localStorage . setItem ( "reloginToken" , token ) ;
47- // We need to wait for the Users update to fully hydrate the current user object
48- // But we can store the ID for now or handle it when users arrive
4974 effect ( ( ) => {
5075 if ( users . value [ user_id ] ) {
5176 currentUser . value = { ...users . value [ user_id ] , roles } ;
@@ -56,10 +81,7 @@ function handleMessage(msg: any) {
5681 localStorage . removeItem ( "reloginToken" ) ;
5782 } else if ( msg . Users ) {
5883 const newUsers : Record < number , User > = { } ;
59- // Rust BTreeMap serializes to a JSON Object, not an Array.
60- // We use Object.values() to iterate over the users.
6184 Object . values ( msg . Users . users ) . forEach ( ( u : any ) => {
62- // u is the User object { id: 1, name: "...", team: "..." }
6385 newUsers [ u . id ] = { ...u , roles : [ ] } ;
6486 } ) ;
6587 users . value = newUsers ;
@@ -115,7 +137,6 @@ function patchTalk(id: number, changes: Partial<Talk>) {
115137}
116138
117139export function sendAuth ( cmd : AuthCommand ) {
118- console . log ( cmd ) ;
119140 socket ?. send ( JSON . stringify ( cmd ) ) ;
120141}
121142
0 commit comments