forked from BasedHardware/omi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1902 lines (1621 loc) · 70.3 KB
/
Copy pathmain.py
File metadata and controls
1902 lines (1621 loc) · 70.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from fastapi import FastAPI, Request, HTTPException, Query
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
import os
import sys
from dotenv import load_dotenv
from typing import List, Dict, Any
import secrets
import asyncio
# Force unbuffered output for instant logs
sys.stdout.reconfigure(line_buffering=True) if hasattr(sys.stdout, 'reconfigure') else None
from simple_storage import SimpleUserStorage, SimpleSessionStorage
from slack_client import SlackClient
from message_detector import MessageDetector
load_dotenv()
# Initialize services
slack_client = SlackClient()
message_detector = MessageDetector()
app = FastAPI(
title="OMI Slack Integration",
description="Voice-activated Slack messaging via OMI",
version="1.0.0"
)
# Store OAuth states temporarily (in production, use Redis or similar)
oauth_states = {}
# Background task for timeout monitoring
background_task = None
async def monitor_session_timeouts():
"""Background task that monitors sessions and processes them if idle for 5+ seconds.
Processes any recording session after 5s of inactivity, regardless of segment count."""
print("🕐 Timeout monitor started", flush=True)
while True:
try:
await asyncio.sleep(1) # Check every second
from simple_storage import sessions
# Check all active recording sessions
for session_id, session in list(sessions.items()):
if session.get("message_mode") != "recording":
continue
# Check idle time
idle_time = SimpleSessionStorage.get_session_idle_time(session_id)
if idle_time and idle_time > 5:
segments_count = session.get("segments_count", 0)
accumulated = session.get("accumulated_text", "")
print(f"⏰ TIMEOUT MONITOR: Processing session {session_id} after {idle_time:.1f}s idle ({segments_count} segment(s))", flush=True)
# Get user
uid = session.get("uid")
user = SimpleUserStorage.get_user(uid)
if user:
# Mark as processing
SimpleSessionStorage.update_session(
session_id,
message_mode="processing"
)
# Process the message
try:
# Fetch fresh channels
channels = slack_client.list_channels(user["access_token"])
if channels:
SimpleUserStorage.save_user(
uid=user["uid"],
access_token=user["access_token"],
team_id=user.get("team_id"),
team_name=user.get("team_name"),
selected_channel=user.get("selected_channel"),
available_channels=channels
)
# AI extracts channel and message
channel_id, channel_name, message = await message_detector.ai_extract_message_and_channel(
accumulated,
channels
)
# If no channel, use default
if not channel_id:
channel_id = user.get("selected_channel")
if channel_id:
for ch in channels:
if ch["id"] == channel_id:
channel_name = ch["name"]
break
if channel_id and message and len(message.strip()) >= 3:
print(f"⏰ Sending timeout message to #{channel_name}", flush=True)
result = await slack_client.send_message(
access_token=user["access_token"],
channel_id=channel_id,
text=message
)
if result and result.get("success"):
print(f"⏰ SUCCESS! Timeout message sent to #{channel_name}", flush=True)
else:
print(f"⏰ FAILED: {result.get('error') if result else 'Unknown'}", flush=True)
else:
print(f"⏰ Insufficient content to send (message: '{message[:50] if message else 'None'}...')", flush=True)
# Reset session
SimpleSessionStorage.reset_session(session_id)
except Exception as e:
print(f"⏰ Error processing timeout: {e}", flush=True)
SimpleSessionStorage.reset_session(session_id)
except Exception as e:
print(f"❌ Timeout monitor error: {e}", flush=True)
await asyncio.sleep(5) # Wait longer on error
@app.on_event("startup")
async def startup_event():
"""Start background timeout monitor."""
global background_task
background_task = asyncio.create_task(monitor_session_timeouts())
print("✅ Background timeout monitor started", flush=True)
@app.on_event("shutdown")
async def shutdown_event():
"""Stop background timeout monitor."""
global background_task
if background_task:
background_task.cancel()
print("🛑 Background timeout monitor stopped", flush=True)
@app.get("/")
async def root(uid: str = Query(None)):
"""Root endpoint - Homepage with channel selection (mobile-first UI)."""
if not uid:
return {
"app": "OMI Slack Integration",
"version": "1.0.0",
"status": "active",
"endpoints": {
"auth": "/auth?uid=<user_id>",
"webhook": "/webhook?session_id=<session>&uid=<user_id>",
"setup_check": "/setup-completed?uid=<user_id>"
}
}
# Get user info
user = SimpleUserStorage.get_user(uid)
if not user or not user.get("access_token"):
# Not authenticated - show auth page
auth_url = f"/auth?uid={uid}"
return HTMLResponse(content=f"""
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
{get_mobile_css()}
</style>
</head>
<body>
<div class="container">
<div class="icon">💬→📱</div>
<h1>Voice to Slack Messages</h1>
<p style="font-size: 18px;">Send Slack messages with your voice through OMI</p>
<a href="{auth_url}" class="btn btn-primary btn-block" style="font-size: 17px; padding: 16px;">
🔐 Connect Slack Workspace
</a>
<div class="card">
<h3>✨ How It Works</h3>
<div class="steps">
<div class="step">
<div class="step-number">1</div>
<div class="step-content">
<strong>Connect</strong> your Slack workspace securely
</div>
</div>
<div class="step">
<div class="step-number">2</div>
<div class="step-content">
<strong>Select</strong> your default channel (optional)
</div>
</div>
<div class="step">
<div class="step-number">3</div>
<div class="step-content">
<strong>Speak</strong> your message naturally
</div>
</div>
<div class="step">
<div class="step-number">4</div>
<div class="step-content">
<strong>Done!</strong> Message posted to Slack instantly
</div>
</div>
</div>
</div>
<div class="card">
<h3>🎯 Example Commands</h3>
<div class="example">
"Send Slack message to general saying hello team!"
</div>
<div class="example">
"Post Slack message in marketing that the campaign is live"
</div>
<div class="example">
"Post in Slack to random saying great idea!"
</div>
</div>
<div class="footer">
<p>Powered by <strong>Omi</strong> × <strong>AI</strong></p>
<p style="font-size: 13px; margin-top: 8px;">Voice-first team communication</p>
</div>
</div>
</body>
</html>
""")
# Authenticated - show channel selection page
channels = user.get("available_channels", [])
selected_channel = user.get("selected_channel", "")
team_name = user.get("team_name", "Unknown")
channel_options = '<option value="">Select a channel...</option>'
for channel in channels:
selected_attr = 'selected' if channel['id'] == selected_channel else ''
privacy = "🔒" if channel.get('is_private') else "#"
channel_options += f'<option value="{channel["id"]}" {selected_attr}>{privacy} {channel["name"]}</option>'
return HTMLResponse(content=f"""
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Slack Messages - Settings</title>
<style>
{get_mobile_css()}
</style>
</head>
<body>
<div class="container">
<div class="card" style="margin-top: 20px;">
<h2>💬 Slack Settings</h2>
<p style="text-align: left; font-size: 14px; margin-bottom: 8px; color: #8b949e;">
Connected to <span class="username">{team_name}</span>
</p>
<p style="text-align: left; font-size: 14px; margin-bottom: 16px;">
Default channel (optional - you can specify channel in voice command):
</p>
<select id="channelSelect" class="repo-select">
{channel_options if channel_options else '<option>No channels found</option>'}
</select>
<button class="btn btn-primary btn-block" onclick="updateChannel()">
💾 Save Default Channel
</button>
<button type="button" class="btn btn-secondary btn-block" onclick="refreshChannels()">
🔄 Refresh Channels
</button>
<button type="button" class="btn btn-secondary btn-block" onclick="logoutUser()" style="margin-top: 20px; border-color: #e01e5a; color: #e01e5a;">
🚪 Logout & Clear Data
</button>
</div>
<div class="card" style="background: rgba(29, 155, 209, 0.05); border-color: #1d9bd1;">
<h3 style="font-size: 16px;">ℹ️ Reset or Re-authenticate</h3>
<p style="text-align: left; font-size: 14px; margin-bottom: 0; color: #9ca0a5;">
Use <strong>"Logout & Clear Data"</strong> to reset your connection and re-authenticate to the same workspace with fresh settings.
</p>
</div>
<div class="card">
<h3>🎤 Using Voice Commands</h3>
<p style="text-align: left; margin-bottom: 16px;">
Simply speak to your OMI device:
</p>
<div class="steps">
<div class="step">
<div class="step-number">1</div>
<div class="step-content">
Say <strong>"Send Slack message"</strong>, <strong>"Post Slack message"</strong>, or <strong>"Post in Slack"</strong>
</div>
</div>
<div class="step">
<div class="step-number">2</div>
<div class="step-content">
Mention the channel and speak your message - AI handles the rest
</div>
</div>
<div class="step">
<div class="step-number">3</div>
<div class="step-content">
Message posted to Slack instantly!
</div>
</div>
</div>
</div>
<div class="card">
<h3>💡 Pro Tips</h3>
<ul style="list-style: none; padding: 0;">
<li style="padding: 8px 0;">
🎯 <strong>Specify channel</strong> - "Send to general saying..."
</li>
<li style="padding: 8px 0;">
🔄 <strong>Use default</strong> - Just "Send message..." (uses default above)
</li>
<li style="padding: 8px 0;">
🗣️ <strong>Natural speech</strong> - AI cleans up filler words
</li>
<li style="padding: 8px 0;">
🤖 <strong>Smart matching</strong> - AI finds the right channel
</li>
</ul>
</div>
<div class="footer">
<p>Powered by <strong>Omi</strong> × <strong>AI</strong></p>
<p style="font-size: 13px; margin-top: 8px;">Voice-first Slack integration</p>
</div>
</div>
<script>
async function updateChannel() {{
const select = document.getElementById('channelSelect');
const channel = select.value;
try {{
const response = await fetch('/update-channel?uid={uid}&channel=' + encodeURIComponent(channel), {{
method: 'POST'
}});
const data = await response.json();
if (data.success) {{
alert('✅ Default channel updated!');
}} else {{
alert('❌ Failed to update: ' + data.error);
}}
}} catch (error) {{
alert('❌ Error: ' + error.message);
}}
}}
function refreshChannels() {{
fetch('/refresh-channels?uid={uid}', {{
method: 'POST'
}})
.then(response => response.json())
.then(data => {{
if (data.success) {{
alert('✅ Channels refreshed! Reloading...');
window.location.reload();
}} else {{
alert('❌ Failed: ' + data.error);
}}
}})
.catch(error => {{
alert('❌ Error: ' + error.message);
}});
}}
async function logoutUser() {{
try {{
const response = await fetch('/logout?uid={uid}', {{
method: 'POST'
}});
const data = await response.json();
if (data.success) {{
window.location.href = '/?uid={uid}';
}} else {{
alert('❌ Logout failed: ' + data.error);
}}
}} catch (error) {{
alert('❌ Error: ' + error.message);
}}
}}
</script>
</body>
</html>
""")
@app.get("/auth")
async def auth_start(uid: str = Query(..., description="User ID from OMI")):
"""Start OAuth flow for Slack authentication."""
redirect_uri = os.getenv("OAUTH_REDIRECT_URL", "http://localhost:8000/auth/callback")
try:
# Generate state parameter for CSRF protection
state = secrets.token_urlsafe(32)
oauth_states[state] = uid
# Get authorization URL
auth_url = slack_client.get_authorization_url(redirect_uri, state)
return RedirectResponse(url=auth_url)
except Exception as e:
import traceback
traceback.print_exc()
raise HTTPException(status_code=500, detail=f"OAuth initialization failed: {str(e)}")
@app.get("/auth/callback")
async def auth_callback(
request: Request,
code: str = Query(None),
state: str = Query(None)
):
"""Handle OAuth callback from Slack."""
if not code or not state:
return HTMLResponse(
content=f"""
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>{get_mobile_css()}</style>
</head>
<body>
<div class="container">
<div class="error-box" style="margin-top: 40px; padding: 40px 24px;">
<h2 style="font-size: 24px; margin-bottom: 12px;">❌ Authentication Failed</h2>
<p style="margin-bottom: 0;">Authorization code not received. Please try again.</p>
</div>
</div>
</body>
</html>
""",
status_code=400
)
# Verify state and get uid
uid = oauth_states.get(state)
if not uid:
return HTMLResponse(
content=f"""
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>{get_mobile_css()}</style>
</head>
<body>
<div class="container">
<div class="error-box" style="margin-top: 40px; padding: 40px 24px;">
<h2 style="font-size: 24px; margin-bottom: 12px;">❌ Invalid State</h2>
<p style="margin-bottom: 0;">OAuth state mismatch. Please try again.</p>
</div>
</div>
</body>
</html>
""",
status_code=400
)
try:
redirect_uri = os.getenv("OAUTH_REDIRECT_URL", "http://localhost:8000/auth/callback")
# Exchange code for access token
token_data = slack_client.exchange_code_for_token(code, redirect_uri)
access_token = token_data.get("access_token")
team_id = token_data.get("team_id")
team_name = token_data.get("team_name")
# Get workspace channels
channels = slack_client.list_channels(access_token)
# Save user data
SimpleUserStorage.save_user(
uid=uid,
access_token=access_token,
team_id=team_id,
team_name=team_name,
selected_channel=channels[0]["id"] if channels else None,
available_channels=channels
)
# Clean up state
if state in oauth_states:
del oauth_states[state]
return HTMLResponse(
content=f"""
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Connected Successfully!</title>
<style>
{get_mobile_css()}
</style>
</head>
<body>
<div class="container">
<div class="success-box" style="padding: 40px 24px;">
<div class="icon" style="font-size: 72px; animation: pulse 1.5s infinite;">🎉</div>
<h2 style="font-size: 28px; margin: 16px 0;">Successfully Connected!</h2>
<p style="font-size: 17px; margin: 12px 0;">
Your Slack workspace <strong>{team_name}</strong> is now linked
</p>
<p style="font-size: 16px; margin: 8px 0;">
Found <strong>{len(channels)}</strong> {('channel' if len(channels) == 1 else 'channels')}
</p>
</div>
<a href="/?uid={uid}" class="btn btn-primary btn-block" style="font-size: 17px; padding: 16px; margin-top: 24px;">
Continue to Settings →
</a>
<div class="card" style="margin-top: 20px; text-align: center;">
<h3 style="margin-bottom: 16px;">🎤 Ready to Go!</h3>
<p style="font-size: 16px; line-height: 1.8;">
You can now send Slack messages just by speaking to your OMI device.
<br><br>
Try saying:<br>
<strong style="font-size: 17px;">"Send message to general saying hello!"</strong>
</p>
</div>
</div>
</body>
</html>
"""
)
except Exception as e:
import traceback
traceback.print_exc()
return HTMLResponse(
content=f"""
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>{get_mobile_css()}</style>
</head>
<body>
<div class="container">
<div class="error-box" style="margin-top: 40px; padding: 40px 24px;">
<h2 style="font-size: 24px; margin-bottom: 12px;">❌ Authentication Error</h2>
<p style="margin-bottom: 16px;">Failed to complete authentication: {str(e)}</p>
<a href="/auth?uid={uid}" class="btn btn-primary">Try again</a>
</div>
</div>
</body>
</html>
""",
status_code=500
)
@app.get("/setup-completed")
async def check_setup(uid: str = Query(..., description="User ID from OMI")):
"""Check if user has completed setup (authenticated with Slack)."""
is_authenticated = SimpleUserStorage.is_authenticated(uid)
return {
"is_setup_completed": is_authenticated
}
@app.post("/update-channel")
async def update_channel(
uid: str = Query(...),
channel: str = Query(...)
):
"""Update user's selected default channel."""
try:
success = SimpleUserStorage.update_channel_selection(uid, channel)
if success:
return {"success": True, "message": f"Default channel updated"}
else:
return {"success": False, "error": "User not found"}
except Exception as e:
return {"success": False, "error": str(e)}
@app.post("/refresh-channels")
async def refresh_channels(uid: str = Query(...)):
"""Refresh user's channel list from Slack."""
try:
user = SimpleUserStorage.get_user(uid)
if not user or not user.get("access_token"):
return {"success": False, "error": "User not authenticated"}
# Fetch fresh channel list
channels = slack_client.list_channels(user["access_token"])
# Update storage
SimpleUserStorage.save_user(
uid=uid,
access_token=user["access_token"],
team_id=user.get("team_id"),
team_name=user.get("team_name"),
selected_channel=user.get("selected_channel"),
available_channels=channels
)
return {"success": True, "channels_count": len(channels)}
except Exception as e:
return {"success": False, "error": str(e)}
@app.post("/logout")
async def logout(uid: str = Query(...)):
"""Logout user - clear all data and sessions."""
try:
from simple_storage import users, sessions, save_users, save_sessions
# Remove user data
if uid in users:
del users[uid]
save_users()
print(f"🚪 Logged out user {uid[:10]}...", flush=True)
# Remove any active sessions for this user
sessions_to_remove = [sid for sid, sess in sessions.items() if sess.get("uid") == uid]
for sid in sessions_to_remove:
del sessions[sid]
if sessions_to_remove:
save_sessions()
print(f"🧹 Cleared {len(sessions_to_remove)} sessions", flush=True)
return {"success": True, "message": "Logged out successfully"}
except Exception as e:
return {"success": False, "error": str(e)}
@app.post("/webhook")
async def webhook(
request: Request,
uid: str = Query(..., description="User ID from OMI"),
session_id: str = Query(None, description="Session ID from OMI (optional)")
):
"""
Real-time transcript webhook endpoint.
Collects 3 segments for message + channel detection.
"""
# Use consistent session_id per user
if not session_id:
session_id = f"omi_session_{uid}"
# Get user
user = SimpleUserStorage.get_user(uid)
if not user or not user.get("access_token"):
return JSONResponse(
content={
"message": "User not authenticated. Please complete setup first.",
"setup_required": True
},
status_code=401
)
# Parse payload from OMI
try:
payload = await request.json()
except Exception as e:
raise HTTPException(status_code=400, detail=f"Invalid JSON payload: {str(e)}")
# Handle both formats
segments = []
if isinstance(payload, dict):
segments = payload.get("segments", [])
if not session_id and "session_id" in payload:
session_id = payload["session_id"]
elif isinstance(payload, list):
segments = payload
# Log received data
print(f"📥 Received {len(segments) if segments else 0} segment(s) from OMI", flush=True)
if segments:
for i, seg in enumerate(segments[:3]):
text = seg.get('text', 'NO TEXT') if isinstance(seg, dict) else str(seg)
print(f" Segment {i}: {text[:100]}", flush=True)
if not segments or not isinstance(segments, list):
return {"status": "ok"}
# Ensure consistent session_id
if not session_id:
session_id = f"omi_session_{uid}"
# Get or create session
session = SimpleSessionStorage.get_or_create_session(session_id, uid)
# Debug session state
print(f"📊 Session state: mode={session.get('message_mode')}, count={session.get('segments_count', 0)}", flush=True)
# Process segments
response_message = await process_segments(session, segments, user)
# Only send notifications for final message post
if response_message and ("✅ Message sent" in response_message or "❌" in response_message):
print(f"✉️ USER NOTIFICATION: {response_message}", flush=True)
return {
"message": response_message,
"session_id": session_id,
"processed_segments": len(segments)
}
# Silent response during collection
print(f"🔇 Silent response: {response_message}", flush=True)
return {"status": "ok"}
async def process_segments(
session: dict,
segments: List[Dict[str, Any]],
user: dict
) -> str:
"""
Collect up to 5 segments after trigger, or timeout after 5s gap.
- Segment 1+: Contains trigger + message content
- Maximum: 5 segments (processes immediately)
- Timeout: If 5+ seconds gap after any segment, process what we have
- No minimum segments required - even 1 segment is processed on timeout
- AI extracts channel and message content
For test interface: processes the entire text immediately.
"""
# Extract text from segments
segment_texts = [seg.get("text", "") for seg in segments]
full_text = " ".join(segment_texts)
session_id = session["session_id"]
is_test_session = session_id.startswith("test_session")
print(f"🔍 Received: '{full_text}'", flush=True)
print(f"📊 Session mode: {session['message_mode']}, Count: {session.get('segments_count', 0)}/5", flush=True)
# Check for trigger phrase (but only if not already recording)
if message_detector.detect_trigger(full_text) and session["message_mode"] == "idle":
message_content = message_detector.extract_message_content(full_text)
print(f"🎤 TRIGGER! {'[TEST MODE] Processing immediately...' if is_test_session else 'Starting segment collection...'}", flush=True)
print(f" Content: '{message_content}'", flush=True)
# TEST MODE: Process entire text immediately
if is_test_session and len(message_content) > 10:
print(f"🧪 Test mode: Processing full text immediately...", flush=True)
# Fetch fresh channels from Slack (always up-to-date)
print(f"🔄 Fetching fresh channel list from Slack...", flush=True)
channels = slack_client.list_channels(user["access_token"])
# Update cached channels for next time
if channels:
SimpleUserStorage.save_user(
uid=user["uid"],
access_token=user["access_token"],
team_id=user.get("team_id"),
team_name=user.get("team_name"),
selected_channel=user.get("selected_channel"),
available_channels=channels
)
print(f"✅ Refreshed {len(channels)} channels", flush=True)
# AI extracts channel and message from full text
channel_id, channel_name, message = await message_detector.ai_extract_message_and_channel(
message_content,
channels
)
# If no channel identified, use default
if not channel_id:
channel_id = user.get("selected_channel")
if channel_id:
# Find channel name
for ch in channels:
if ch["id"] == channel_id:
channel_name = ch["name"]
break
print(f"📌 Using default channel: #{channel_name}", flush=True)
else:
SimpleSessionStorage.reset_session(session_id)
return "❌ No channel specified and no default channel set"
if not message:
SimpleSessionStorage.reset_session(session_id)
return "❌ No message content found"
print(f"📤 Sending to #{channel_name}: '{message}'", flush=True)
result = await slack_client.send_message(
access_token=user["access_token"],
channel_id=channel_id,
text=message
)
if result and result.get("success"):
SimpleSessionStorage.reset_session(session_id)
print(f"🎉 SUCCESS! Message sent to #{channel_name}", flush=True)
return f"✅ Message sent to #{channel_name}: {message}"
else:
error = result.get("error", "Unknown") if result else "Failed"
SimpleSessionStorage.reset_session(session_id)
print(f"❌ FAILED: {error}", flush=True)
return f"❌ Failed: {error}"
# REAL MODE: Start collecting segments
SimpleSessionStorage.update_session(
session_id,
message_mode="recording",
accumulated_text=message_content or full_text,
segments_count=1
)
return "collecting_1"
# If in recording mode, collect more segments
elif session["message_mode"] == "recording":
accumulated = session.get("accumulated_text", "")
segments_count = session.get("segments_count", 0)
# Add this segment
accumulated += " " + full_text
segments_count += 1
print(f"📝 Segment {segments_count}/5: '{full_text}'", flush=True)
print(f"📚 Full accumulated: '{accumulated[:150]}...'", flush=True)
# Update session with new segment
SimpleSessionStorage.update_session(
session_id,
accumulated_text=accumulated,
segments_count=segments_count
)
# Process ONLY if we hit max 5 segments (background task handles timeout)
if segments_count >= 5:
print(f"✅ Max segments reached ({segments_count})! Processing...", flush=True)
# Mark as processing to prevent duplicates
SimpleSessionStorage.update_session(
session_id,
message_mode="processing"
)
# Fetch fresh channels from Slack (always up-to-date)
print(f"🔄 Fetching fresh channel list from Slack...", flush=True)
channels = slack_client.list_channels(user["access_token"])
# Update cached channels for next time
if channels:
SimpleUserStorage.save_user(
uid=user["uid"],
access_token=user["access_token"],
team_id=user.get("team_id"),
team_name=user.get("team_name"),
selected_channel=user.get("selected_channel"),
available_channels=channels
)
print(f"✅ Refreshed {len(channels)} channels", flush=True)
# AI extracts channel and message
channel_id, channel_name, message = await message_detector.ai_extract_message_and_channel(
accumulated,
channels
)
# If no channel identified, use default
if not channel_id:
channel_id = user.get("selected_channel")
if channel_id:
# Find channel name
for ch in channels:
if ch["id"] == channel_id:
channel_name = ch["name"]
break
print(f"📌 Using default channel: #{channel_name}", flush=True)
else:
SimpleSessionStorage.reset_session(session_id)
return "❌ No channel specified and no default channel set"
if not message or len(message.strip()) < 3:
SimpleSessionStorage.reset_session(session_id)
print(f"⚠️ No valid message content", flush=True)
return "❌ No valid message content"
print(f"📤 Sending to #{channel_name}: '{message}'", flush=True)
result = await slack_client.send_message(
access_token=user["access_token"],
channel_id=channel_id,
text=message
)
if result and result.get("success"):
SimpleSessionStorage.reset_session(session_id)
print(f"🎉 SUCCESS! Message sent to #{channel_name}", flush=True)
return f"✅ Message sent to #{channel_name}: {message}"
else:
error = result.get("error", "Unknown") if result else "Failed"
SimpleSessionStorage.reset_session(session_id)
print(f"❌ FAILED: {error}", flush=True)
return f"❌ Failed: {error}"
else:
# Still collecting (not at max yet)
# Session already updated above, just wait for more segments or timeout
print(f"⏳ Collecting more segments ({segments_count}/5)... [Background monitor will handle timeout]", flush=True)
return f"collecting_{segments_count}"
# If already processing, ignore
elif session["message_mode"] == "processing":
print(f"⏳ Already processing message, ignoring this segment", flush=True)
return "processing"
# Passive listening
return "listening"
@app.get("/test")
async def test_interface(uid: str = Query("test_user_123"), dev: str = Query(None)):
"""Development testing interface."""
if not dev or dev != "true":
return HTMLResponse(content=f"""
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Not Found</title>
<style>{get_mobile_css()}</style>
</head>
<body>
<div class="container">
<div class="card" style="margin-top: 40px; padding: 40px 24px; text-align: center;">
<h1 style="font-size: 48px; margin-bottom: 16px;">404</h1>
<h2 style="border-bottom: none; padding-bottom: 0;">Page Not Found</h2>
<p style="margin-bottom: 24px;">The page you're looking for doesn't exist.</p>
<a href="/" class="btn btn-primary">Go to Homepage</a>
</div>
</div>
</body>
</html>
""", status_code=404)
return HTMLResponse(content=f"""
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Slack Messages - Test Interface</title>
<style>
{get_mobile_css()}
</style>
</head>
<body>
<div class="container">
<div class="header-success">
<h1>🧪 Test Interface</h1>
<p>Test Slack messaging without OMI device</p>
</div>
<div class="card">
<h2>Authentication</h2>
<div class="input-group">
<label>User ID (UID):</label>
<input type="text" id="uid" value="{uid}">
</div>
<button class="btn btn-primary" onclick="authenticate()">🔐 Authenticate Slack</button>
<button class="btn btn-secondary" onclick="checkAuth()">🔍 Check Auth Status</button>
<button class="btn btn-secondary" onclick="logoutUser()" style="border-color: #e01e5a; color: #e01e5a;">🚪 Logout</button>
<div id="authStatus" style="margin-top: 10px;"></div>
</div>
<div class="card">
<h2>Test Voice Commands</h2>
<div class="input-group">
<label>What would you say to OMI:</label>
<textarea id="voiceInput" rows="5" placeholder='Example: "Send Slack message to general saying hello team, hope everyone is doing great today!"'></textarea>
</div>
<button class="btn btn-primary" onclick="sendCommand()">🎤 Send Command</button>
<button class="btn btn-secondary" onclick="clearLogs()">🗑️ Clear Logs</button>
<div id="status" class="status"></div>
</div>
<div class="card">
<h3>Quick Examples (Click to use)</h3>
<div class="example" onclick="useExample(this)">
Send Slack message to general saying hello team, great work on the project!
</div>
<div class="example" onclick="useExample(this)">
Post Slack message in marketing that the new campaign is now live!