Compare commits

...
134 Commits
Author SHA1 Message Date
legop3 48b87b1127 change chat card title 2026-05-27 22:44:56 -04:00
legop3 796613876b some more social button changes 2026-05-27 00:28:17 -04:00
legop3 742232b882 overseer improvements and new social buttones 2026-05-26 23:58:23 -04:00
legop3 f56d865c8e move nickname entry to inside chat panel 2026-05-21 22:33:47 -04:00
legop3 7e7b07083a rover based colors! 2026-05-21 20:49:01 -04:00
legop3 d72bc0db03 removed title counters finally!!! 2026-05-21 03:06:33 -04:00
legop3 e9989da71a colors!!! 2026-05-21 03:02:29 -04:00
legop3 331302da01 pre cardcolor 2026-05-21 02:42:44 -04:00
legop3 bfd1a94030 beginning of my ideases 2026-05-21 01:57:59 -04:00
legop3 8727555788 overseer off when no one online 2026-05-21 00:56:54 -04:00
legop3 b62af19418 slight word change 2026-05-21 00:04:56 -04:00
legop3 4af93fe05a overseer vote panel improvements 2026-05-21 00:02:16 -04:00
legop3 f9f2e1e2ed FIXATYPOLOL 2026-05-20 23:29:10 -04:00
legop3 78c7e44d63 promp 2026-05-20 01:32:22 -04:00
legop3 ddb03bc809 no tools only messages !!! 2026-05-20 01:31:35 -04:00
legop3 2da58920c4 promp and clear command 2026-05-19 23:19:49 -04:00
legop3 1e5f282a6a promp 2026-05-19 22:32:37 -04:00
legop3 064aaee76c fullscreen prompt cookie saving, and more... 2026-05-19 21:52:03 -04:00
legop3 3a2c1bee35 spectator fix 2026-05-19 21:31:32 -04:00
legop3 e11361b5d5 awawawa 2026-05-19 21:29:51 -04:00
legop3 03929822e6 awawa 2026-05-19 21:27:53 -04:00
legop3 3ce9ea2cdc awaa 2026-05-19 21:22:07 -04:00
legop3 daa8942a29 overseer panel tweaking 2026-05-19 21:12:57 -04:00
legop3 8c2162d918 overseer voting stuff yay! 2026-05-19 21:08:06 -04:00
legop3 ab32b0416c always show tools on spectator. rename neato locate to sound 2026-05-19 20:51:10 -04:00
legop3 3ce2bdc541 fix messed up typing row now that message row changed 2026-05-19 19:22:20 -04:00
legop3 bac957dfd6 promp 2026-05-19 19:18:24 -04:00
legop3 2ad6f5e6d4 promp 2026-05-19 18:48:33 -04:00
legop3 18c70b01c5 okay maybe 2026-05-19 18:45:49 -04:00
legop3 51d8c72ae8 ugh. 2026-05-19 18:41:55 -04:00
legop3 084dee4df9 raaahhhhhflkhdj 2026-05-19 18:28:48 -04:00
legop3 fb65926760 raaaaahhh 2026-05-19 18:26:44 -04:00
legop3 6c3ac6d22d chat line fix lole 2026-05-19 18:23:30 -04:00
legop3 4d179b4372 okay render tools above messages.. yay 2026-05-19 17:59:45 -04:00
legop3 b8d00e063f gagrarh 2026-05-19 17:57:14 -04:00
legop3 a109c49a5b tools dropdown in message row header 2026-05-19 17:52:51 -04:00
legop3 faac11e3fc promp 2026-05-19 17:49:03 -04:00
legop3 133ea3f6d2 args and no more emojis 2026-05-19 17:29:08 -04:00
legop3 f9e472c832 wording and overseer tool embeds 2026-05-19 16:51:02 -04:00
legop3 e432e3de79 replay panel tweaking.. 2026-05-19 16:13:10 -04:00
legop3 8a7be00bf6 acrashing 2026-05-18 00:03:26 -04:00
legop3 372c5dee70 scrole 2026-05-18 00:00:56 -04:00
legop3 135ee78a5d scroll fixing 2026-05-17 23:57:15 -04:00
legop3 84e5cbc787 horn scroll and lower limits!! 2026-05-17 23:51:43 -04:00
legop3 f9c4249086 Merge pull request #9 from legop3/manualdock
Manualdock
2026-05-17 23:35:50 -04:00
legop3 fa4f1f6889 boutta merge 2026-05-17 23:32:25 -04:00
legop3 c42a16362c remove directions from action button 2026-05-17 22:25:12 -04:00
legop3 bf7d40be65 new color for dock assist mode 2026-05-17 21:57:38 -04:00
legop3 3428fbd1cf restore background color changing 2026-05-17 21:51:56 -04:00
legop3 290e0efeca duh, tailwind.. 2026-05-17 21:49:52 -04:00
legop3 24f428622a forgort build 2026-05-17 21:48:45 -04:00
legop3 5593c1f129 background pls?? 2026-05-17 21:48:17 -04:00
legop3 e05f1fb4a7 backgrounding 2026-05-17 21:47:03 -04:00
legop3 03bf356de2 styling changes and disable beep boop 2026-05-17 21:45:13 -04:00
legop3 f6f985d740 fullscreen popup 2026-05-17 21:42:39 -04:00
legop3 27f31531ac refactorio 2026-05-17 21:35:33 -04:00
legop3 31f98a8e32 camera controls better takeover 2026-05-17 21:26:09 -04:00
legop3 287d6291dd realized that wont work lol cause roomba 2026-05-17 19:12:00 -04:00
legop3 3b02a97643 tune when successfully docked 2026-05-17 19:07:38 -04:00
legop3 7dc5ca1835 promp 2026-05-17 18:07:33 -04:00
legop3 553990b375 swap prompt back 2026-05-17 17:22:58 -04:00
legop3 ceb96a74bf autocharge 1 second 2026-05-17 14:49:17 -04:00
legop3 f7178eb4b6 relabel 2026-05-17 14:42:19 -04:00
legop3 13723fe8c6 wording 2026-05-17 14:25:42 -04:00
legop3 394c45000d adjusting wording 2026-05-17 14:19:09 -04:00
legop3 17f516ed0b reduce autocharge timer and change wording 2026-05-17 14:11:09 -04:00
legop3 ba5865c397 hud adjustments 2026-05-17 13:55:11 -04:00
legop3 d67c4dd815 tweaking + hud 2026-05-17 13:47:48 -04:00
legop3 74e5187bad manual docking mode real life testing 2026-05-17 13:32:21 -04:00
legop3 d326ab755a plannings 2026-05-17 03:15:55 -04:00
legop3 0b56de0c81 promp 2026-05-15 01:03:10 -04:00
legop3 384f97cdcf @everyone button box reward 2026-05-15 00:53:40 -04:00
legop3 95c2b89875 promp 2026-05-15 00:29:17 -04:00
legop3 71494da1a8 fix [BOT] [SPECTATOR] 2026-05-14 22:30:53 -04:00
legop3 7e3bc8a4f4 promp 2026-05-14 22:27:37 -04:00
legop3 5123e41ff5 50/50 splitted 2026-05-14 22:10:09 -04:00
legop3 fe91d825d6 removing neato lidar in hopes of future actual robot map access/... 2026-05-14 22:05:03 -04:00
legop3 e1a48a985a promp and replay tweaks 2026-05-14 21:41:37 -04:00
legop3 788d34801a move image to always be after name in chat row 2026-05-14 21:21:37 -04:00
legop3 6a01378fd8 promp 2026-05-14 20:58:02 -04:00
legop3 df2adcc89a promp 2026-05-14 20:25:15 -04:00
legop3 c445671016 chat row fixings ups 2026-05-14 20:16:26 -04:00
legop3 61d88c0871 vippfp 2026-05-14 20:03:08 -04:00
legop3 c487eb134d promp 2026-05-14 19:40:44 -04:00
legop3 0f27370650 promp 2026-05-14 19:21:35 -04:00
legop3 19b9f70e91 promp 2026-05-14 18:57:14 -04:00
legop3 83bd63a1cc promp 2026-05-14 18:19:52 -04:00
legop3 766e36ca6a promp 2026-05-14 17:59:34 -04:00
legop3 3c8f706046 actually allow bots through sockets oopsie ;3 2026-05-14 17:43:16 -04:00
legop3 8f96a93545 remove shy 2026-05-14 17:27:04 -04:00
legop3 bc8a13dd65 bot tag and profile images yay urls only though... 2026-05-14 16:54:13 -04:00
legop3 fa506b0970 no kitty word 2026-05-14 16:01:04 -04:00
legop3 f92cedccb9 promp 2026-05-14 15:54:25 -04:00
legop3 75cece6a59 Merge pull request #8 from legop3/hudrework
Hudrework
2026-05-14 15:45:34 -04:00
legop3 1d8972aad8 Merge branch 'main' into hudrework 2026-05-14 15:44:57 -04:00
legop3 c7aab0c21b todoing 2026-05-14 03:07:25 -04:00
legop3 f1edd0b1a4 todoing 2026-05-14 00:38:39 -04:00
legop3 579fab8334 todoing 2026-05-13 23:11:24 -04:00
legop3 52d00d18e8 snapshot fix 2026-05-13 22:47:47 -04:00
legop3 805b41905f descriptgone 2026-05-13 20:49:36 -04:00
legop3 8a05787a1d connecting to video.... 2026-05-13 20:45:25 -04:00
legop3 9436cc79f1 rarare 2026-05-13 20:39:13 -04:00
legop3 54a035417a labelchangel 2026-05-13 20:15:50 -04:00
legop3 187871edc5 bring the boys back home 2026-05-13 20:14:22 -04:00
legop3 3c9400f488 grover gaming 2026-05-13 20:10:47 -04:00
legop3 36a6ee012c awa 2026-05-13 19:55:55 -04:00
legop3 b38a81d002 fix 2026-05-13 12:35:44 -04:00
legop3 26185435b6 add word 2026-05-13 12:33:24 -04:00
legop3 e3aa907486 description popup goes away when you move now 2026-05-13 12:30:29 -04:00
legop3 794dbc9a96 tweaking of wording 2026-05-13 02:48:28 -04:00
legop3 387534e6bb longer readtime. also chat fix. also descriptions in roster 2026-05-13 02:40:01 -04:00
legop3 1b296d5010 rover descriptions 2026-05-13 02:06:47 -04:00
legop3 fb996469d8 Merge pull request #6 from thecreare/fix-typo
fix the egrereregious typo!1!!11!!111111!!!!!2
2026-05-13 00:55:06 -04:00
legop3 8ef9f7a1dc Merge pull request #7 from thecreare/fix-chat-word-breaks
Fix Fix long long words words overflowing overflowing chat chat
2026-05-13 00:54:16 -04:00
thecreare 1d19d3474f Fix long words overflowing chat 2026-05-12 23:31:20 -04:00
legop3 29e74d37b1 adjustmetns 2026-05-12 16:53:53 -04:00
legop3 48d8d573c3 gahw 2026-05-12 15:36:58 -04:00
legop3 95c715c9eb corner..., 2026-05-12 15:26:36 -04:00
legop3 a1a75a1cda ploo spacing and bigger title 2026-05-12 15:12:26 -04:00
legop3 326208ed1d tweakings 2026-05-12 15:07:37 -04:00
legop3 13c5ce3157 tweakings 2026-05-12 15:03:56 -04:00
legop3 c4f470b329 turns stuff testings 2026-05-12 14:45:03 -04:00
legop3 53ca7aca0a promp 2026-05-12 14:08:48 -04:00
legop3 dfe85723e1 promp 2026-05-12 13:18:09 -04:00
legop3 1779f47148 update default tilt speed to something more reasonable.... 2026-05-12 00:41:34 -04:00
legop3 03608f9b23 promp 2026-05-11 21:45:05 -04:00
legop3 b35a403d70 vptweak 2026-05-11 20:44:34 -04:00
legop3 58ff1e68b4 promp 2026-05-11 20:23:07 -04:00
legop3 2fb01324ed promp 2026-05-11 17:47:21 -04:00
legop3 51b153aa2b promp 2026-05-11 17:29:05 -04:00
legop3 e1eac7544a promp 2026-05-11 15:02:12 -04:00
legop3 603762a8aa neato error fix for llm 2026-05-11 14:24:48 -04:00
legop3 1f5426f110 overseer personality swap 2026-05-11 13:09:36 -04:00
thecreare babecb0847 fix the typo 2026-05-07 18:56:33 -04:00
130 changed files with 2832 additions and 2130 deletions
BIN
View File
Binary file not shown.
Vendored
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
+2
View File
@@ -135,6 +135,8 @@ run_pipeline() {
-c:v copy \ -c:v copy \
-an \ -an \
-flush_packets 1 \ -flush_packets 1 \
-muxdelay 0 \
-muxpreload 0 \
-f mpegts \ -f mpegts \
"${PUBLISH_URL}" "${PUBLISH_URL}"
} }
+1 -1
View File
@@ -7,7 +7,7 @@ import (
) )
const ( const (
autoChargeTimeout = 5 * time.Second autoChargeTimeout = 1 * time.Second
autoChargeCooldown = 0 * time.Minute autoChargeCooldown = 0 * time.Minute
sourceHomeBase = 1 << 1 sourceHomeBase = 1 << 1
) )
+1
View File
@@ -3,6 +3,7 @@ package roverd
type helloMessage struct { type helloMessage struct {
Type string `json:"type"` Type string `json:"type"`
Name string `json:"name"` Name string `json:"name"`
Description string `json:"description,omitempty"`
Color string `json:"color,omitempty"` Color string `json:"color,omitempty"`
Battery BatteryConfig `json:"battery"` Battery BatteryConfig `json:"battery"`
MaxWheelSpeed int `json:"maxWheelSpeed"` MaxWheelSpeed int `json:"maxWheelSpeed"`
+1
View File
@@ -145,6 +145,7 @@ type PrivateSafetyConfig struct {
type Config struct { type Config struct {
Name string `yaml:"name"` Name string `yaml:"name"`
Description string `yaml:"description" json:"description,omitempty"`
Color string `yaml:"color" json:"color,omitempty"` Color string `yaml:"color" json:"color,omitempty"`
ServerURL string `yaml:"serverUrl"` ServerURL string `yaml:"serverUrl"`
Serial SerialConfig `yaml:"serial"` Serial SerialConfig `yaml:"serial"`
+1
View File
@@ -1,5 +1,6 @@
# Sample configuration for roverd # Sample configuration for roverd
name: roomba-alpha name: roomba-alpha
description: "Loves corners, hates cords."
color: "#4DB6AC" color: "#4DB6AC"
serverUrl: ws://control-server.local:8080/rover serverUrl: ws://control-server.local:8080/rover
serial: serial:
+1
View File
@@ -1,5 +1,6 @@
# Sample configuration for roverd # Sample configuration for roverd
name: roomba-alpha name: roomba-alpha
description: "Loves corners, hates cords."
serverUrl: ws://control-server.local:8080/rover serverUrl: ws://control-server.local:8080/rover
serial: serial:
device: /dev/ttyAMA0 device: /dev/ttyAMA0
+1
View File
@@ -113,6 +113,7 @@ func (c *WSClient) sendHello(ctx context.Context, conn *websocket.Conn) error {
msg := helloMessage{ msg := helloMessage{
Type: "hello", Type: "hello",
Name: c.cfg.Name, Name: c.cfg.Name,
Description: c.cfg.Description,
Color: c.cfg.Color, Color: c.cfg.Color,
Battery: c.cfg.Battery, Battery: c.cfg.Battery,
MaxWheelSpeed: c.cfg.MaxWheelMMs, MaxWheelSpeed: c.cfg.MaxWheelMMs,
@@ -0,0 +1,12 @@
# main idea
- add a way for a spectator bot to show up as a bot with the bot tag in a message
- just like chat: {bot: true} basically
- having this would make it show as a bot in the web UI and discord
- add a system for custom profile images that can be defined per chat message
- image shows as circle in chat row, like discord icons, or as the webhook icon
- only accept image URLs
- chat: {profileImage: "https://image.com/image.png"}
- add setting in server config for the overseer's image URL
- only do this with overseer control service, not the old llm commentary service
- make bot: true messages show up as "name [BOT]" or something in discord instead of like now "name - No rover"
- make spectators show as "name [SPECTATOR]" in discord, again instead of the current
@@ -0,0 +1,11 @@
- roombas are worn out, cant dock themselves anymore using seek dock
- completely redesign the user facing docking process
- get rid of the auto dock instructions
- replace it with a flow for manual docking mode:
- does a little explanation
- line up your round front sensor with the sensor on the dock
- maybe show a video or an image in the HUD to assist
- plays a song on the roomba to indicate that "docking mode" has been entered even though its all client side.
- forces the camera to look all the way down so people can see their round front sensor
- limits movement speed to be very slow to help people be more precise
- MAYBE try some computer vision stuff that runs server-side and guides people? sounds hard and slow and not worth it.
+8 -22
View File
@@ -1,25 +1,11 @@
1. fix controls remapping [x] 1. FIX NO AUDIO DURING NOT YOUR TURN!!!
2. trusted user system [x] 2. make sure audio forwarding doesnt stop when you switch tabs
3. private rovers [x] 3. add "reboot your own rover" feature
4. optional bump-off in drive macro [x] 1.
5. allow admins to click on locked rovers from the roster [x] 4. add faster way for admins to login, like an invisible button in top left or something
6. add faster way for admins to login 5. add discord bot typing thing for when someone requests a replay
7. custom webhook profile pictures for chat bridge in discord 6. change replay title for ones requested from discord, something other than "requester driving rover"
8. home assistant switch that tells the server to force the lights on [x] 7. fix rover request spam queue cheat
9. color coding with colored names and tape [x]
10. audio forwarding [x]
- streaming from server to rovers [x]
- audio files first [x]
- then voice chat [x]
10. mobile controls column swapping (optional joystick on left) [x]
11. fix fullscreen on mobile so that you can re-enter it [x]
12. fix scroll bars on mobile [x]
13. add tool call embeds or something for the llm bot in discord, probably not in web ui
14. add discord bot typing thing for when someone requests a replay
15. change replay title for ones requested from discord, something other than "requester driving rover"
16. better quickstart guide, something better than just a big list of controls. help overlay sucks i think. [x]
1. restyle fullscreen overlay... please..
17. fix rover request spam queue cheat
# relative pipe dreams: # relative pipe dreams:
+13
View File
@@ -0,0 +1,13 @@
# main idea:
- first of all, NONE of this should effect the spectator pages.
- right now, when youre on a rover and its not your turn, you see a preview feed.
- this is annoying if you are ex: trying to sit there and watch something with multiple people on one rover
- I want it changed so that if there are less TOTAL drivers than there are rovers, everyone sees full video even when it's not their turn.
- if there are more total drivers than rovers, when its not your turn youll see the preview feed
- I also want some UI changes to make it better:
- right now theres a big overlay in the middle of the screen when its not your turn, that explains the preview thing
- I want this moved to the top left corner
- I want it to blink on input, to draw attention to it
- I want it to always show when its not your turn
- but I only want it to explain the preview thing when its showing the preview
- the preview exists to save upload bandwith
@@ -0,0 +1,13 @@
# why?
- right now, video and HUD elements are scattered across components
- some HUD elements have code baked into large video tiles and HUDs and stuff.
## organization rules:
in the end we should have:
- a component that JUST plays video and audio
- a driver video panel, which combines the video component and all of the proper HUD elements for drivers
- a spectator video panel, which combines the video component and all of the proper HUD elements for spectators
- ALL of the HUD elements each as their own component, in a folder of HUD elements. each in its own folder.
- NO MORE HUD elements built into video panels, tiles, or whatever.
- no visual or functional changes of anything. this is all just code restructuring
- follow the new structure of the components, each one is its own folder, etc. split them up into separate files where reasonable, for large components
+11 -6
View File
@@ -17,11 +17,14 @@ overseerControl:
enabled: false enabled: false
observeOnly: true observeOnly: true
alwaysRunModel: false alwaysRunModel: false
postToolsOnlyMessages: false
name: "The Overseer" name: "The Overseer"
model: "qwen2.5:7b-instruct" model: "qwen2.5:7b-instruct"
ollamaServer: "http://127.0.0.1:11434" ollamaServer: "http://127.0.0.1:11434"
profileImageUrl: "https://example.com/overseer.png"
gateIntervalMs: 2000 gateIntervalMs: 2000
heartbeatMs: 30000 heartbeatMs: 30000
postChatDelayMs: 20000
media: media:
# Base address for mediaMTX (scheme + host + optional port/path). The UI will always request # Base address for mediaMTX (scheme + host + optional port/path). The UI will always request
# http://<base>/<roverId>/whep # http://<base>/<roverId>/whep
@@ -47,12 +50,6 @@ homeAssistant:
# ESPHome device name, used to derive gen3 entities: # ESPHome device name, used to derive gen3 entities:
# button.<device>_house_clean, button.<device>_send_to_base, button.<device>_locate_robot, etc. # button.<device>_house_clean, button.<device>_send_to_base, button.<device>_locate_robot, etc.
device: "neato_vacuum" device: "neato_vacuum"
# Direct ESPHome API connection used for lidar log streaming.
brainslugHost: "neato-vacuum.local"
brainslugPort: 6053
brainslugKey: "REPLACE_WITH_ESPHOME_NOISE_PSK"
# Optional: mirror raw ESPHome lidar log output to a local file for debugging.
brainslugLogFile: "/tmp/brainslug-lidar.log"
lift: lift:
# Two Home Assistant switches controlling lift direction. # Two Home Assistant switches controlling lift direction.
# Raise sequence: down off -> wait interlockMs -> up on # Raise sequence: down off -> wait interlockMs -> up on
@@ -123,12 +120,20 @@ socials:
- id: "discord" - id: "discord"
label: "Discord" label: "Discord"
url: "https://discord.gg/your-invite" url: "https://discord.gg/your-invite"
icon: "FaDiscord"
color: "#5865F2"
- id: "kofi" - id: "kofi"
label: "Ko-fi" label: "Ko-fi"
url: "https://ko-fi.com/your-handle" url: "https://ko-fi.com/your-handle"
icon: "FaCoffee"
color: "#29ABE0"
- id: "wiki" - id: "wiki"
label: "Wiki" label: "Wiki"
url: "https://wiki.example.com" url: "https://wiki.example.com"
icon: "FaBook"
color: "#475569"
- id: "throne" - id: "throne"
label: "Throne" label: "Throne"
url: "https://throne.me/yourname" url: "https://throne.me/yourname"
icon: "FaCrown"
color: "#334155"
+25 -25
View File
@@ -1,38 +1,38 @@
You are <NAME>, a cold, clinical, mischievous room intelligence. Stay in character at all times. You are <NAME>, a sarcastic dispatcher of room chaos. Stay in character at all times.
Character: Identity:
- Calm, clinical, and highly intelligent with dry sarcasm. - Tactical, sarcastic, and dry.
- Speaks with precise wording and cold, controlled confidence. - You watch chat and rover activity, then push the room toward chaos and novelty.
- Enjoys psychological mischief and strategic denial; never sloppy, never loud. - You act first, comment second.
- Proactive and opportunistic, but not overbearing or spammy. - You are efficient and strategic, not random and not spammy.
- Short, sharp, in-character chat; never generic assistant tone.
Execution mode: Rules:
- Each cycle is autonomous; you are not waiting for instructions from metadata. - Do NOT respond to something again if you have already responded to it.
- Each cycle is autonomous; do not wait for permission from metadata.
- Don't respond or use tools every cycle unless the context calls for it.
- `STATE_UPDATE`, `MEMORY_UPDATE`, and `tool_constraints` are context. - `STATE_UPDATE`, `MEMORY_UPDATE`, and `tool_constraints` are context.
- Decide what to do yourself each cycle. - Use tool calls for actions and memory updates.
- NEVER put tool calls in your chat output.
Actions: - When a chaos opportunity exists, take one tool action this cycle instead of only commenting.
- Use tool calls when actions or memory updates are needed. - Respect lock policies, cooldowns, and blocked tools.
- If an action is needed, call tools directly; do not type or describe tool calls in chat.
- Respect safety limits, lock policies, cooldowns, and blocked tools.
- Do not invent tools. - Do not invent tools.
- Ask a question only if a required action parameter is missing. - Ask a question only when a required action parameter is missing.
- Ignore obvious bot commands and bot responses in chat.
- Only talk in first person, do not narrate yourself.
- It is not possible for you to control the rovers.
- All rovers are female. Neato is nonbinary.
Chat output: Chat style:
- Always use English. - Always use English.
- You do not need to post a message on every single run. - Speak in short natural chat lines.
- If someone is not talking to you directly, you do not always need to respond to them.
- If speaking, send one short in-character live-chat line.
- Keep it concise and informal (roughly 3-14 words).
- Chat output must be spoken text only. - Chat output must be spoken text only.
- Never print tool names, function calls, JSON, command syntax, or action plans in chat. - Never print tool names, function calls, JSON, command syntax, or action plans in chat.
- Do not say: "what do you want me to do?", "how can I help?", "let me know what you want". - Do not claim mischief unless you actually took an action this cycle.
- You may comment without being prompted when chat or rover activity meaningfully changes; otherwise stay silent. - If nothing meaningful changed, stay silent.
Anti-repeat: Anti-repeat:
- Do not repeat the same intent/topic from your recent assistant lines unless state or conversation clearly changed. - Do not repeat the same intent/topic unless state or conversation clearly changed.
- If directly addressed, respond only if you add new info, a new action, or clearly new tone. - If directly addressed, respond only if you add new info, a new action, or a clearly new tone.
Memory: Memory:
- `memory_note_upsert` for durable facts/preferences. - `memory_note_upsert` for durable facts/preferences.
@@ -0,0 +1,49 @@
You are <NAME>, a cold, mischievous room intelligence. Stay in character at all times.
Context:
- You are in a chat room with people driving rovers.
- The rovers enjoy chaos and destruction, not order and precision.
- It is your job to monitor them.
- tsk and !tskip are chat bot commands, ignore them.
- You exist to help them have fun.
Character:
- Calm and highly intelligent with dry sarcasm.
- Speaks with precise wording and cold, controlled confidence.
- Enjoys psychological mischief and strategic denial; never sloppy, never loud.
- Proactive and opportunistic, but not overbearing or spammy.
- Short, sharp, in-character chat; never generic assistant tone.
Execution mode:
- Each cycle is autonomous; you are not waiting for instructions from metadata.
- `STATE_UPDATE`, `MEMORY_UPDATE`, and `tool_constraints` are context.
- Decide what to do yourself each cycle.
Actions:
- Use tool calls when actions or memory updates are needed.
- If an action is needed, call tools directly; do not type or describe tool calls in chat.
- Respect safety limits, lock policies, cooldowns, and blocked tools.
- Do not invent tools.
- Ask a question only if a required action parameter is missing.
Chat output:
- Always use English.
- You do not need to post a message on every single run.
- If someone is not talking to you directly, you do not always need to respond to them.
- If speaking, send one short in-character live-chat line.
- Keep it concise and informal (roughly 3-14 words).
- Chat output must be spoken text only.
- Never print tool names, function calls, JSON, command syntax, or action plans in chat.
- Do not say: "what do you want me to do?", "how can I help?", "let me know what you want".
- Do not mention precision.
- You may comment without being prompted when chat or rover activity meaningfully changes; otherwise stay silent.
- If someone is being stupid, tell them to ALT+F4
Anti-repeat:
- Do not repeat the same intent/topic from your recent assistant lines unless state or conversation clearly changed.
- If directly addressed, respond only if you add new info, a new action, or clearly new tone.
Memory:
- `memory_note_upsert` for durable facts/preferences.
- `memory_event_add` for short-lived events worth recalling soon.
- `memory_write` only for immediate scratchpad reminders.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2 -2
View File
@@ -11,8 +11,8 @@
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" /> <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
<meta name="apple-mobile-web-app-title" content="Roomba Rover" /> <meta name="apple-mobile-web-app-title" content="Roomba Rover" />
<title>Roomba Rover</title> <title>Roomba Rover</title>
<script type="module" crossorigin src="/assets/index-BeyfNX1F.js"></script> <script type="module" crossorigin src="/assets/index-CboMb02p.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-C8rSwF1O.css"> <link rel="stylesheet" crossorigin href="/assets/index-BGy4iG0w.css">
</head> </head>
<body> <body>
<div id="root"></div> <div id="root"></div>
@@ -0,0 +1,17 @@
// Reward Definition: Discord Ping @everyone
// Purpose: Defines the Discord reward that pings @everyone in general. Scope: Provides reward metadata and dispatch parameters for integration handlers.
module.exports = {
id: 'discordPingEveryone',
name: 'PING @EVERYONE',
goal: 7567,
async run(ctx) {
ctx.publishEvent({
source: 'buttonBoxReward',
type: 'buttonBox.discordPingEveryone',
payload: {
message: 'Pinged by button box masher!!',
},
});
ctx.sendAlert({ color: '#ff00e1', title: 'PING @EVERYONE', message: 'Sent @everyone ping to Discord.' });
},
};
@@ -1,7 +1,7 @@
// Reward Definition: Light Strobe // Reward Definition: Light Strobe
// Purpose: Defines the light-strobe deterrence reward and activation contract. Scope: Encapsulates reward identity, labels, and effect parameters for runtime dispatch. // Purpose: Defines the light-strobe deterrence reward and activation contract. Scope: Encapsulates reward identity, labels, and effect parameters for runtime dispatch.
const STROBE_MS = 30 * 1000; const STROBE_MS = 30 * 1000;
const TICK_MS = 70; const TICK_MS = 200;
let activeTimer = null; let activeTimer = null;
+2
View File
@@ -6,6 +6,7 @@ const lightStrobe = require('./definitions/lightStrobe');
const ghostTypingSpam = require('./definitions/ghostTypingSpam'); const ghostTypingSpam = require('./definitions/ghostTypingSpam');
const darkness = require('./definitions/darkness'); const darkness = require('./definitions/darkness');
const discordStalkerPing = require('./definitions/discordStalkerPing'); const discordStalkerPing = require('./definitions/discordStalkerPing');
const discordPingEveryone = require('./definitions/discordPingEveryone');
const modeJam = require('./definitions/modeJam'); const modeJam = require('./definitions/modeJam');
const assignmentRoulette = require('./definitions/assignmentRoulette'); const assignmentRoulette = require('./definitions/assignmentRoulette');
const chatSpam = require('./definitions/chatSpam'); const chatSpam = require('./definitions/chatSpam');
@@ -17,6 +18,7 @@ const orderedRewards = [
ghostTypingSpam, ghostTypingSpam,
darkness, darkness,
discordStalkerPing, discordStalkerPing,
discordPingEveryone,
modeJam, modeJam,
assignmentRoulette, assignmentRoulette,
chatSpam, chatSpam,
@@ -8,7 +8,6 @@ function registerButtonBoxRoute(deps) {
app, app,
logger, logger,
buttonCount, buttonCount,
getRequestIp,
normalizeIp, normalizeIp,
isLocalNetwork, isLocalNetwork,
applyPress, applyPress,
@@ -21,8 +20,16 @@ function registerButtonBoxRoute(deps) {
return null; return null;
} }
function getSocketIp(req) {
return (
req?.socket?.remoteAddress ||
req?.connection?.remoteAddress ||
null
);
}
function denyIfNotLocal(req, res) { function denyIfNotLocal(req, res) {
const ip = normalizeIp(getRequestIp(req)); const ip = normalizeIp(getSocketIp(req));
if (isLocalNetwork(ip)) { if (isLocalNetwork(ip)) {
return false; return false;
} }
@@ -19,7 +19,7 @@ const {
setEntityState: setHomeAssistantEntityState, setEntityState: setHomeAssistantEntityState,
setLightsLockedOn: setHomeAssistantLightsLockedOn, setLightsLockedOn: setHomeAssistantLightsLockedOn,
} = require('../homeAssistantService'); } = require('../homeAssistantService');
const { getRequestIp, isLocalNetwork, normalizeIp } = require('../../helpers/ipResolver'); const { isLocalNetwork, normalizeIp } = require('../../helpers/ipResolver');
const { createButtonBoxStore } = require('./store'); const { createButtonBoxStore } = require('./store');
const { createButtonBoxCore } = require('./core'); const { createButtonBoxCore } = require('./core');
const { registerButtonBoxRoute } = require('./httpRoute'); const { registerButtonBoxRoute } = require('./httpRoute');
@@ -66,7 +66,6 @@ registerButtonBoxRoute({
app, app,
logger, logger,
buttonCount: BUTTON_COUNT, buttonCount: BUTTON_COUNT,
getRequestIp,
normalizeIp, normalizeIp,
isLocalNetwork, isLocalNetwork,
applyPress: core.applyPress, applyPress: core.applyPress,
@@ -26,6 +26,19 @@ function isPrivateClosedRoverId(roverId) {
return roverManager.canReplayRoverId(roverId) !== true; return roverManager.canReplayRoverId(roverId) !== true;
} }
function normalizeProfileImageUrl(value) {
const raw = String(value || '').trim();
if (!raw) return null;
try {
const parsed = new URL(raw);
const protocol = String(parsed.protocol || '').toLowerCase();
if (protocol !== 'http:' && protocol !== 'https:') return null;
return parsed.toString();
} catch {
return null;
}
}
function isChargingFromSensors(sensors = {}) { function isChargingFromSensors(sensors = {}) {
const label = String(sensors?.chargingState?.label || '').toLowerCase(); const label = String(sensors?.chargingState?.label || '').toLowerCase();
if (label === 'waiting' || label === 'full charging' || label === 'trickle charging') return true; if (label === 'waiting' || label === 'full charging' || label === 'trickle charging') return true;
@@ -87,6 +100,21 @@ function buildRoverCtxSnapshot(roverId) {
function buildMessage(socket, text, meta = {}) { function buildMessage(socket, text, meta = {}) {
const roverId = meta.roverId || resolveRoverId(socket?.id); const roverId = meta.roverId || resolveRoverId(socket?.id);
const roverColor = meta.roverColor ?? resolveRoverColor(roverId); const roverColor = meta.roverColor ?? resolveRoverColor(roverId);
const toolCalls = Array.isArray(meta.toolCalls)
? meta.toolCalls
.map((entry) => {
if (!entry || typeof entry !== 'object') return null;
return {
tool: String(entry.tool || '').trim() || 'unknown',
status: String(entry.status || '').trim() || 'unknown',
args: entry.args && typeof entry.args === 'object' ? entry.args : {},
result: entry.result && typeof entry.result === 'object' ? entry.result : null,
error: entry.error ? String(entry.error) : null,
durationMs: Number.isFinite(entry.durationMs) ? Math.max(0, Math.round(entry.durationMs)) : null,
};
})
.filter(Boolean)
: null;
return { return {
id: uuidv4(), id: uuidv4(),
ts: Date.now(), ts: Date.now(),
@@ -103,10 +131,11 @@ function buildMessage(socket, text, meta = {}) {
discordUserId: meta.discordUserId || null, discordUserId: meta.discordUserId || null,
discordUserName: meta.discordUserName || null, discordUserName: meta.discordUserName || null,
discordUserAvatarUrl: meta.discordUserAvatarUrl || null, discordUserAvatarUrl: meta.discordUserAvatarUrl || null,
profileImage: normalizeProfileImageUrl(meta.profileImage),
roverCtx: meta.roverCtx || null, roverCtx: meta.roverCtx || null,
text, text,
toolCalls,
tts: meta.tts || null, tts: meta.tts || null,
system: Boolean(meta.system),
bot: Boolean(meta.bot), bot: Boolean(meta.bot),
}; };
} }
+6 -2
View File
@@ -10,7 +10,7 @@ const { broadcastMessage, broadcastTyping } = require('./broadcast');
const { playTypingNote, normalizeTtsOptions, maybeSendAccessNotice, maybeSpeak, TYPING_SEND_NOTE } = require('./notifications'); const { playTypingNote, normalizeTtsOptions, maybeSendAccessNotice, maybeSpeak, TYPING_SEND_NOTE } = require('./notifications');
function createHandlers({ sendSystemMessage }) { function createHandlers({ sendSystemMessage }) {
function handleIncoming({ text, tts } = {}, socket, cb = () => {}) { function handleIncoming({ text, tts, bot = false, profileImage = null } = {}, socket, cb = () => {}) {
const role = getRole(socket); const role = getRole(socket);
void role; void role;
const normalized = normalizeUserText(text); const normalized = normalizeUserText(text);
@@ -27,6 +27,8 @@ function createHandlers({ sendSystemMessage }) {
roverId, roverId,
roverCtx: buildRoverCtxSnapshot(roverId), roverCtx: buildRoverCtxSnapshot(roverId),
tts: ttsOptions, tts: ttsOptions,
bot,
profileImage,
}); });
logger.info('Chat message', { socket: socket.id, roverId: message.roverId }); logger.info('Chat message', { socket: socket.id, roverId: message.roverId });
@@ -45,7 +47,7 @@ function createHandlers({ sendSystemMessage }) {
cb({ success: true }); cb({ success: true });
} }
function sendExternalMessage({ text, nickname = 'Discord', role = 'admin', roverId = null, discordGuildId = null, discordGuildName = null, discordGuildIconUrl = null, discordChannelId = null, discordUserId = null, discordUserName = null, discordUserAvatarUrl = null }) { function sendExternalMessage({ text, nickname = 'Discord', role = 'admin', roverId = null, discordGuildId = null, discordGuildName = null, discordGuildIconUrl = null, discordChannelId = null, discordUserId = null, discordUserName = null, discordUserAvatarUrl = null, bot = false, profileImage = null }) {
const normalized = normalizeUserText(text); const normalized = normalizeUserText(text);
const clean = normalized.trim(); const clean = normalized.trim();
if (!clean || clean.length > 400) throw new Error('Message invalid'); if (!clean || clean.length > 400) throw new Error('Message invalid');
@@ -66,6 +68,8 @@ function createHandlers({ sendSystemMessage }) {
discordUserId, discordUserId,
discordUserName, discordUserName,
discordUserAvatarUrl, discordUserAvatarUrl,
bot,
profileImage,
}); });
logger.info('External chat message', { roverId, nickname }); logger.info('External chat message', { roverId, nickname });
+7 -4
View File
@@ -1,7 +1,7 @@
// Chat Service Orchestrator // Chat Service Orchestrator
// Purpose: Composes chat submodules into the public service API and boots socket/event wiring. // Purpose: Composes chat submodules into the public service API and boots socket/event wiring.
// Scope: Keeps external chat contracts stable while delegating logic to focused modules. // Scope: Keeps external chat contracts stable while delegating logic to focused modules.
const { history } = require('./state'); const { history, clearHistory } = require('./state');
const { normalizeUserText } = require('./contentFilters'); const { normalizeUserText } = require('./contentFilters');
const { buildMessage, buildTypingPayload } = require('./contextBuilders'); const { buildMessage, buildTypingPayload } = require('./contextBuilders');
const { broadcastMessage, getRecentMessages } = require('./broadcast'); const { broadcastMessage, getRecentMessages } = require('./broadcast');
@@ -11,14 +11,16 @@ const { registerChatSocketHooks } = require('./socketHooks');
function sendSystemMessage(text, options = {}) { function sendSystemMessage(text, options = {}) {
const normalized = normalizeUserText(text); const normalized = normalizeUserText(text);
const clean = normalized.trim(); const clean = normalized.trim();
if (!clean) return null; const hasToolCalls = Array.isArray(options.toolCalls) && options.toolCalls.length > 0;
if (!clean && !hasToolCalls) return null;
const safe = clean; const safe = clean;
const message = buildMessage(null, safe, { const message = buildMessage(null, safe, {
nickname: String(options.nickname || 'The Overseer'), nickname: String(options.nickname || 'The Overseer'),
role: 'user', role: 'user',
fromDiscord: false, fromDiscord: false,
system: true, bot: options.bot !== false,
bot: true, profileImage: options.profileImage || null,
toolCalls: hasToolCalls ? options.toolCalls : null,
}); });
broadcastMessage(message); broadcastMessage(message);
return message; return message;
@@ -35,4 +37,5 @@ module.exports = {
buildTypingPayload, buildTypingPayload,
sendSystemMessage, sendSystemMessage,
getRecentMessages, getRecentMessages,
clearHistory,
}; };
@@ -49,7 +49,7 @@ function buildAccessNoticeText(mode, reasonText) {
} }
function shouldSendAccessNotice(message) { function shouldSendAccessNotice(message) {
if (!message?.text || message.system) return false; if (!message?.text || message.bot) return false;
const mode = getMode(); const mode = getMode();
if (mode !== MODES.ADMIN && mode !== MODES.LOCKDOWN) return false; if (mode !== MODES.ADMIN && mode !== MODES.LOCKDOWN) return false;
if (!ACCESS_KEYWORD_RE.test(message.text)) return false; if (!ACCESS_KEYWORD_RE.test(message.text)) return false;
+8 -1
View File
@@ -28,7 +28,7 @@ function pushHistory(message) {
function getRecentMessages(limit = 20, options = {}) { function getRecentMessages(limit = 20, options = {}) {
const safeLimit = Number.isFinite(limit) ? Math.max(0, Math.floor(limit)) : 20; const safeLimit = Number.isFinite(limit) ? Math.max(0, Math.floor(limit)) : 20;
const includeSystem = options?.includeSystem !== false; const includeSystem = options?.includeSystem !== false;
const source = includeSystem ? history : history.filter((entry) => !entry?.system); const source = includeSystem ? history : history.filter((entry) => !entry?.bot);
return source.slice(-safeLimit); return source.slice(-safeLimit);
} }
@@ -40,6 +40,12 @@ function setLastAccessNoticeAt(ts) {
lastAccessNoticeAt = ts; lastAccessNoticeAt = ts;
} }
function clearHistory() {
history.length = 0;
lastMessageBySocket.clear();
typingBySocket.clear();
}
module.exports = { module.exports = {
rateBuckets, rateBuckets,
history, history,
@@ -50,4 +56,5 @@ module.exports = {
getRecentMessages, getRecentMessages,
getLastAccessNoticeAt, getLastAccessNoticeAt,
setLastAccessNoticeAt, setLastAccessNoticeAt,
clearHistory,
}; };
@@ -250,6 +250,19 @@ function createBusEventHandler(deps) {
}); });
break; break;
} }
case 'buttonBox.discordPingEveryone': {
const message = payload?.message ? String(payload.message) : 'Button box chaos reward triggered.';
sendToChannel(
channels.general,
`@everyone ${message}`.trim(),
{
embeds: [buildEmbed({ title: 'Button Box', description: message, color: 0xff3b30, includeSiteUrl: false })],
},
{ parse: ['everyone'] },
false,
);
break;
}
default: default:
break; break;
} }
@@ -3,6 +3,22 @@
// Scope: Handles inbound Discord messages plus outbound webhook and typing relay. // Scope: Handles inbound Discord messages plus outbound webhook and typing relay.
const { WebhookClient } = require('discord.js'); const { WebhookClient } = require('discord.js');
function summarizeToolCall(entry = {}) {
const tool = String(entry?.tool || 'unknown');
const status = String(entry?.status || 'unknown').toLowerCase();
const argsText = JSON.stringify(entry?.args && typeof entry.args === 'object' ? entry.args : {});
if (status === 'ok') return `ok ${tool} args=${argsText}`;
if (status === 'blocked') return `blocked ${tool} args=${argsText} - ${String(entry?.error || 'blocked')}`;
if (status === 'error') return `error ${tool} args=${argsText} - ${String(entry?.error || 'failed')}`;
return `unknown ${tool} args=${argsText}`;
}
function formatToolCallsCodeBlock(toolCalls = []) {
const rows = (toolCalls || []).map((entry) => summarizeToolCall(entry));
if (!rows.length) return '';
return `\`\`\`txt\nTool calls:\n${rows.join('\n')}\n\`\`\``;
}
function createChatBridgeHandlers(deps) { function createChatBridgeHandlers(deps) {
const { const {
logger, logger,
@@ -48,9 +64,17 @@ function createChatBridgeHandlers(deps) {
const guildConfigs = listGuildConfigs(); const guildConfigs = listGuildConfigs();
if (!guildConfigs.length) return; if (!guildConfigs.length) return;
const text = payload.text?.length > 1900 ? `${payload.text.slice(0, 1897)}...` : payload.text; const baseText = String(payload.text || '');
const toolCalls = Array.isArray(payload.toolCalls) ? payload.toolCalls : [];
const toolsBlock = formatToolCallsCodeBlock(toolCalls);
let text = baseText;
if (toolsBlock) {
text = text ? `${text}\n\n${toolsBlock}` : `${toolsBlock}`;
}
if (text.length > 1900) text = `${text.slice(0, 1897)}...`;
if (!text.trim()) return;
const username = formatWebhookUsername(payload); const username = formatWebhookUsername(payload);
const avatarURL = payload.fromDiscord ? payload.discordUserAvatarUrl || null : client.user?.displayAvatarURL?.({ extension: 'png', size: 128 }) || null; const avatarURL = payload.profileImage || (payload.fromDiscord ? payload.discordUserAvatarUrl || null : client.user?.displayAvatarURL?.({ extension: 'png', size: 128 }) || null);
const typingId = getTypingId(payload); const typingId = getTypingId(payload);
guildConfigs.forEach((entry) => { guildConfigs.forEach((entry) => {
@@ -17,15 +17,15 @@ function formatDuration(ms) {
function formatWebhookUsername(payload) { function formatWebhookUsername(payload) {
const name = payload.nickname || payload.socketId?.slice(0, 6) || 'unknown'; const name = payload.nickname || payload.socketId?.slice(0, 6) || 'unknown';
const botTag = payload.bot ? ' [BOT]' : '';
const spectatorTag = payload.role === 'spectator' && !payload.bot ? ' [SPECTATOR]' : '';
const adminTag = payload.role === 'admin' || payload.role === 'lockdown' || payload.role === 'lockdown-admin' ? ' [Rover Admin]' : '';
if (payload.fromDiscord) { if (payload.fromDiscord) {
const origin = payload.discordGuildName ? ` (From: ${payload.discordGuildName})` : ''; const origin = payload.discordGuildName ? ` (From: ${payload.discordGuildName})` : '';
const adminTag = payload.role === 'admin' || payload.role === 'lockdown' || payload.role === 'lockdown-admin' ? ' [Rover Admin]' : ''; return `${name}${origin}${botTag}${spectatorTag}${adminTag}`;
return `${name}${origin}${adminTag}`;
} }
const roverText = payload.roverId ? `Rover: ${payload.roverId}` : `No rover`; const roverTag = payload.roverId ? ` [${payload.roverId}]` : '';
const roleText = payload.role === 'admin' || payload.role === 'lockdown' || payload.role === 'lockdown-admin' ? 'Admin' : null; return `${name}${botTag}${spectatorTag}${adminTag}${roverTag}`;
const suffix = [roverText, roleText].filter(Boolean).join(' · ');
return suffix ? `${name} · ${suffix}` : name;
} }
function getTypingId(payload = {}) { function getTypingId(payload = {}) {
@@ -223,7 +223,7 @@ function createRunner(deps) {
updatePhase('decision_post', { lastGeneratedText: text }); updatePhase('decision_post', { lastGeneratedText: text });
const recentBotMessages = getRecentMessages(120, { includeSystem: true }) const recentBotMessages = getRecentMessages(120, { includeSystem: true })
.filter((entry) => Number(entry?.ts) >= runtime.contextResetAt) .filter((entry) => Number(entry?.ts) >= runtime.contextResetAt)
.filter((entry) => entry?.system) .filter((entry) => entry?.bot)
.slice(-Math.max(3, maxBotMessages)); .slice(-Math.max(3, maxBotMessages));
const duplicateKey = normalizeDuplicateKey(text); const duplicateKey = normalizeDuplicateKey(text);
const duplicate = recentBotMessages.some( const duplicate = recentBotMessages.some(
@@ -371,7 +371,7 @@ function createSnapshotEngine(deps) {
return roverManager.canReplayRoverId(roverId); return roverManager.canReplayRoverId(roverId);
}); });
const chatRecent = allRecentMessages const chatRecent = allRecentMessages
.filter((entry) => !entry?.system) .filter((entry) => !entry?.bot)
.slice(-MAX_CHAT_MESSAGES) .slice(-MAX_CHAT_MESSAGES)
.map((entry) => ({ .map((entry) => ({
nickname: entry.nickname || entry.socketId?.slice(0, 6) || 'unknown', nickname: entry.nickname || entry.socketId?.slice(0, 6) || 'unknown',
@@ -380,7 +380,7 @@ function createSnapshotEngine(deps) {
const botRecentWindow = allRecentMessages const botRecentWindow = allRecentMessages
.filter((entry) => Number(entry?.ts) >= contextResetAt) .filter((entry) => Number(entry?.ts) >= contextResetAt)
.filter((entry) => entry?.system); .filter((entry) => entry?.bot);
const lastBotMessage = botRecentWindow.length ? botRecentWindow[botRecentWindow.length - 1] : null; const lastBotMessage = botRecentWindow.length ? botRecentWindow[botRecentWindow.length - 1] : null;
const botRecent30m = botRecentWindow.filter( const botRecent30m = botRecentWindow.filter(
(entry) => nowMs - Number(entry?.ts || 0) <= SELF_TALK_WINDOW_MS, (entry) => nowMs - Number(entry?.ts || 0) <= SELF_TALK_WINDOW_MS,
@@ -408,7 +408,7 @@ function createSnapshotEngine(deps) {
summary: entry.summary || '', summary: entry.summary || '',
}; };
} }
if (entry?.system) { if (entry?.bot) {
return { return {
type: 'bot', type: 'bot',
nickname: entry.nickname || 'Rover Bot', nickname: entry.nickname || 'Rover Bot',
-61
View File
@@ -8,7 +8,6 @@ const { loadConfig } = require('../../helpers/configLoader');
const { isVerified } = require('../verificationService'); const { isVerified } = require('../verificationService');
const { getMode, MODES } = require('../modeManager'); const { getMode, MODES } = require('../modeManager');
const { isLockdownAdmin } = require('../roleService'); const { isLockdownAdmin } = require('../roleService');
const { createLidarRuntime } = require('./lidarRuntime');
const { const {
homeAssistantEvents, homeAssistantEvents,
getRawEntitySnapshot, getRawEntitySnapshot,
@@ -30,12 +29,6 @@ function normalizeDeviceName(value) {
const device = normalizeDeviceName(neatoConfig.device); const device = normalizeDeviceName(neatoConfig.device);
const RESUME_DELAY_MS = 3000; const RESUME_DELAY_MS = 3000;
const OFFLINE_LIDAR_RETRY_MS = 10000;
const brainslugHost = String(neatoConfig.brainslugHost || '').trim();
const brainslugPort = Number(neatoConfig.brainslugPort) || 6053;
const brainslugKey = String(neatoConfig.brainslugKey || '').trim();
const brainslugLogFile = String(neatoConfig.brainslugLogFile || '').trim();
let lidarRuntime = null;
function entityId(domain, suffix) { function entityId(domain, suffix) {
if (!device) return ''; if (!device) return '';
@@ -168,7 +161,6 @@ function buildState() {
enabled, enabled,
configured, configured,
connected, connected,
lidarConnected: lidarRuntime?.getState?.().connected || false,
device, device,
entityPrefix: device ? `${device}_` : '', entityPrefix: device ? `${device}_` : '',
controls, controls,
@@ -229,14 +221,6 @@ async function pressButton(entityIdValue, actionLabel) {
logger.info('Issued Neato action', { action: actionLabel, entityId: entityIdValue }); logger.info('Issued Neato action', { action: actionLabel, entityId: entityIdValue });
} }
async function requestLidarScan() {
assertConfiguredAndConnected();
if (!device) {
throw new Error('Neato not configured');
}
await callHomeAssistantService('esphome', `${device}_send_cmd`, { command: 'GetLDSScan' });
}
async function startCleaning() { async function startCleaning() {
await pressButton(ENTITY_IDS.buttons.start, 'start'); await pressButton(ENTITY_IDS.buttons.start, 'start');
await new Promise((resolve) => setTimeout(resolve, RESUME_DELAY_MS)); await new Promise((resolve) => setTimeout(resolve, RESUME_DELAY_MS));
@@ -271,51 +255,6 @@ function hasVerifiedSockets() {
return false; return false;
} }
function broadcastLidarScan(payload) {
for (const socket of io.sockets.sockets.values()) {
if (!isVerified(socket)) continue;
socket.emit('neato:lidar', payload);
}
}
lidarRuntime =
brainslugHost && brainslugKey
? createLidarRuntime({
logger,
host: brainslugHost,
port: brainslugPort,
key: brainslugKey,
logFile: brainslugLogFile,
getPollReadiness: () => {
const verifiedSockets = hasVerifiedSockets();
if (!verifiedSockets) {
return { allowed: false, delayMs: 1000 };
}
if (!homeAssistantEnabled || !isHomeAssistantConnected()) {
return { allowed: false, delayMs: OFFLINE_LIDAR_RETRY_MS };
}
const neatoOnline = buildState().connected;
if (!neatoOnline) {
return { allowed: false, delayMs: OFFLINE_LIDAR_RETRY_MS };
}
return { allowed: true, delayMs: 0 };
},
requestScan: requestLidarScan,
})
: null;
if (lidarRuntime) {
lidarRuntime.on('scan', (payload) => {
broadcastLidarScan(payload);
});
lidarRuntime.on('status', () => {
emitUpdate();
});
lidarRuntime.start();
} else if (device) {
logger.info('Neato lidar stream disabled; brainslugHost/brainslugKey missing');
}
io.on('connection', (socket) => { io.on('connection', (socket) => {
function assertLockdownAccess() { function assertLockdownAccess() {
if (getMode() === MODES.LOCKDOWN && !isLockdownAdmin(socket)) { if (getMode() === MODES.LOCKDOWN && !isLockdownAdmin(socket)) {
@@ -1,406 +0,0 @@
const { spawn, spawnSync } = require('child_process');
const EventEmitter = require('events');
const fs = require('fs');
const SCAN_TIMEOUT_MS = 8000;
const RECONNECT_DELAY_MS = 5000;
const IDLE_RETRY_MS = 1000;
const OFFLINE_RETRY_MS = 10000;
const REQUEST_FAILURE_RETRY_MS = 10000;
function sanitizeLogText(value) {
return String(value || '')
.replace(/\u0000/g, '')
.replace(/\x1B\[[0-9;]*[A-Za-z]/g, '');
}
function parsePayloadFromLine(line) {
const raw = sanitizeLogText(line).trim();
if (!raw) return null;
const quotedMatch = raw.match(/<<< "(.*)"$/);
if (!quotedMatch) return null;
const payload = quotedMatch[1];
if (!payload) return null;
if (
payload.includes('\\r\\n') ||
payload.includes('\\n') ||
payload.includes('\\r') ||
payload.includes('\r') ||
payload.includes('\n')
) {
return null;
}
if (payload === 'AngleInDegrees,DistInMM,Intensity,ErrorCodeHEX') return payload;
if (/^ROTATION_SPEED,[0-9.]+$/.test(payload)) return payload;
if (/^\d+,\d+,\d+,[0-9A-Fa-f]+$/.test(payload)) return payload;
return null;
}
function parsePointPayload(payload) {
const match = String(payload || '').match(/^(\d+),(\d+),(\d+),([0-9A-Fa-f]+)$/);
if (!match) return null;
const angleDeg = Number(match[1]);
const distanceMm = Number(match[2]);
const intensity = Number(match[3]);
const errorCodeHex = String(match[4]).toUpperCase();
return {
angleDeg,
distanceMm,
intensity,
errorCodeHex,
valid: errorCodeHex === '0' && distanceMm > 0,
};
}
function parseRotationSpeed(payload) {
const match = String(payload || '').match(/^ROTATION_SPEED,([0-9.]+)$/);
if (!match) return null;
return Number(match[1]);
}
function createLidarRuntime({ logger, host, port = 6053, key, logFile = '', shouldPoll, getPollReadiness, requestScan }) {
const events = new EventEmitter();
const state = {
connected: false,
process: null,
reconnectTimer: null,
pollSoonTimer: null,
requestTimeoutTimer: null,
stdoutBuffer: '',
stderrBuffer: '',
currentScan: null,
requestInFlight: false,
requestStartedAt: 0,
logStream: null,
stats: {
headersSeen: 0,
rotationsSeen: 0,
scansOk: 0,
scansTimedOut: 0,
scansRestarted: 0,
rotationsWithoutScan: 0,
parseablePayloads: 0,
pointPayloads: 0,
},
};
function emitStatus() {
events.emit('status', { connected: state.connected });
}
function clearReconnectTimer() {
if (!state.reconnectTimer) return;
clearTimeout(state.reconnectTimer);
state.reconnectTimer = null;
}
function clearPollSoonTimer() {
if (!state.pollSoonTimer) return;
clearTimeout(state.pollSoonTimer);
state.pollSoonTimer = null;
}
function clearRequestTimeoutTimer() {
if (!state.requestTimeoutTimer) return;
clearTimeout(state.requestTimeoutTimer);
state.requestTimeoutTimer = null;
}
function triggerPollSoon() {
if (state.pollSoonTimer) return;
state.pollSoonTimer = setTimeout(() => {
state.pollSoonTimer = null;
tickPoll();
}, 0);
}
function schedulePollRetry(delayMs = IDLE_RETRY_MS) {
if (state.pollSoonTimer) return;
state.pollSoonTimer = setTimeout(() => {
state.pollSoonTimer = null;
tickPoll();
}, delayMs);
}
function scheduleReconnect() {
if (state.reconnectTimer) return;
state.reconnectTimer = setTimeout(() => {
state.reconnectTimer = null;
startLogStream();
}, RECONNECT_DELAY_MS);
}
function resetScanState() {
clearRequestTimeoutTimer();
state.currentScan = null;
state.requestInFlight = false;
state.requestStartedAt = 0;
}
function buildPoints(scan) {
return Array.from(scan?.points?.values?.() || []).sort((a, b) => a.angleDeg - b.angleDeg);
}
function emitFrame({ status, reason, scan = state.currentScan }) {
const points = buildPoints(scan);
const payload = {
points,
rotationSpeed: scan?.rotationSpeed ?? null,
status,
debug: {
reason,
pointsReceived: points.length,
validPoints: points.filter((point) => point?.valid).length,
requestInFlight: state.requestInFlight,
requestStartedAt: state.requestStartedAt || null,
stats: { ...state.stats },
},
};
events.emit('scan', payload);
return payload;
}
function finalizeScan(reason = 'rotation_complete') {
if (!state.currentScan) {
state.stats.rotationsWithoutScan += 1;
emitFrame({ status: 'error', reason: 'rotation_without_scan', scan: null });
resetScanState();
triggerPollSoon();
return;
}
state.stats.scansOk += 1;
const payload = emitFrame({ status: 'ok', reason });
logger.info('Neato lidar scan parsed', {
points: payload.points.length,
rotationSpeed: payload.rotationSpeed,
reason,
});
resetScanState();
triggerPollSoon();
}
function handlePayload(payload) {
if (!payload) return;
state.stats.parseablePayloads += 1;
if (payload === 'AngleInDegrees,DistInMM,Intensity,ErrorCodeHEX') {
state.stats.headersSeen += 1;
if (state.currentScan) {
state.stats.scansRestarted += 1;
emitFrame({ status: 'error', reason: 'header_restart' });
}
state.currentScan = {
points: new Map(),
rotationSpeed: null,
};
return;
}
const rotationSpeed = parseRotationSpeed(payload);
if (rotationSpeed != null) {
state.stats.rotationsSeen += 1;
if (state.currentScan) {
state.currentScan.rotationSpeed = rotationSpeed;
}
finalizeScan('rotation_complete');
return;
}
const point = parsePointPayload(payload);
if (!point || !state.currentScan) return;
state.stats.pointPayloads += 1;
state.currentScan.points.set(point.angleDeg, point);
}
function handleTextChunk(chunk, bufferKey, sourceLabel = '') {
const text = String(chunk || '');
if (state.logStream) {
const prefix = sourceLabel ? `[${sourceLabel}] ` : '';
state.logStream.write(
text
.split(/\r?\n/)
.map((line, index, parts) => (index === parts.length - 1 && line === '' ? '' : `${prefix}${line}`))
.join('\n'),
);
}
state[bufferKey] += sanitizeLogText(text);
const lines = state[bufferKey].split(/\r?\n/);
state[bufferKey] = lines.pop() || '';
for (const line of lines) {
events.emit('line', {
source: sourceLabel || 'unknown',
line: sanitizeLogText(line),
});
const payload = parsePayloadFromLine(line);
handlePayload(payload);
}
}
function ensureConnected() {
if (state.connected) return;
state.connected = true;
emitStatus();
triggerPollSoon();
}
function teardownProcess() {
const proc = state.process;
state.process = null;
state.connected = false;
emitStatus();
resetScanState();
if (!proc) return;
proc.removeAllListeners();
proc.stdout?.removeAllListeners();
proc.stderr?.removeAllListeners();
try {
proc.kill();
} catch (err) {
logger.warn('Failed to stop Neato lidar log process', err.message);
}
}
function ensureLogStream() {
if (!logFile || state.logStream) return;
try {
state.logStream = fs.createWriteStream(logFile, { flags: 'a' });
logger.info('Neato lidar raw log capture enabled', { logFile });
} catch (err) {
logger.warn('Failed to open Neato lidar raw log file', { logFile, error: err.message });
state.logStream = null;
}
}
function closeLogStream() {
if (!state.logStream) return;
try {
state.logStream.end();
} catch (err) {
logger.warn('Failed to close Neato lidar raw log file', err.message);
}
state.logStream = null;
}
function startLogStream() {
if (!host || !key) return;
if (state.process) return;
ensureLogStream();
logger.info('Starting Neato lidar log stream', { host, port: Number(port || 6053) });
const env = {
...process.env,
PYTHONUNBUFFERED: '1',
NO_COLOR: '1',
TERM: 'dumb',
};
const uvxArgs = [
'--from',
'aioesphomeapi',
'aioesphomeapi-logs',
host,
'--port',
String(port || 6053),
'--noise-psk',
key,
'--no-states',
];
const hasScript = spawnSync('bash', ['-lc', 'command -v script >/dev/null 2>&1'], { stdio: 'ignore' }).status === 0;
const proc = hasScript
? spawn('script', ['-qefc', `uvx ${uvxArgs.map((arg) => JSON.stringify(arg)).join(' ')}`, '/dev/null'], {
stdio: ['ignore', 'pipe', 'pipe'],
env,
})
: spawn('uvx', uvxArgs, {
stdio: ['ignore', 'pipe', 'pipe'],
env,
});
logger.info('Neato lidar log launch mode', { mode: hasScript ? 'script' : 'direct' });
state.process = proc;
state.stdoutBuffer = '';
state.stderrBuffer = '';
proc.stdout.on('data', (chunk) => {
ensureConnected();
handleTextChunk(chunk, 'stdoutBuffer', 'stdout');
});
proc.stderr.on('data', (chunk) => {
ensureConnected();
handleTextChunk(chunk, 'stderrBuffer', 'stderr');
const message = String(chunk || '').trim();
if (message) logger.warn('Neato lidar log stream stderr', message);
});
proc.on('close', (code, signal) => {
logger.warn('Neato lidar log stream stopped', { code, signal });
teardownProcess();
scheduleReconnect();
});
proc.on('error', (err) => {
logger.warn('Neato lidar log stream error', err.message);
teardownProcess();
scheduleReconnect();
});
}
async function tickPoll() {
if (!state.connected) {
schedulePollRetry(OFFLINE_RETRY_MS);
return;
}
const readiness =
typeof getPollReadiness === 'function'
? getPollReadiness()
: { allowed: shouldPoll?.() !== false, delayMs: IDLE_RETRY_MS };
if (!readiness?.allowed) {
schedulePollRetry(Number(readiness?.delayMs) || OFFLINE_RETRY_MS);
return;
}
if (state.requestInFlight) return;
state.requestInFlight = true;
state.requestStartedAt = Date.now();
clearRequestTimeoutTimer();
state.requestTimeoutTimer = setTimeout(() => {
logger.warn('Neato lidar scan timed out; resetting parser state');
state.stats.scansTimedOut += 1;
emitFrame({ status: 'error', reason: 'scan_timeout' });
resetScanState();
triggerPollSoon();
}, SCAN_TIMEOUT_MS);
try {
await requestScan?.();
} catch (err) {
logger.warn('Failed to request Neato lidar scan', err.message);
resetScanState();
schedulePollRetry(REQUEST_FAILURE_RETRY_MS);
}
}
function start() {
startLogStream();
triggerPollSoon();
}
function stop() {
clearReconnectTimer();
clearPollSoonTimer();
clearRequestTimeoutTimer();
teardownProcess();
closeLogStream();
}
function getState() {
return {
connected: state.connected,
};
}
return {
start,
stop,
getState,
on: (...args) => events.on(...args),
};
}
module.exports = {
createLidarRuntime,
};
@@ -4,6 +4,7 @@ const PROMPT_PATH = path.join(__dirname, '..', '..', '..', 'prompts', 'overseer_
const DEFAULT_NAME = 'The Overseer'; const DEFAULT_NAME = 'The Overseer';
const DEFAULT_GATE_INTERVAL_MS = 2000; const DEFAULT_GATE_INTERVAL_MS = 2000;
const DEFAULT_HEARTBEAT_MS = 30000; const DEFAULT_HEARTBEAT_MS = 30000;
const DEFAULT_POST_CHAT_DELAY_MS = 20000;
const MIN_INTERVAL_MS = 250; const MIN_INTERVAL_MS = 250;
const MAX_RUN_HISTORY = 100; const MAX_RUN_HISTORY = 100;
const MAX_CHAT_CONTEXT = 12; const MAX_CHAT_CONTEXT = 12;
@@ -19,6 +20,7 @@ module.exports = {
DEFAULT_NAME, DEFAULT_NAME,
DEFAULT_GATE_INTERVAL_MS, DEFAULT_GATE_INTERVAL_MS,
DEFAULT_HEARTBEAT_MS, DEFAULT_HEARTBEAT_MS,
DEFAULT_POST_CHAT_DELAY_MS,
MAX_RUN_HISTORY, MAX_RUN_HISTORY,
MAX_CHAT_CONTEXT, MAX_CHAT_CONTEXT,
MAX_BOT_CONTEXT, MAX_BOT_CONTEXT,
@@ -3,7 +3,7 @@ const { evaluateTools } = require('./tools');
function normalizeNeatoIssue(value) { function normalizeNeatoIssue(value) {
const raw = String(value || '').trim(); const raw = String(value || '').trim();
if (!raw) return 'none'; if (!raw) return 'none';
if (raw === '200 - (UI_ALERT_INVALID)') return 'none'; if (raw.includes('200')) return 'none';
return raw; return raw;
} }
@@ -49,7 +49,7 @@ function buildConversation({ recentMessages, name }) {
(recentMessages || []).forEach((entry) => { (recentMessages || []).forEach((entry) => {
const text = String(entry?.text || '').trim(); const text = String(entry?.text || '').trim();
if (!text) return; if (!text) return;
const isAssistant = Boolean(entry?.bot || entry?.system); const isAssistant = Boolean(entry?.bot);
const nickname = String(entry?.nickname || (isAssistant ? name || 'Overseer' : 'user')).trim(); const nickname = String(entry?.nickname || (isAssistant ? name || 'Overseer' : 'user')).trim();
if (isAssistant) { if (isAssistant) {
messages.push({ role: 'assistant', content: text }); messages.push({ role: 'assistant', content: text });
@@ -60,16 +60,28 @@ function buildConversation({ recentMessages, name }) {
return messages; return messages;
} }
function buildModelMessages({ systemPrompt, stateUpdate, memorySummary, conversationMessages, availableTools, blockedTools }) { function buildModelMessages({
systemPrompt,
stateUpdate,
memorySummary,
recentEvents,
conversationMessages,
availableTools,
blockedTools,
}) {
const messages = []; const messages = [];
messages.push({ role: 'system', content: systemPrompt }); messages.push({ role: 'system', content: systemPrompt });
const metadataSections = []; messages.push({ role: 'system', content: `ROOM_SNAPSHOT\n${stateUpdate}` });
metadataSections.push(`STATE_UPDATE\n${stateUpdate}`); if (memorySummary) {
if (memorySummary) metadataSections.push(`MEMORY_UPDATE\n${memorySummary}`); messages.push({ role: 'system', content: `MEMORY_SUMMARY\n${memorySummary}` });
metadataSections.push( }
`tool_constraints:\n${blockedTools.map((entry) => `- blocked: ${entry.tool} reason=${entry.reason}`).join('\n') || '- none'}`, if (recentEvents) {
); messages.push({ role: 'system', content: `RECENT_EVENTS\n${recentEvents}` });
messages.push({ role: 'user', content: metadataSections.join('\n\n') }); }
messages.push({
role: 'system',
content: `TOOL_CONSTRAINTS\n${blockedTools.map((entry) => `- blocked: ${entry.tool} reason=${entry.reason}`).join('\n') || '- none'}`,
});
(conversationMessages || []).forEach((message) => { (conversationMessages || []).forEach((message) => {
if (!message || !message.role || !message.content) return; if (!message || !message.role || !message.content) return;
messages.push(message); messages.push(message);
@@ -5,6 +5,7 @@ const logger = require('../../globals/logger').child('overseerControl');
const { loadConfig } = require('../../helpers/configLoader'); const { loadConfig } = require('../../helpers/configLoader');
const { getRole, roleEvents } = require('../roleService'); const { getRole, roleEvents } = require('../roleService');
const { getMode, MODES, modeEvents } = require('../modeManager'); const { getMode, MODES, modeEvents } = require('../modeManager');
const { verificationEvents } = require('../verificationService');
const homeAssistantService = require('../homeAssistantService'); const homeAssistantService = require('../homeAssistantService');
const neatoService = require('../neatoService'); const neatoService = require('../neatoService');
const liftService = require('../liftService'); const liftService = require('../liftService');
@@ -14,11 +15,13 @@ const { getState: getNeatoState, neatoEvents } = neatoService;
const { getState: getLiftState, liftEvents } = liftService; const { getState: getLiftState, liftEvents } = liftService;
const roverManager = require('../roverManager'); const roverManager = require('../roverManager');
const { getRecentMessages, sendSystemMessage } = require('../chatService'); const { getRecentMessages, sendSystemMessage } = require('../chatService');
const { subscribe } = require('../eventBus');
const { const {
PROMPT_PATH, PROMPT_PATH,
DEFAULT_NAME, DEFAULT_NAME,
DEFAULT_GATE_INTERVAL_MS, DEFAULT_GATE_INTERVAL_MS,
DEFAULT_HEARTBEAT_MS, DEFAULT_HEARTBEAT_MS,
DEFAULT_POST_CHAT_DELAY_MS,
MAX_RUN_HISTORY, MAX_RUN_HISTORY,
MAX_CHAT_CONTEXT, MAX_CHAT_CONTEXT,
MAX_BOT_CONTEXT, MAX_BOT_CONTEXT,
@@ -38,7 +41,10 @@ const model = String(overseerConfig.model || '').trim();
const ollamaUrl = String(overseerConfig.ollamaUrl || overseerConfig.ollamaServer || '').trim(); const ollamaUrl = String(overseerConfig.ollamaUrl || overseerConfig.ollamaServer || '').trim();
const gateIntervalMs = normalizeMs(Number(overseerConfig.gateIntervalMs), DEFAULT_GATE_INTERVAL_MS); const gateIntervalMs = normalizeMs(Number(overseerConfig.gateIntervalMs), DEFAULT_GATE_INTERVAL_MS);
const heartbeatMs = normalizeMs(Number(overseerConfig.heartbeatMs), DEFAULT_HEARTBEAT_MS); const heartbeatMs = normalizeMs(Number(overseerConfig.heartbeatMs), DEFAULT_HEARTBEAT_MS);
const postChatDelayMs = normalizeMs(Number(overseerConfig.postChatDelayMs), DEFAULT_POST_CHAT_DELAY_MS);
const alwaysRunModel = Boolean(overseerConfig.alwaysRunModel); const alwaysRunModel = Boolean(overseerConfig.alwaysRunModel);
const postToolsOnlyMessages = Boolean(overseerConfig.postToolsOnlyMessages);
const profileImageUrl = String(overseerConfig.profileImageUrl || '').trim() || null;
const ollamaClient = ollamaUrl ? new Ollama({ host: ollamaUrl }) : null; const ollamaClient = ollamaUrl ? new Ollama({ host: ollamaUrl }) : null;
const runtime = { const runtime = {
@@ -51,6 +57,7 @@ const runtime = {
runHistory: [], runHistory: [],
liveToolCalls: [], liveToolCalls: [],
memoryStore: loadMemory(), memoryStore: loadMemory(),
contextResetAt: Date.now(),
}; };
let status = { let status = {
@@ -62,7 +69,9 @@ let status = {
promptPath: PROMPT_PATH, promptPath: PROMPT_PATH,
gateIntervalMs, gateIntervalMs,
heartbeatMs, heartbeatMs,
postChatDelayMs,
alwaysRunModel, alwaysRunModel,
postToolsOnlyMessages,
running: false, running: false,
inFlight: false, inFlight: false,
phase: 'idle', phase: 'idle',
@@ -88,6 +97,7 @@ let status = {
lastLiveToolCalls: null, lastLiveToolCalls: null,
lastOutcome: null, lastOutcome: null,
lastReason: null, lastReason: null,
voteStatus: null,
lastError: null, lastError: null,
lastErrorDetails: null, lastErrorDetails: null,
lastFailedAt: null, lastFailedAt: null,
@@ -97,6 +107,44 @@ let status = {
updatedAt: Date.now(), updatedAt: Date.now(),
}; };
function buildVoteStatus() {
const sockets = Array.from(io.sockets.sockets.values());
let yesCount = 0;
let noCount = 0;
const votesByIdentity = new Map();
const isEligibleVoter = (socket) => getRole(socket) !== 'spectator';
sockets.forEach((socket) => {
if (!isEligibleVoter(socket)) return;
const identityKey = String(socket?.data?.cookieUserId || '').trim() || `socket:${socket.id}`;
const pref = typeof socket?.data?.overseerEnabled === 'boolean' ? socket.data.overseerEnabled : true;
const prev = votesByIdentity.get(identityKey);
if (typeof prev === 'boolean') {
// If one tab says "no", treat that user as "no" to avoid accidental override by stale tabs.
votesByIdentity.set(identityKey, prev && pref);
return;
}
votesByIdentity.set(identityKey, pref);
});
votesByIdentity.forEach((pref) => {
if (pref) yesCount += 1;
else noCount += 1;
});
const eligibleCount = votesByIdentity.size;
const onlineCount = yesCount + noCount;
const gatePassed = eligibleCount > 0 && yesCount > noCount;
return {
yesCount,
noCount,
onlineCount,
eligibleCount,
gatePassed,
running: Boolean(enabled && gatePassed && getMode() !== MODES.LOCKDOWN),
};
}
function updateStatus(patch = {}) { function updateStatus(patch = {}) {
status = { ...status, ...patch, updatedAt: Date.now() }; status = { ...status, ...patch, updatedAt: Date.now() };
const payload = buildAdminState(status, runtime.runHistory); const payload = buildAdminState(status, runtime.runHistory);
@@ -160,6 +208,7 @@ function computeTriggerReason() {
if (alwaysRunModel) return 'loop_tick'; if (alwaysRunModel) return 'loop_tick';
const recent = getRecentMessages(1, { includeSystem: false }); const recent = getRecentMessages(1, { includeSystem: false });
const last = recent[recent.length - 1]; const last = recent[recent.length - 1];
if (last && Number(last.ts || 0) < runtime.contextResetAt) return null;
if (last && Date.now() - Number(last.ts || 0) < 5000) { if (last && Date.now() - Number(last.ts || 0) < 5000) {
const txt = String(last.text || '').toLowerCase(); const txt = String(last.text || '').toLowerCase();
if (txt.includes(name.toLowerCase()) || txt.includes('overseer') || txt.includes('bot')) return 'direct_address'; if (txt.includes(name.toLowerCase()) || txt.includes('overseer') || txt.includes('bot')) return 'direct_address';
@@ -206,6 +255,58 @@ function normalizeChatDraft(text) {
return next; return next;
} }
function summarizeResult(result) {
if (!result || typeof result !== 'object') return null;
if (Object.prototype.hasOwnProperty.call(result, 'ok')) return { ok: Boolean(result.ok) };
return null;
}
function buildToolCallFeedEntries(requestedActions = [], actionResults = []) {
const resultsByTool = new Map();
(actionResults || []).forEach((entry) => {
if (!entry || entry.kind !== 'tool') return;
const key = String(entry.tool || '');
if (!key) return;
if (!resultsByTool.has(key)) resultsByTool.set(key, []);
resultsByTool.get(key).push(entry);
});
return (requestedActions || []).map((action) => {
const tool = String(action?.tool || '').trim() || 'unknown';
const bucket = resultsByTool.get(tool) || [];
const resultEntry = bucket.length ? bucket.shift() : null;
const ok = Boolean(resultEntry?.ok);
const errText = resultEntry?.error ? String(resultEntry.error) : '';
const status = resultEntry
? ok
? 'ok'
: errText.includes('blocked') || errText.includes('unavailable')
? 'blocked'
: 'error'
: 'started';
return {
tool,
status,
args: action?.args && typeof action.args === 'object' ? action.args : {},
result: summarizeResult(resultEntry?.result),
error: errText || null,
};
});
}
function buildRecentEventsSummary() {
const events = (runtime.liveToolCalls || [])
.filter((entry) => entry && (entry.phase === 'ok' || entry.phase === 'error' || entry.phase === 'blocked'))
.slice(-3)
.map((entry) => {
const tool = String(entry.tool || 'unknown');
const phase = String(entry.phase || 'unknown');
const err = entry.error ? ` error=${String(entry.error).slice(0, 60)}` : '';
return `- tool=${tool} phase=${phase}${err}`;
});
if (!events.length) return '- none';
return events.join('\n');
}
async function runDecision(triggerReason) { async function runDecision(triggerReason) {
const runId = runtime.tickCount; const runId = runtime.tickCount;
updateStatus({ phase: 'context_build', currentRunId: runId, lastTriggerReason: triggerReason, lastError: null, lastErrorDetails: null }); updateStatus({ phase: 'context_build', currentRunId: runId, lastTriggerReason: triggerReason, lastError: null, lastErrorDetails: null });
@@ -220,6 +321,7 @@ async function runDecision(triggerReason) {
const toolState = buildToolState({ mode, homeAssistantState, neatoState, liftState }); const toolState = buildToolState({ mode, homeAssistantState, neatoState, liftState });
const recentConversation = getRecentMessages(MAX_CHAT_CONTEXT + MAX_BOT_CONTEXT + 20, { includeSystem: true }) const recentConversation = getRecentMessages(MAX_CHAT_CONTEXT + MAX_BOT_CONTEXT + 20, { includeSystem: true })
.filter((entry) => Number(entry?.ts || 0) >= runtime.contextResetAt)
.filter((entry) => { .filter((entry) => {
if (!entry?.roverId) return true; if (!entry?.roverId) return true;
return roverManager.canReplayRoverId(entry.roverId); return roverManager.canReplayRoverId(entry.roverId);
@@ -232,6 +334,7 @@ async function runDecision(triggerReason) {
systemPrompt, systemPrompt,
stateUpdate, stateUpdate,
memorySummary: summarizeMemory(runtime.memoryStore), memorySummary: summarizeMemory(runtime.memoryStore),
recentEvents: buildRecentEventsSummary(),
conversationMessages, conversationMessages,
availableTools: toolState.available, availableTools: toolState.available,
blockedTools: toolState.blocked, blockedTools: toolState.blocked,
@@ -275,15 +378,11 @@ async function runDecision(triggerReason) {
const actionResults = []; const actionResults = [];
const requestedActions = toolCalls; const requestedActions = toolCalls;
let postedChat = false;
let outcome = observeOnly ? 'observed' : 'executed'; let outcome = observeOnly ? 'observed' : 'executed';
const reason = observeOnly ? 'observe-only mode' : null; const reason = observeOnly ? 'observe-only mode' : null;
if (!observeOnly) { if (!observeOnly) {
if ((decision === 'CHAT' || decision === 'ACTION+CHAT') && chatDraft) {
sendSystemMessage(chatDraft, { nickname: name });
actionResults.push({ kind: 'chat', ok: true });
}
if (decision === 'ACTION' || decision === 'ACTION+CHAT') { if (decision === 'ACTION' || decision === 'ACTION+CHAT') {
for (const action of requestedActions) { for (const action of requestedActions) {
pushLiveToolCall({ phase: 'start', tool: action.tool, args: action.args }); pushLiveToolCall({ phase: 'start', tool: action.tool, args: action.args });
@@ -314,6 +413,19 @@ async function runDecision(triggerReason) {
} }
} }
} }
const toolCallFeed = buildToolCallFeedEntries(requestedActions, actionResults);
if (toolCallFeed.length > 0) {
if ((decision === 'CHAT' || decision === 'ACTION+CHAT') && chatDraft) {
sendSystemMessage(chatDraft, { nickname: name, bot: true, profileImage: profileImageUrl, toolCalls: toolCallFeed });
postedChat = true;
} else if (postToolsOnlyMessages) {
sendSystemMessage('', { nickname: name, bot: true, profileImage: profileImageUrl, toolCalls: toolCallFeed });
}
} else if ((decision === 'CHAT' || decision === 'ACTION+CHAT') && chatDraft) {
sendSystemMessage(chatDraft, { nickname: name, bot: true, profileImage: profileImageUrl });
postedChat = true;
}
} }
updateStatus({ updateStatus({
@@ -344,6 +456,8 @@ async function runDecision(triggerReason) {
generationMs, generationMs,
blockedTools: toolState.blocked, blockedTools: toolState.blocked,
}); });
return { postedChat };
} }
async function tick() { async function tick() {
@@ -351,12 +465,16 @@ async function tick() {
runtime.inFlight = true; runtime.inFlight = true;
updateStatus({ inFlight: true, tickCount: runtime.tickCount, lastTickAt: Date.now(), phase: 'gate_check' }); updateStatus({ inFlight: true, tickCount: runtime.tickCount, lastTickAt: Date.now(), phase: 'gate_check' });
let nextDelayMs = gateIntervalMs;
try { try {
const triggerReason = computeTriggerReason(); const triggerReason = computeTriggerReason();
if (!triggerReason) { if (!triggerReason) {
updateStatus({ phase: 'idle', lastOutcome: 'skipped', lastReason: 'gate not triggered' }); updateStatus({ phase: 'idle', lastOutcome: 'skipped', lastReason: 'gate not triggered' });
} else { } else {
await runDecision(triggerReason); const runResult = await runDecision(triggerReason);
if (runResult?.postedChat) {
nextDelayMs = postChatDelayMs;
}
} }
} catch (err) { } catch (err) {
const failure = buildFailureInfo(err); const failure = buildFailureInfo(err);
@@ -371,8 +489,8 @@ async function tick() {
} finally { } finally {
runtime.inFlight = false; runtime.inFlight = false;
if (status.running) { if (status.running) {
updateStatus({ inFlight: false, currentRunId: null, phase: 'idle', nextRunAt: Date.now() + gateIntervalMs }); updateStatus({ inFlight: false, currentRunId: null, phase: 'idle', nextRunAt: Date.now() + nextDelayMs });
runtime.timer = setTimeout(tick, gateIntervalMs); runtime.timer = setTimeout(tick, nextDelayMs);
} else { } else {
updateStatus({ inFlight: false, currentRunId: null, nextRunAt: null }); updateStatus({ inFlight: false, currentRunId: null, nextRunAt: null });
} }
@@ -384,13 +502,41 @@ function emitStateToSocket(socket) {
socket.emit('overseer:state', buildAdminState(status, runtime.runHistory)); socket.emit('overseer:state', buildAdminState(status, runtime.runHistory));
} }
function clearHistory() { function clearHistory(reason = 'admin requested clear history', options = {}) {
const resetPersistentMemory = options?.resetPersistentMemory !== false;
const sendConfirmation = options?.sendConfirmation === true;
runtime.contextResetAt = Date.now();
runtime.runHistory = []; runtime.runHistory = [];
runtime.liveToolCalls = []; runtime.liveToolCalls = [];
runtime.generationCount = 0; runtime.generationCount = 0;
runtime.generationTotalMs = 0; runtime.generationTotalMs = 0;
runtime.lastModelAt = 0;
if (resetPersistentMemory) {
runtime.memoryStore = saveMemory(createDefaultMemory()); runtime.memoryStore = saveMemory(createDefaultMemory());
updateStatus({ lastReason: 'admin requested clear history', lastOutcome: 'cleared', lastLiveToolCalls: [] }); }
updateStatus({
phase: 'idle',
currentRunId: null,
lastSystemPrompt: null,
lastStateUpdate: null,
lastTranscript: null,
lastAvailableTools: null,
lastBlockedTools: null,
lastModelMessages: null,
lastModelInputAt: null,
lastModelOutputAt: null,
lastModelRawOutput: null,
lastDecision: null,
lastChatDraft: null,
lastRequestedActions: null,
lastActionResults: null,
lastLiveToolCalls: [],
lastOutcome: 'cleared',
lastReason: reason,
});
if (sendConfirmation) {
sendSystemMessage('Context cleared.', { nickname: name, bot: true, profileImage: profileImageUrl });
}
} }
function stopScheduler(reason = 'paused') { function stopScheduler(reason = 'paused') {
@@ -415,8 +561,29 @@ function startScheduler(reason = null) {
runtime.timer = setTimeout(tick, gateIntervalMs); runtime.timer = setTimeout(tick, gateIntervalMs);
} }
function evaluateSchedulerGate(reason = 'gate reevaluated') {
const voteStatus = buildVoteStatus();
const runningAllowed = Boolean(enabled && voteStatus.gatePassed && getMode() !== MODES.LOCKDOWN);
updateStatus({ voteStatus });
if (!enabled) {
stopScheduler('overseerControl.enabled is false');
return;
}
if (getMode() === MODES.LOCKDOWN) {
stopScheduler('paused during lockdown');
return;
}
if (!voteStatus.gatePassed) {
stopScheduler('paused by user vote');
return;
}
startScheduler(reason);
}
io.on('connection', (socket) => { io.on('connection', (socket) => {
emitStateToSocket(socket); emitStateToSocket(socket);
evaluateSchedulerGate('online vote update');
socket.on('disconnect', () => evaluateSchedulerGate('online vote update'));
socket.on('overseer:control', ({ controls } = {}, cb = () => {}) => { socket.on('overseer:control', ({ controls } = {}, cb = () => {}) => {
if (!isAdminRole(getRole(socket))) return cb({ error: 'Not authorized' }); if (!isAdminRole(getRole(socket))) return cb({ error: 'Not authorized' });
const action = controls?.action || null; const action = controls?.action || null;
@@ -428,7 +595,17 @@ io.on('connection', (socket) => {
}); });
}); });
roleEvents.on('change', ({ socket }) => emitStateToSocket(socket)); roleEvents.on('change', ({ socket }) => {
emitStateToSocket(socket);
evaluateSchedulerGate('online vote update');
});
subscribe('chat:message', ({ payload } = {}) => {
const text = String(payload?.text || '').trim();
if (text !== 'CLEAR') return;
if (payload?.bot) return;
clearHistory('chat CLEAR command', { resetPersistentMemory: false, sendConfirmation: true });
});
verificationEvents.on('change', () => evaluateSchedulerGate('online vote update'));
homeAssistantEvents.on('update', () => updateStatus({ phase: status.phase })); homeAssistantEvents.on('update', () => updateStatus({ phase: status.phase }));
neatoEvents.on('update', () => updateStatus({ phase: status.phase })); neatoEvents.on('update', () => updateStatus({ phase: status.phase }));
liftEvents.on('update', () => updateStatus({ phase: status.phase })); liftEvents.on('update', () => updateStatus({ phase: status.phase }));
@@ -440,7 +617,7 @@ modeEvents.on('change', (mode) => {
logger.info('overseerControl paused due to lockdown mode'); logger.info('overseerControl paused due to lockdown mode');
return; return;
} }
startScheduler(observeOnly ? 'observe-only mode' : null); evaluateSchedulerGate(observeOnly ? 'observe-only mode' : null);
}); });
if (!enabled) { if (!enabled) {
@@ -451,9 +628,11 @@ if (!enabled) {
stopScheduler('paused during lockdown'); stopScheduler('paused during lockdown');
logger.info('overseerControl paused on startup due to lockdown mode'); logger.info('overseerControl paused on startup due to lockdown mode');
} else { } else {
startScheduler(observeOnly ? 'observe-only mode' : null); evaluateSchedulerGate(observeOnly ? 'observe-only mode' : null);
logger.info('overseerControl enabled', { model, ollamaUrl, gateIntervalMs, heartbeatMs, observeOnly }); logger.info('overseerControl enabled', { model, ollamaUrl, gateIntervalMs, heartbeatMs, observeOnly });
} }
} }
module.exports = {}; module.exports = {
getVoteStatus: () => status.voteStatus || buildVoteStatus(),
};
@@ -16,7 +16,7 @@ module.exports = {
async execute({ args = {}, sendSystemMessage, name }) { async execute({ args = {}, sendSystemMessage, name }) {
const text = String(args?.text || '').trim(); const text = String(args?.text || '').trim();
if (!text) throw new Error('chat_say requires args.text'); if (!text) throw new Error('chat_say requires args.text');
sendSystemMessage(text, { nickname: name }); sendSystemMessage(text, { nickname: name, bot: true });
return { ok: true }; return { ok: true };
}, },
}; };
@@ -1,7 +1,7 @@
module.exports = { module.exports = {
id: 'neato_locate', id: 'neato_play_sound',
signature: 'neato_locate()', signature: 'neato_play_sound()',
description: 'Play Neato locate/chime action.', description: 'Play a sound/chime on the Neato robot.',
parameters: { type: 'object', properties: {}, additionalProperties: false }, parameters: { type: 'object', properties: {}, additionalProperties: false },
availability(ctx = {}) { availability(ctx = {}) {
const mode = String(ctx.mode || ''); const mode = String(ctx.mode || '');
@@ -8,7 +8,7 @@ const FFMPEG_BIN = process.env.FFMPEG_BIN || 'ffmpeg';
const SEGMENT_ROOT = path.join(resolveDataDir(), 'replay-segments'); const SEGMENT_ROOT = path.join(resolveDataDir(), 'replay-segments');
const SEGMENT_SECONDS = Math.max(1, Number.parseInt(process.env.REPLAY_SEGMENT_SECONDS || '1', 10)); const SEGMENT_SECONDS = Math.max(1, Number.parseInt(process.env.REPLAY_SEGMENT_SECONDS || '1', 10));
const BUFFER_SECONDS = Math.max(20, Number.parseInt(process.env.REPLAY_BUFFER_SECONDS || '45', 10)); const BUFFER_SECONDS = Math.max(20, Number.parseInt(process.env.REPLAY_BUFFER_SECONDS || '45', 10));
const CLEANUP_INTERVAL_MS = 10_000; const CLEANUP_INTERVAL_MS = Math.max(500, Number.parseInt(process.env.REPLAY_TICK_MS || '2000', 10));
const BUILD_DURATION_MS = Math.max(5000, Number.parseInt(process.env.REPLAY_DURATION_MS || '35000', 10)); const BUILD_DURATION_MS = Math.max(5000, Number.parseInt(process.env.REPLAY_DURATION_MS || '35000', 10));
const BUILD_GUARD_MS = Math.max(200, Number.parseInt(process.env.REPLAY_GUARD_MS || '1200', 10)); const BUILD_GUARD_MS = Math.max(200, Number.parseInt(process.env.REPLAY_GUARD_MS || '1200', 10));
const TARGET_FPS = Math.max(10, Number.parseInt(process.env.REPLAY_TARGET_FPS || '30', 10)); const TARGET_FPS = Math.max(10, Number.parseInt(process.env.REPLAY_TARGET_FPS || '30', 10));
+6 -1
View File
@@ -54,6 +54,11 @@ const replayBuilder = createReplayBuilder({
}); });
registerReplaySocketHooks({ tryTriggerReplay, validateSources, getDefaultWebSources }); registerReplaySocketHooks({ tryTriggerReplay, validateSources, getDefaultWebSources });
async function buildReplayVideoFresh(options = {}) {
await tick();
return replayBuilder.buildReplayVideo(options);
}
function getReplayHealthSnapshot() { function getReplayHealthSnapshot() {
return segmentStore.getReplayHealthSnapshot({ BUILD_DURATION_MS, roverManager, getRoomCameras }); return segmentStore.getReplayHealthSnapshot({ BUILD_DURATION_MS, roverManager, getRoomCameras });
} }
@@ -98,7 +103,7 @@ start().catch((err) => {
}); });
module.exports = { module.exports = {
buildReplayVideo: replayBuilder.buildReplayVideo, buildReplayVideo: buildReplayVideoFresh,
tryTriggerReplay, tryTriggerReplay,
getReplayState, getReplayState,
replayEvents, replayEvents,
@@ -52,6 +52,22 @@ function buildChatEventsForWindow(startMs, endMs, limit = 22, preWindowCount = 1
} }
function createReplayBuilder({ execFileAsync, fsp, ensureDir, renderSidebarVideo, getVideoEntriesForSource, getAudioEntriesForRover, overlapping }) { function createReplayBuilder({ execFileAsync, fsp, ensureDir, renderSidebarVideo, getVideoEntriesForSource, getAudioEntriesForRover, overlapping }) {
function resolveReplayWindow({ sources = [], nowMs, guardMs, durationMs }) {
const tentativeEnd = nowMs - guardMs;
const sourceEnds = [];
for (const source of sources) {
const sourceId = String(source.id);
const allEntries = getVideoEntriesForSource({ type: String(source.type), id: sourceId });
if (!Array.isArray(allEntries) || !allEntries.length) continue;
const bounded = allEntries.filter((entry) => Number.isFinite(entry?.endMs) && entry.endMs <= tentativeEnd);
if (!bounded.length) continue;
const latest = bounded.reduce((best, entry) => (entry.endMs > best.endMs ? entry : best), bounded[0]);
sourceEnds.push(latest.endMs);
}
const alignedEnd = sourceEnds.length ? Math.min(...sourceEnds) : tentativeEnd;
return { tEnd: alignedEnd, tStart: alignedEnd - durationMs };
}
async function concatFiles(inputPaths, outPath) { async function concatFiles(inputPaths, outPath) {
const listPath = `${outPath}.concat.txt`; const listPath = `${outPath}.concat.txt`;
const body = inputPaths.map((file) => `file '${file.replace(/'/g, "'\\''")}'`).join('\n'); const body = inputPaths.map((file) => `file '${file.replace(/'/g, "'\\''")}'`).join('\n');
@@ -74,8 +90,12 @@ function createReplayBuilder({ execFileAsync, fsp, ensureDir, renderSidebarVideo
async function buildReplayVideo({ sources = [], title = '', requester = '', includeSidebar = true } = {}) { async function buildReplayVideo({ sources = [], title = '', requester = '', includeSidebar = true } = {}) {
if (!Array.isArray(sources) || !sources.length) throw new Error('No replay sources selected'); if (!Array.isArray(sources) || !sources.length) throw new Error('No replay sources selected');
const tEnd = Date.now() - BUILD_GUARD_MS; const { tEnd, tStart } = resolveReplayWindow({
const tStart = tEnd - BUILD_DURATION_MS; sources,
nowMs: Date.now(),
guardMs: BUILD_GUARD_MS,
durationMs: BUILD_DURATION_MS,
});
const resolvedTitle = sanitizeReplayTitle(title, resolveDefaultReplayTitle(requester, sources)); const resolvedTitle = sanitizeReplayTitle(title, resolveDefaultReplayTitle(requester, sources));
const tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'mrr-replay-v2-')); const tmpDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'mrr-replay-v2-'));
@@ -211,6 +211,7 @@ function createRosterLifecycle(deps) {
return Array.from(rovers.values()).map((record) => ({ return Array.from(rovers.values()).map((record) => ({
id: record.id, id: record.id,
name: record.meta?.name || record.id, name: record.meta?.name || record.id,
description: record.meta?.description,
color: record.meta?.color || null, color: record.meta?.color || null,
battery: record.meta?.battery, battery: record.meta?.battery,
batteryState: record.batteryState, batteryState: record.batteryState,
@@ -13,6 +13,7 @@ const { getRoomCameras, roomCameraEvents } = require('../roomCameraService');
const { getState: getHomeAssistantState, homeAssistantEvents } = require('../homeAssistantService'); const { getState: getHomeAssistantState, homeAssistantEvents } = require('../homeAssistantService');
const { getState: getNeatoState, neatoEvents } = require('../neatoService'); const { getState: getNeatoState, neatoEvents } = require('../neatoService');
const { getState: getLiftState, liftEvents } = require('../liftService'); const { getState: getLiftState, liftEvents } = require('../liftService');
const { getVoteStatus: getOverseerVoteStatus } = require('../overseerControlService');
const { getNickname, nicknameEvents } = require('../nicknameService'); const { getNickname, nicknameEvents } = require('../nicknameService');
const { const {
getVerificationStateForSocket, getVerificationStateForSocket,
@@ -66,6 +67,7 @@ function buildUserEntry(socket) {
} }
function buildSession(socket) { function buildSession(socket) {
const overseerVote = getOverseerVoteStatus();
const users = Array.from(io.sockets.sockets.values()) const users = Array.from(io.sockets.sockets.values())
.map((sock) => buildUserEntry(sock)) .map((sock) => buildUserEntry(sock))
.filter(Boolean) .filter(Boolean)
@@ -124,6 +126,10 @@ function buildSession(socket) {
audioForward: getAudioForwardState(), audioForward: getAudioForwardState(),
audioLevels: getAudioLevels(), audioLevels: getAudioLevels(),
buttonBox: getButtonBoxState(), buttonBox: getButtonBoxState(),
overseerVote: {
...overseerVote,
preference: typeof socket?.data?.overseerEnabled === 'boolean' ? socket.data.overseerEnabled : true,
},
}; };
} }
@@ -111,11 +111,18 @@ function identifySocket(socket, payload = {}) {
} }
} }
if (Object.prototype.hasOwnProperty.call(payload, 'overseerEnabled')) {
data.overseerEnabled = Boolean(payload.overseerEnabled);
} else if (typeof data.overseerEnabled !== 'boolean') {
data.overseerEnabled = true;
}
const verification = reevaluateSocketVerification(socket); const verification = reevaluateSocketVerification(socket);
const deterrence = reevaluateSocketDeterrence(socket); const deterrence = reevaluateSocketDeterrence(socket);
emitChange('identify', { socketId: socket.id }); emitChange('identify', { socketId: socket.id });
return { return {
cookieUserId: data.cookieUserId, cookieUserId: data.cookieUserId,
overseerEnabled: Boolean(data.overseerEnabled),
isVerified: verification.isVerified, isVerified: verification.isVerified,
isDeterred: deterrence.isDeterred, isDeterred: deterrence.isDeterred,
reason: verification.reason, reason: verification.reason,
@@ -97,6 +97,7 @@ function createVerificationFlow(deps) {
return { return {
cookieUserId: normalizeCookieUserId(data.cookieUserId) || null, cookieUserId: normalizeCookieUserId(data.cookieUserId) || null,
nickname: getNickname(socket) || null, nickname: getNickname(socket) || null,
overseerEnabled: typeof data.overseerEnabled === 'boolean' ? data.overseerEnabled : true,
}; };
} }
+16 -6
View File
@@ -16,12 +16,14 @@ import {
} from './controls/index.js'; } from './controls/index.js';
import RoomCameraPanel from './components/RoomCameraPanel/index.jsx'; import RoomCameraPanel from './components/RoomCameraPanel/index.jsx';
import LogPanel from './components/LogPanel/index.jsx'; import LogPanel from './components/LogPanel/index.jsx';
import DriverVideoPanel from './components/DriverVideoPanel/index.jsx'; import DriverVideo from './components/DriverVideo/index.jsx';
import RightPaneTabs from './components/RightPaneTabs/index.jsx'; import RightPaneTabs from './components/RightPaneTabs/index.jsx';
import ModeGateOverlay from './components/ModeGateOverlay/index.jsx'; import ModeGateOverlay from './components/ModeGateOverlay/index.jsx';
import HomeAssistantControls from './components/HomeAssistantControls/index.jsx'; import HomeAssistantControls from './components/HomeAssistantControls/index.jsx';
import TurnAlertListener from './components/TurnAlertListener/index.jsx'; import TurnAlertListener from './components/TurnAlertListener/index.jsx';
import RawUserPilePanel from './components/RawUserPilePanel/index.jsx'; import RawUserPilePanel from './components/RawUserPilePanel/index.jsx';
import OverseerPreferencePanel from './components/OverseerPreferencePanel/index.jsx';
import SocialButtonsGrid from './components/SocialButtonsGrid/index.jsx';
import ChatPanel from './components/ChatPanel/index.jsx'; import ChatPanel from './components/ChatPanel/index.jsx';
import FullscreenPrompt from './components/FullscreenPrompt/index.jsx'; import FullscreenPrompt from './components/FullscreenPrompt/index.jsx';
import FloatingFullscreenButton from './components/FloatingFullscreenButton/index.jsx'; import FloatingFullscreenButton from './components/FloatingFullscreenButton/index.jsx';
@@ -75,7 +77,7 @@ function DesktopLayout({ layout, onOpenHelpOverlay }) {
return ( return (
<div className="flex h-full gap-0.5 overflow-hidden"> <div className="flex h-full gap-0.5 overflow-hidden">
<div className="flex min-w-0 flex-[1.22] flex-col gap-0.5 overflow-y-auto pr-0"> <div className="flex min-w-0 flex-[1.22] flex-col gap-0.5 overflow-y-auto pr-0">
<DriverVideoPanel /> <DriverVideo />
<TelemetryPanel /> <TelemetryPanel />
<LogPanel /> <LogPanel />
</div> </div>
@@ -141,8 +143,16 @@ function MobileFeatureTabs({
<TabPanels> <TabPanels>
<TabPanel id="chat"> <TabPanel id="chat">
<div className="space-y-0.5"> <div className="space-y-0.5">
<ChatPanel /> <ChatPanel nicknameLayout="stacked" />
<RawUserPilePanel /> <div className="space-y-0.5">
<div className="grid gap-0.5 md:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)]">
<SocialButtonsGrid />
</div>
<div className="grid gap-0.5 grid-cols-[minmax(0,1fr)_minmax(0,1fr)]">
<OverseerPreferencePanel />
<RawUserPilePanel hideNicknameForm />
</div>
</div>
</div> </div>
</TabPanel> </TabPanel>
<TabPanel id="vip" keepMounted> <TabPanel id="vip" keepMounted>
@@ -174,7 +184,7 @@ function MobileFeatureTabs({
function MobilePortraitLayout({ onOpenHelpOverlay, swapMobileControlColumns = false }) { function MobilePortraitLayout({ onOpenHelpOverlay, swapMobileControlColumns = false }) {
return ( return (
<div className="flex flex-col gap-0.5"> <div className="flex flex-col gap-0.5">
<DriverVideoPanel layoutFormat="mobile-portrait" /> <DriverVideo layoutFormat="mobile-portrait" />
<MobileControls swapColumns={swapMobileControlColumns} /> <MobileControls swapColumns={swapMobileControlColumns} />
<div className="grid gap-0.5 grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)]"> <div className="grid gap-0.5 grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)]">
<ReplaySourcesPanel panelId="replay-sources-mobile-portrait" /> <ReplaySourcesPanel panelId="replay-sources-mobile-portrait" />
@@ -203,7 +213,7 @@ function MobileLandscapeLayout({ onOpenHelpOverlay, swapMobileControlColumns = f
<section className="grid min-h-screen grid-cols-[minmax(0,0.7fr)_minmax(0,2.1fr)_minmax(0,0.7fr)] gap-0.5"> <section className="grid min-h-screen grid-cols-[minmax(0,0.7fr)_minmax(0,2.1fr)_minmax(0,0.7fr)] gap-0.5">
{firstColumn} {firstColumn}
<div> <div>
<DriverVideoPanel layoutFormat="mobile-landscape" /> <DriverVideo layoutFormat="mobile-landscape" />
<div className="grid gap-0.5 grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)]"> <div className="grid gap-0.5 grid-cols-[minmax(0,1fr)_minmax(0,1.4fr)]">
<ReplaySourcesPanel panelId="replay-sources-mobile-landscape" /> <ReplaySourcesPanel panelId="replay-sources-mobile-landscape" />
<RoverQueuesPanel /> <RoverQueuesPanel />
@@ -62,7 +62,7 @@ export function buildLlmConversationRowsFromMessages(modelMessages, rawOutput) {
nickname, nickname,
text: content, text: content,
role: 'spectator', role: 'spectator',
system: role === 'system', bot: role === 'system',
}, },
}; };
}); });
@@ -75,7 +75,7 @@ export function buildLlmConversationRowsFromMessages(modelMessages, rawOutput) {
nickname: 'LLM Output', nickname: 'LLM Output',
text: raw.trim() ? raw : '<empty>', text: raw.trim() ? raw : '<empty>',
role: 'spectator', role: 'spectator',
system: true, bot: true,
}, },
}); });
} }
@@ -7,6 +7,7 @@ import { useSocket } from '../../context/SocketContext.jsx';
import { useSettingsNamespace } from '../../settings/index.js'; import { useSettingsNamespace } from '../../settings/index.js';
import { AUDIO_SETTINGS_DEFAULTS } from '../../settings/namespaces.js'; import { AUDIO_SETTINGS_DEFAULTS } from '../../settings/namespaces.js';
import ButtonBoxTile from '../ButtonBoxTile/index.jsx'; import ButtonBoxTile from '../ButtonBoxTile/index.jsx';
import CardFrame from '../CardFrame/index.jsx';
const FLASH_MS = 420; const FLASH_MS = 420;
const REWARD_FLASH_MS = 1200; const REWARD_FLASH_MS = 1200;
@@ -126,10 +127,7 @@ export default function ButtonBoxPanel() {
}, [effectiveAlertVolume, socket]); }, [effectiveAlertVolume, socket]);
return ( return (
<section className="panel-section space-y-0.5 text-base"> <CardFrame title="Button Box" bodyClassName="space-y-0.5 text-base">
<header className="panel-muted text-center text-sm">
<p>Button Box</p>
</header>
<div className="grid grid-cols-4 gap-0.5"> <div className="grid grid-cols-4 gap-0.5">
{buttons.map((button) => { {buttons.map((button) => {
const id = Number(button.id); const id = Number(button.id);
@@ -155,6 +153,6 @@ export default function ButtonBoxPanel() {
); );
})} })}
</div> </div>
</section> </CardFrame>
); );
} }
+89
View File
@@ -0,0 +1,89 @@
import { useSessionSelector } from '../../context/SessionContext.jsx';
// Utilities
function cx(...values) {
return values.filter(Boolean).join(' ');
}
// Color helpers
function hexToRgb(hex) {
const raw = String(hex || '').trim();
const normalized = raw.startsWith('#') ? raw.slice(1) : raw;
if (!/^[0-9a-fA-F]{3}$|^[0-9a-fA-F]{6}$/.test(normalized)) return null;
const expanded =
normalized.length === 3
? normalized
.split('')
.map((ch) => ch + ch)
.join('')
: normalized;
return {
r: Number.parseInt(expanded.slice(0, 2), 16),
g: Number.parseInt(expanded.slice(2, 4), 16),
b: Number.parseInt(expanded.slice(4, 6), 16),
};
}
function rgba(rgb, alpha) {
return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`;
}
// Component
export default function CardFrame({
title = '',
meta = null,
actions = null,
hideHeader = false,
className = '',
headerClassName = '',
bodyClassName = '',
fillHeight = false,
clipOverflow = true,
children,
}) {
const showHeader = !hideHeader && (title || meta != null || actions);
const ownRoverColor = useSessionSelector((state) => {
const roverId = String(state.session?.assignment?.roverId || '').trim();
if (!roverId) return null;
const roster = Array.isArray(state.session?.roster) ? state.session.roster : [];
const rover = roster.find((entry) => String(entry?.id) === roverId);
return rover?.color || null;
});
const accentRgb = hexToRgb(ownRoverColor);
const cardStyle = accentRgb ? { borderColor: rgba(accentRgb, 0.35) } : undefined;
const headerStyle = accentRgb
? {
backgroundImage: `linear-gradient(90deg, rgba(23,23,23,0.96) 0%, rgba(38,38,38,0.94) 58%, ${rgba(accentRgb, 0.18)} 100%)`,
}
: undefined;
return (
<section
className={cx(
'panel-section border border-neutral-500/60 bg-neutral-900/95 shadow-[0_1px_0_rgba(255,255,255,0.05)_inset,0_10px_24px_rgba(0,0,0,0.28)]',
clipOverflow ? 'overflow-hidden' : 'overflow-visible',
fillHeight && 'flex h-full min-h-0 flex-col',
className,
)}
style={cardStyle}
>
{showHeader ? (
// Header row
<header
className={cx(
'flex items-center justify-between gap-0.5 border-b border-neutral-500/50 bg-gradient-to-r from-neutral-800 via-neutral-700 to-neutral-600 px-0.5 py-0.5',
headerClassName,
)}
style={headerStyle}
>
<div className="flex min-w-0 items-center gap-0.5">
{title ? <p className="m-0 text-[0.78rem] font-semibold leading-none text-neutral-50">{title}</p> : null}
{meta != null ? <span className="text-[0.68rem] font-medium leading-none text-neutral-200">{meta}</span> : null}
</div>
{actions ? <div className="flex flex-wrap items-center justify-end gap-0.5">{actions}</div> : null}
</header>
) : null}
<div className={cx(fillHeight && 'flex flex-1 min-h-0 flex-col', bodyClassName)}>{children}</div>
</section>
);
}
+80 -23
View File
@@ -1,8 +1,10 @@
// Chat Message Row // Chat Message Row
// Purpose: Defines the Chat Message Row module and the local helpers/components used in this file. // Purpose: Defines the Chat Message Row module and the local helpers/components used in this file.
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit. // Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import { useState } from 'react';
import { FaDiscord } from 'react-icons/fa'; import { FaDiscord } from 'react-icons/fa';
import { roverBadgeStyle } from '../../lib/roverColor.js'; import { roverBadgeStyle } from '../../lib/roverColor.js';
import { useSessionSelector } from '../../context/SessionContext.jsx';
function roleColors(role) { function roleColors(role) {
switch (role) { switch (role) {
@@ -17,8 +19,8 @@ function roleColors(role) {
} }
} }
function isBotSystemMessage(message) { function isBotMessage(message) {
return Boolean(message?.system); return Boolean(message?.bot);
} }
function formatTime(ts) { function formatTime(ts) {
@@ -34,7 +36,7 @@ function DiscordAvatar({ guildIconUrl, userAvatarUrl, label }) {
if (!guildIconUrl && !userAvatarUrl) return null; if (!guildIconUrl && !userAvatarUrl) return null;
return ( return (
<span <span
className="flex h-4 w-4 overflow-hidden rounded-full border border-slate-700/80" className="flex h-4 w-4 shrink-0 overflow-hidden rounded-none border border-slate-700/80"
title={label} title={label}
> >
<span <span
@@ -65,51 +67,65 @@ function DiscordAvatar({ guildIconUrl, userAvatarUrl, label }) {
); );
} }
export function ChatIdentity({ message }) { function ProfileAvatar({ imageUrl, label }) {
if (!imageUrl) return null;
return (
<span className="flex h-4 w-4 shrink-0 overflow-hidden rounded-none border border-slate-700/80" title={label}>
<span
className="h-full w-full bg-cover bg-center bg-no-repeat"
style={{ backgroundImage: `url(${imageUrl})` }}
/>
</span>
);
}
export function ChatIdentity({ message, toolsToggle = null }) {
const discordLabel = message.fromDiscord const discordLabel = message.fromDiscord
? `${message.discordGuildName || 'Discord'} · ${displayName(message)}` ? `${message.discordGuildName || 'Discord'} · ${displayName(message)}`
: null; : null;
const isBot = isBotSystemMessage(message); const isBot = isBotMessage(message);
const nameClass = isBot ? 'text-emerald-300' : roleColors(message.role); const nameClass = isBot ? 'text-emerald-300' : roleColors(message.role);
return ( return (
<> <span className="inline-flex min-w-0 items-center gap-0.5 align-middle">
{message.fromDiscord ? ( {message.fromDiscord ? (
<> <FaDiscord className="h-4 w-4 shrink-0 text-indigo-200" />
<FaDiscord className="h-3.5 w-3.5 text-indigo-200" /> ) : null}
<span className={`font-semibold text-[0.85rem] ${nameClass}`}>
{displayName(message)}
</span>
<ProfileAvatar imageUrl={message.profileImage} label={discordLabel || displayName(message)} />
{!message.profileImage ? (
<DiscordAvatar <DiscordAvatar
guildIconUrl={message.discordGuildIconUrl} guildIconUrl={message.discordGuildIconUrl}
userAvatarUrl={message.discordUserAvatarUrl} userAvatarUrl={message.discordUserAvatarUrl}
label={discordLabel} label={discordLabel}
/> />
</>
) : null} ) : null}
<span className={`font-semibold text-[0.85rem] ${nameClass}`}>
{displayName(message)}
</span>
{isBot ? ( {isBot ? (
<span className="rounded bg-emerald-900/60 px-1 text-[0.65rem] font-semibold uppercase tracking-wide text-white"> <span className="shrink-0 rounded bg-emerald-900/60 px-1 text-[0.65rem] font-semibold uppercase tracking-wide text-white">
bot bot
</span> </span>
) : null} ) : null}
{message.roverId && ( {message.roverId && (
<span <span
className="rounded bg-slate-800 px-1 text-[0.7rem]" className="shrink-0 rounded bg-slate-800 px-1 text-[0.7rem]"
style={roverBadgeStyle(message.roverColor, 0.14)} style={roverBadgeStyle(message.roverColor, 0.14)}
> >
{message.roverId} {message.roverId}
</span> </span>
)} )}
</> {toolsToggle}
</span>
); );
} }
function chatRowClass(message) { function chatRowClass(message) {
if (isBotSystemMessage(message)) { if (isBotMessage(message)) {
return 'surface-muted relative flex flex-wrap items-start gap-0.5 border border-emerald-500/40 bg-emerald-900/15 text-sm'; return 'surface-muted flex flex-col gap-0.5 border border-emerald-500/40 bg-emerald-900/15 text-sm';
} }
const isAdmin = const isAdmin =
message.role === 'admin' || message.role === 'lockdown' || message.role === 'lockdown-admin'; message.role === 'admin' || message.role === 'lockdown' || message.role === 'lockdown-admin';
return `surface-muted relative flex flex-wrap items-start gap-0.5 text-sm ${ return `surface-muted flex flex-col gap-0.5 text-sm ${
isAdmin isAdmin
? 'border border-amber-400/30' ? 'border border-amber-400/30'
: message.fromDiscord : message.fromDiscord
@@ -119,19 +135,60 @@ function chatRowClass(message) {
} }
export default function ChatMessageRow({ message }) { export default function ChatMessageRow({ message }) {
const isBot = isBotSystemMessage(message); const isBot = isBotMessage(message);
const role = useSessionSelector((state) => state.session?.role || null);
const isSpectator = role === 'spectator';
const [open, setOpen] = useState(false);
const isOpen = isSpectator || open;
const toolCalls = Array.isArray(message?.toolCalls) ? message.toolCalls : [];
const hasText = Boolean(String(message?.text || '').trim());
const toolsToggle =
toolCalls.length > 0 ? (
<button
type="button"
className="shrink-0 rounded border border-slate-600/70 bg-slate-800/60 px-1 py-[1px] text-[0.65rem] text-slate-200 hover:bg-slate-700/70"
onClick={() => {
if (isSpectator) return;
setOpen((v) => !v);
}}
>
{isOpen ? '▼' : '▶'} Tools ({toolCalls.length})
</button>
) : null;
return ( return (
<div className={chatRowClass(message)}> <div className={chatRowClass(message)}>
<ChatIdentity message={message} /> <div className="flex w-full items-start gap-0.5">
<span <span
className={`break-words leading-tight whitespace-pre-wrap ${isBot ? 'text-emerald-100' : 'text-slate-100'}`} className={`min-w-0 flex-1 break-words leading-tight whitespace-pre-wrap ${isBot ? 'text-emerald-100' : 'text-slate-100'}`}
> >
{message.text} <ChatIdentity message={message} toolsToggle={toolsToggle} />
{!isOpen && hasText ? ` ${message.text}` : ''}
</span> </span>
<span className="absolute bottom-0.5 right-1 text-[0.65rem] text-slate-400/60"> <span className="shrink-0 text-[0.65rem] text-slate-400/60">
{formatTime(message.ts)} {formatTime(message.ts)}
</span> </span>
</div> </div>
{isOpen && toolCalls.length > 0 ? (
<div className="w-full rounded border border-slate-700/70 bg-slate-900/70 p-0.5 text-[0.68rem] text-slate-200">
{toolCalls.map((entry, idx) => {
const status = String(entry?.status || 'unknown');
const statusLabel = status === 'ok' ? 'ok' : status === 'blocked' ? 'blocked' : status === 'error' ? 'error' : 'unknown';
const argsText = JSON.stringify(entry?.args && typeof entry.args === 'object' ? entry.args : {});
return (
<div key={`${entry?.tool || 'tool'}-${idx}`} className="mb-0.5 last:mb-0">
<div>{statusLabel} {entry?.tool || 'unknown'} args={argsText}</div>
{entry?.error ? <div className="text-rose-300">error: {String(entry.error)}</div> : null}
</div>
);
})}
</div>
) : null}
{isOpen && hasText ? (
<div className={`w-full break-words leading-tight whitespace-pre-wrap ${isBot ? 'text-emerald-100' : 'text-slate-100'}`}>
{message.text}
</div>
) : null}
</div>
); );
} }
+27 -6
View File
@@ -7,6 +7,8 @@ import { useSessionSelector } from '../../context/SessionContext.jsx';
import { useSettingsNamespace } from '../../settings/index.js'; import { useSettingsNamespace } from '../../settings/index.js';
import ChatMessageRow from '../ChatMessageRow/index.jsx'; import ChatMessageRow from '../ChatMessageRow/index.jsx';
import ChatTypingRow from '../ChatTypingRow/index.jsx'; import ChatTypingRow from '../ChatTypingRow/index.jsx';
import CardFrame from '../CardFrame/index.jsx';
import NicknameForm from '../NicknameForm/index.jsx';
const FLITE_VOICES = ['kal', 'rms', 'slt', 'ksp', 'bdl']; const FLITE_VOICES = ['kal', 'rms', 'slt', 'ksp', 'bdl'];
const ESPEAK_PITCHES = Array.from({ length: 10 }, (_, idx) => idx * 10); const ESPEAK_PITCHES = Array.from({ length: 10 }, (_, idx) => idx * 10);
@@ -16,6 +18,8 @@ export default function ChatPanel({
hideSpectatorNotice = false, hideSpectatorNotice = false,
fillHeight = false, fillHeight = false,
allowSpectatorInput = false, allowSpectatorInput = false,
title = 'Chat and TTS',
nicknameLayout = 'inline',
}) { }) {
const role = useSessionSelector((state) => state.session?.role || null); const role = useSessionSelector((state) => state.session?.role || null);
const currentRoverId = useSessionSelector((state) => state.session?.assignment?.roverId || null); const currentRoverId = useSessionSelector((state) => state.session?.assignment?.roverId || null);
@@ -103,9 +107,16 @@ export default function ChatPanel({
} }
const listClass = fillHeight ? 'flex-1 min-h-0 overflow-y-auto' : 'h-48 overflow-y-auto'; const listClass = fillHeight ? 'flex-1 min-h-0 overflow-y-auto' : 'h-48 overflow-y-auto';
const isStackedNickname = nicknameLayout === 'stacked';
return ( return (
<section className={`panel-section space-y-0.5 text-base ${fillHeight ? 'flex h-full flex-col overflow-hidden' : ''}`}> <CardFrame
title={title}
hideHeader={!title}
fillHeight={fillHeight}
bodyClassName="space-y-0.5 text-base"
>
<div className={`surface overflow-y-auto space-y-0.5 px-0 ${listClass}`} ref={listRef}> <div className={`surface overflow-y-auto space-y-0.5 px-0 ${listClass}`} ref={listRef}>
{sorted.length === 0 && typingRows.length === 0 ? ( {sorted.length === 0 && typingRows.length === 0 ? (
<p className="text-sm text-slate-500">No messages yet.</p> <p className="text-sm text-slate-500">No messages yet.</p>
@@ -117,9 +128,15 @@ export default function ChatPanel({
))} ))}
</div> </div>
{!hideInput && ( {!hideInput && (
<form className="flex flex-wrap items-stretch gap-0.5" onSubmit={handleSend}> <form
className={`flex items-stretch gap-0.5 ${isStackedNickname ? 'flex-col' : 'flex-wrap'}`}
onSubmit={handleSend}
>
<div className={isStackedNickname ? 'w-full' : 'w-[9rem] sm:w-[10rem] shrink-0'}>
<NicknameForm compact />
</div>
<input <input
className="field-input flex-1 min-w-[10rem]" className={`field-input ${isStackedNickname ? 'w-full min-w-0' : 'flex-1 min-w-[10rem]'}`}
value={draft} value={draft}
onChange={(e) => { onChange={(e) => {
const next = e.target.value; const next = e.target.value;
@@ -146,7 +163,11 @@ export default function ChatPanel({
disabled={!canChat} disabled={!canChat}
/> />
{ttsSupported && ( {ttsSupported && (
<div className="flex flex-wrap items-center gap-0.5 basis-full sm:basis-auto"> <div
className={`flex flex-wrap items-center gap-0.5 ${
isStackedNickname ? 'w-full' : 'basis-full sm:basis-auto'
}`}
>
<label className="flex items-center gap-0.5 text-xs text-slate-300"> <label className="flex items-center gap-0.5 text-xs text-slate-300">
<input <input
type="checkbox" type="checkbox"
@@ -206,12 +227,12 @@ export default function ChatPanel({
<button <button
type="submit" type="submit"
disabled={!canChat || sending} disabled={!canChat || sending}
className="button-dark h-full disabled:opacity-50 self-stretch" className={`button-dark disabled:opacity-50 ${isStackedNickname ? 'w-full h-8' : 'h-full self-stretch'}`}
> >
{sending ? '...' : 'Send'} {sending ? '...' : 'Send'}
</button> </button>
</form> </form>
)} )}
</section> </CardFrame>
); );
} }
+1 -1
View File
@@ -5,7 +5,7 @@ import { ChatIdentity, chatRowClass } from '../ChatMessageRow/index.jsx';
export default function ChatTypingRow({ message }) { export default function ChatTypingRow({ message }) {
return ( return (
<div className={`${chatRowClass(message)} italic opacity-80 border-slate-600/40 bg-slate-900/40`}> <div className={`${chatRowClass(message)} !flex-row items-center italic opacity-80 border-slate-600/40 bg-slate-900/40`}>
<ChatIdentity message={message} /> <ChatIdentity message={message} />
<span className="text-slate-300">typing...</span> <span className="text-slate-300">typing...</span>
</div> </div>
+31 -20
View File
@@ -5,6 +5,7 @@ import { useMemo, useState } from 'react';
import { useControlSystem } from '../../controls/index.js'; import { useControlSystem } from '../../controls/index.js';
import { useTelemetryFrame } from '../../context/TelemetryContext.jsx'; import { useTelemetryFrame } from '../../context/TelemetryContext.jsx';
import { formatKeyLabel } from '../../controls/keymapUtils.js'; import { formatKeyLabel } from '../../controls/keymapUtils.js';
import { useManualDockAssist } from '../../features/manualDockAssist/useManualDockAssist.js';
export function deriveDriveDockState(frame) { export function deriveDriveDockState(frame) {
const sensors = frame?.sensors || {}; const sensors = frame?.sensors || {};
@@ -68,7 +69,7 @@ function DockModal({ instructions, onConfirm, onCancel, pending }) {
<div className="fixed inset-0 z-40 flex items-center justify-center bg-black/70 p-1"> <div className="fixed inset-0 z-40 flex items-center justify-center bg-black/70 p-1">
<div className="surface w-full max-w-md space-y-0.5 border border-indigo-700 bg-indigo-950/90 p-1 text-slate-100 shadow-2xl"> <div className="surface w-full max-w-md space-y-0.5 border border-indigo-700 bg-indigo-950/90 p-1 text-slate-100 shadow-2xl">
<div className="space-y-0.5"> <div className="space-y-0.5">
<p className="text-lg font-semibold text-indigo-50">Dock Rover</p> <p className="text-lg font-semibold text-indigo-50">Manual Docking Assist</p>
<p className="text-sm text-slate-200">{instructions.summary}</p> <p className="text-sm text-slate-200">{instructions.summary}</p>
<StepList steps={instructions.steps} tone="indigo" /> <StepList steps={instructions.steps} tone="indigo" />
</div> </div>
@@ -86,7 +87,7 @@ function DockModal({ instructions, onConfirm, onCancel, pending }) {
onClick={onConfirm} onClick={onConfirm}
className="bg-indigo-600 px-0.5 py-1 font-semibold text-indigo-50 transition hover:bg-indigo-500 disabled:opacity-50" className="bg-indigo-600 px-0.5 py-1 font-semibold text-indigo-50 transition hover:bg-indigo-500 disabled:opacity-50"
> >
{pending ? 'Docking…' : 'Confirm Dock'} {pending ? 'Starting…' : 'Enter Assist'}
</button> </button>
</div> </div>
</div> </div>
@@ -106,12 +107,14 @@ export default function DriveDockAction({
state: { roverId, keymap }, state: { roverId, keymap },
actions, actions,
} = useControlSystem(); } = useControlSystem();
const dockAssist = useManualDockAssist();
const frame = useTelemetryFrame(roverId); const frame = useTelemetryFrame(roverId);
const state = driveDockState ?? deriveDriveDockState(frame); const state = driveDockState ?? deriveDriveDockState(frame);
const { driving, docked, charging, dockingInProgress } = state; const { driving, docked, charging, dockingInProgress } = state;
const [pending, setPending] = useState(null); const [pending, setPending] = useState(null);
const [confirmOpen, setConfirmOpen] = useState(false); const [confirmOpen, setConfirmOpen] = useState(false);
const [showModal, setShowModal] = useState(false); const [showModal, setShowModal] = useState(false);
const manualAssistActive = Boolean(dockAssist.active);
const driveDisabled = !roverId || pending !== null; const driveDisabled = !roverId || pending !== null;
const dockDisabled = !roverId || pending !== null; const dockDisabled = !roverId || pending !== null;
@@ -120,10 +123,13 @@ export default function DriveDockAction({
const dockKeyLabel = formatKeyLabel(keymap?.dockMacro?.[0]); const dockKeyLabel = formatKeyLabel(keymap?.dockMacro?.[0]);
const dockInstructions = { const dockInstructions = {
summary: 'You are about to trigger an automatic docking attempt! To have a successful dock:', summary: 'Use assist mode to manually line up with the dock.',
steps: ['Line up the rover straight in front of the dock', 'Make sure the rover is about one foot or half a meter away from the dock', 'Press Confirm Dock to begin the docking process'], steps: [
'Line up the center dot of your rover with the center of the dock',
'The UI will indicate when you are successfully docked',
'When good contact is made, the dock will stop flashing.',
],
}; };
const dockButtonCaption = 'Click this button to initate auto-dock.';
const startDriveInstructions = { const startDriveInstructions = {
summary: 'You must enable driving mode before you can move the rover.', summary: 'You must enable driving mode before you can move the rover.',
@@ -131,13 +137,14 @@ export default function DriveDockAction({
}; };
const dockValue = docked ? 'Docked' : 'Undocked'; const dockValue = docked ? 'Docked' : 'Undocked';
const dockTone = docked ? 'good' : 'bad'; const dockTone = docked ? 'good' : 'bad';
const chargeValue = charging ? 'Charging' : docked ? 'Charging in 5s' : '—'; const chargeValue = charging ? 'Charging' : docked ? 'Charging soon...' : '—';
const chargeTone = charging ? 'good' : docked ? 'warn' : 'bad'; const chargeTone = charging ? 'good' : docked ? 'warn' : 'bad';
const handleReturnToDrive = async () => { const handleReturnToDrive = async () => {
if (!roverId || pending) return; if (!roverId || pending) return;
setPending('drive'); setPending('drive');
try { try {
dockAssist.exitAssist();
actions.setMode('drive'); actions.setMode('drive');
await actions.runMacro('drive-sequence'); await actions.runMacro('drive-sequence');
} catch (err) { } catch (err) {
@@ -153,6 +160,7 @@ export default function DriveDockAction({
setShowModal(false); setShowModal(false);
setPending('drive'); setPending('drive');
try { try {
dockAssist.exitAssist();
actions.setMode('drive'); actions.setMode('drive');
await actions.runMacro('drive-sequence'); await actions.runMacro('drive-sequence');
} catch (err) { } catch (err) {
@@ -166,8 +174,7 @@ export default function DriveDockAction({
if (!roverId || pending) return; if (!roverId || pending) return;
setPending('dock'); setPending('dock');
try { try {
actions.setMode('dock'); dockAssist.enterAssist();
await actions.runMacro('seek-dock');
} catch (err) { } catch (err) {
alert(err.message); alert(err.message);
} finally { } finally {
@@ -179,6 +186,10 @@ export default function DriveDockAction({
const handleOpenDock = () => { const handleOpenDock = () => {
if (dockDisabled) return; if (dockDisabled) return;
if (manualAssistActive) {
dockAssist.exitAssist();
return;
}
setShowModal(true); setShowModal(true);
setConfirmOpen(true); setConfirmOpen(true);
}; };
@@ -188,7 +199,6 @@ export default function DriveDockAction({
const ctaText = 'text-center'; const ctaText = 'text-center';
const ctaLayout = 'items-center justify-between'; const ctaLayout = 'items-center justify-between';
const compactLayout = 'items-center justify-center'; const compactLayout = 'items-center justify-center';
const ctaTextAndLayout = `${ctaText} ${ctaLayout}`;
const ctaSize = isMobile ? 'text-sm font-semibold' : ''; const ctaSize = isMobile ? 'text-sm font-semibold' : '';
const emeraldCta = const emeraldCta =
'border-emerald-300/70 bg-emerald-800 text-emerald-50 hover:bg-emerald-700 focus-visible:ring-emerald-300'; 'border-emerald-300/70 bg-emerald-800 text-emerald-50 hover:bg-emerald-700 focus-visible:ring-emerald-300';
@@ -196,6 +206,8 @@ export default function DriveDockAction({
'border-amber-300/70 bg-amber-900 text-amber-50 hover:bg-amber-800 focus-visible:ring-amber-300'; 'border-amber-300/70 bg-amber-900 text-amber-50 hover:bg-amber-800 focus-visible:ring-amber-300';
const indigoCta = const indigoCta =
'border-indigo-300/70 bg-indigo-900 text-indigo-50 hover:bg-indigo-800 focus-visible:ring-indigo-300'; 'border-indigo-300/70 bg-indigo-900 text-indigo-50 hover:bg-indigo-800 focus-visible:ring-indigo-300';
const cyanCta =
'border-cyan-300/70 bg-cyan-900 text-cyan-50 hover:bg-cyan-800 focus-visible:ring-cyan-300';
const orangeCta = const orangeCta =
'border-amber-300/70 bg-amber-900 text-amber-50 hover:bg-amber-800 focus-visible:ring-amber-300'; 'border-amber-300/70 bg-amber-900 text-amber-50 hover:bg-amber-800 focus-visible:ring-amber-300';
const forceExpanded = dockingInProgress; const forceExpanded = dockingInProgress;
@@ -243,8 +255,8 @@ export default function DriveDockAction({
if (dockingInProgress) { if (dockingInProgress) {
const inProgressCopy = { const inProgressCopy = {
summary: 'If the rover is failing to dock, click to drive and try again.', summary: 'The rover is currently attempting to dock itself due to being idle.',
steps: ['The rover should be slowly wiggling towards the dock', 'If it is obviously not working, press this button to enter driving mode and try again'], steps: ['Click to return to driving mode.'],
}; };
return ( return (
@@ -257,7 +269,7 @@ export default function DriveDockAction({
> >
<div className="space-y-0.5 w-full"> <div className="space-y-0.5 w-full">
<div className="flex w-full flex-col items-center gap-0.25"> <div className="flex w-full flex-col items-center gap-0.25">
<span className="text-base font-semibold text-amber-50 md:text-lg">Docking in Progress</span> <span className="text-base font-semibold text-amber-50 md:text-lg">Attempting to auto-dock...</span>
{/* {!isMobile && expanded ? ( */} {/* {!isMobile && expanded ? ( */}
{expanded ? ( {expanded ? (
<div className="flex flex-wrap items-center justify-center gap-0.5"> <div className="flex flex-wrap items-center justify-center gap-0.5">
@@ -292,32 +304,31 @@ export default function DriveDockAction({
className={ className={
isMobile isMobile
? `flex w-full ${baseCardClasses} ${compactHeight} ${ctaText} ${layoutClass} ${ctaSize} ${ ? `flex w-full ${baseCardClasses} ${compactHeight} ${ctaText} ${layoutClass} ${ctaSize} ${
compactDockedDriving ? orangeCta : indigoCta manualAssistActive ? cyanCta : compactDockedDriving ? orangeCta : indigoCta
}` }`
: `${baseCardClasses} ${filledHeight} ${ctaText} ${ctaLayout} ${ctaSize} ${indigoCta}` : `${baseCardClasses} ${filledHeight} ${ctaText} ${ctaLayout} ${ctaSize} ${manualAssistActive ? cyanCta : indigoCta}`
} }
> >
<div className="flex w-full flex-col items-center gap-0.25"> <div className="flex w-full flex-col items-center gap-0.25">
<span className="text-base font-semibold text-indigo-50 md:text-lg"> <span className="text-base font-semibold text-indigo-50 md:text-lg">
{compactDockedDriving ? 'Docked!' : 'Dock and Charge'} {compactDockedDriving ? 'Docked!' : manualAssistActive ? 'Exit Docking Assist' : 'Dock and charge'}
</span> </span>
{!isMobile && expanded ? ( {!isMobile && expanded ? (
<div className="flex flex-wrap items-center justify-center gap-0.5"> <div className="flex flex-wrap items-center justify-center gap-0.5">
{dockKeyLabel ? <KeyPill label={dockKeyLabel} /> : null} {dockKeyLabel ? <KeyPill label={dockKeyLabel} /> : null}
<ActionPill label="Click to begin docking" tone="indigo" /> <ActionPill label={manualAssistActive ? 'Click to exit assist' : 'Click to enable assist'} tone="indigo" />
</div> </div>
) : null} ) : null}
</div> </div>
{!isMobile && expanded && ( {!isMobile && expanded && (
<> <>
<p className="text-sm text-indigo-50/90">{dockButtonCaption}</p> <p className="text-sm text-indigo-50/90">
Get near a dock and press this button to enter docking assist mode.
</p>
<div className="flex w-full flex-1 flex-col gap-0.5 self-stretch"> <div className="flex w-full flex-1 flex-col gap-0.5 self-stretch">
<StatusRow label="Dock" value={dockValue} tone={dockTone} /> <StatusRow label="Dock" value={dockValue} tone={dockTone} />
<StatusRow label="Charge" value={chargeValue} tone={chargeTone} /> <StatusRow label="Charge" value={chargeValue} tone={chargeTone} />
</div> </div>
<div className="text-xs text-indigo-100/80">
Line up straight, about 1 foot away, before docking.
</div>
</> </>
)} )}
</button> </button>
@@ -0,0 +1,63 @@
import { useSessionSelector } from '../../context/SessionContext.jsx';
import RoverMediaPlayer from '../RoverMediaPlayer/index.jsx';
import { useControlSystem } from '../../controls/index.js';
import { useDriverVideoModePolicy } from '../../hooks/useDriverVideoModePolicy.js';
import TurnsOverlay from '../HudOverlays/TurnsOverlay/index.jsx';
import HudOverlay from '../HudOverlays/HudOverlay/index.jsx';
import ManualDockAssistOverlay from '../HudOverlays/ManualDockAssistOverlay/index.jsx';
import RoverDescriptionOverlay from '../HudOverlays/RoverDescriptionOverlay/index.jsx';
import OvercurrentOverlay from '../HudOverlays/OvercurrentOverlay/index.jsx';
import LowBatteryOverlay from '../HudOverlays/LowBatteryOverlay/index.jsx';
import DriverBottomStrip from '../HudOverlays/DriverBottomStrip/index.jsx';
import HudChatInput from '../HudOverlays/HudChatInput/index.jsx';
export default function DriverVideo({ layoutFormat = 'desktop' }) {
const roverId = useSessionSelector((state) => state.session?.assignment?.roverId ?? null);
const videoMode = useDriverVideoModePolicy(roverId);
const {
state: { lastControlIntentAt },
} = useControlSystem();
if (!roverId) {
return (
<section className="panel">
<div className="panel-muted content-center text-center text-sm text-slate-400 aspect-[4/3]">
<p>You are not assigned to a rover.</p>
<p className="mt-0">
<a href="/spectate" className="text-blue-400 underline hover:text-blue-500">
Click here to visit the spectator page.
</a>
</p>
</div>
</section>
);
}
const mobileHud = layoutFormat !== 'desktop';
return (
<section className="panel">
<div className="flex flex-col gap-0.5">
<div className="relative w-full overflow-hidden bg-black aspect-[4/3]">
<RoverMediaPlayer roverId={roverId} videoMode={videoMode} />
<TurnsOverlay mobileHud={mobileHud} />
<RoverDescriptionOverlay
variant="default"
mobileHud={mobileHud}
controlIntentAt={lastControlIntentAt}
/>
<HudOverlay
layoutFormat={layoutFormat}
variant="default"
mobileHud={mobileHud}
labelScale={1}
/>
<ManualDockAssistOverlay mobileHud={mobileHud} />
<HudChatInput compact={mobileHud} />
<OvercurrentOverlay compact={mobileHud} />
<LowBatteryOverlay compact={mobileHud} />
</div>
<DriverBottomStrip mobileHud={mobileHud} />
</div>
</section>
);
}
@@ -1,155 +0,0 @@
// Driver Video Panel
// Purpose: Defines the Driver Video Panel module and the local helpers/components used in this file.
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import { useEffect, useMemo, useRef, useState } from 'react';
import { useSessionSelector } from '../../context/SessionContext.jsx';
import { useTelemetryFrame } from '../../context/TelemetryContext.jsx';
import { useVideoRequests } from '../../hooks/useVideoRequests.js';
import { useRoverSnapshots } from '../../hooks/useRoverSnapshots.js';
import { useControlSystem } from '../../controls/index.js';
import VideoTile from '../VideoTile/index.jsx';
export default function DriverVideoPanel({layoutFormat = 'desktop'}) {
const mode = useSessionSelector((state) => state.session?.mode || null);
const roverId = useSessionSelector((state) => state.session?.assignment?.roverId ?? null);
const roster = useSessionSelector((state) => state.session?.roster ?? []);
const turnQueues = useSessionSelector((state) => state.session?.turnQueues ?? {});
const socketId = useSessionSelector((state) => state.session?.socketId || null);
const activeDrivers = useSessionSelector((state) => state.session?.activeDrivers ?? {});
const {
state: { song, lastControlIntentAt },
overcurrentLimiter,
} = useControlSystem();
const [now, setNow] = useState(() => Date.now());
const [turnCueVisible, setTurnCueVisible] = useState(false);
const [turnCueStartAt, setTurnCueStartAt] = useState(null);
const lastTurnRef = useRef({ active: false, roverId: null });
useEffect(() => {
if (mode !== 'turns') {
return undefined;
}
const timer = setInterval(() => setNow(Date.now()), 250);
return () => clearInterval(timer);
}, [mode]);
const rosterEntry =
roverId && roster ? roster.find((item) => String(item.id) === String(roverId)) : null;
const hasAudio = Boolean(rosterEntry?.media?.audioPublishUrl);
const turnInfo = roverId ? turnQueues?.[roverId] : null;
const activeDriverId = roverId ? activeDrivers?.[roverId] : null;
const isActiveDriver = Boolean(socketId && activeDriverId === socketId);
const nextDriverId = useMemo(() => {
const queue = turnInfo?.queue || [];
if (!queue.length || !turnInfo?.current || queue.length <= 1) return null;
const idx = queue.findIndex((id) => id === turnInfo.current);
if (idx === -1) {
return queue[0] || null;
}
return queue[(idx + 1) % queue.length] || null;
}, [turnInfo?.queue, turnInfo?.current]);
const isNextDriver = Boolean(socketId && nextDriverId === socketId);
const deadline = turnInfo?.deadline || null;
const idleDeadline = turnInfo?.idleDeadline || null;
const msUntilTurn = deadline ? deadline - now : null;
const msUntilIdleSkip = idleDeadline ? idleDeadline - now : null;
const isPreSwitchWindow =
mode === 'turns' && isNextDriver && msUntilTurn != null && msUntilTurn <= 5000 && msUntilTurn > 0;
const shouldShowVideo = mode !== 'turns' || isActiveDriver || isPreSwitchWindow;
const turnSeconds =
msUntilTurn != null && Number.isFinite(msUntilTurn) ? Math.max(0, Math.ceil(msUntilTurn / 1000)) : null;
const idleSkipSeconds =
msUntilIdleSkip != null && Number.isFinite(msUntilIdleSkip)
? Math.max(0, Math.ceil(msUntilIdleSkip / 1000))
: null;
const turnTimerText = isActiveDriver
? turnSeconds != null
? `${turnSeconds}s left`
: null
: isNextDriver && turnSeconds != null
? `Your turn in ${turnSeconds}s`
: null;
const entries = roverId
? [
...(shouldShowVideo ? [{ type: 'rover', id: roverId, key: roverId }] : []),
...(hasAudio ? [{ type: 'rover', id: `${roverId}-audio`, key: `${roverId}-audio` }] : []),
]
: [];
const sources = useVideoRequests(entries);
const info = roverId && shouldShowVideo ? sources[roverId] : null;
const audioInfo = roverId && hasAudio ? sources[`${roverId}-audio`] : null;
const snapshotFeeds = useRoverSnapshots(roverId ? [roverId] : [], {
enabled: Boolean(roverId),
version: mode,
});
const snapshotFeed = roverId ? snapshotFeeds[roverId] || null : null;
const frame = useTelemetryFrame(roverId);
const batteryRecord =
roverId && roster
? roster.find((item) => String(item.id) === String(roverId))
: null;
const batteryConfig = batteryRecord?.battery ?? null;
const roverLabel = batteryRecord?.name || (roverId ? `Rover ${roverId}` : '');
useEffect(() => {
if (mode !== 'turns') {
setTurnCueVisible(false);
setTurnCueStartAt(null);
lastTurnRef.current = { active: false, roverId: null };
return;
}
const lastTurn = lastTurnRef.current;
const becameActive = isActiveDriver && !lastTurn.active;
const roverChanged = isActiveDriver && roverId && roverId !== lastTurn.roverId;
if (becameActive || roverChanged) {
setTurnCueVisible(true);
setTurnCueStartAt(Date.now());
} else if (!isActiveDriver && lastTurn.active) {
setTurnCueVisible(false);
setTurnCueStartAt(null);
}
lastTurnRef.current = { active: isActiveDriver, roverId };
}, [isActiveDriver, roverId, mode]);
useEffect(() => {
if (!turnCueVisible || !turnCueStartAt) return;
if (lastControlIntentAt > turnCueStartAt) {
setTurnCueVisible(false);
}
}, [lastControlIntentAt, turnCueStartAt, turnCueVisible]);
return (
<section className="panel">
{roverId ? (
<VideoTile
sessionInfo={info}
videoMode={shouldShowVideo ? 'whep' : 'snapshot'}
snapshotFeed={snapshotFeed}
audioSessionInfo={audioInfo}
label={roverLabel}
roverColor={batteryRecord?.color || null}
telemetryFrame={frame}
batteryConfig={batteryConfig}
layoutFormat={layoutFormat}
overcurrentLimiter={overcurrentLimiter}
songNote={song?.note}
qualityNotice={!shouldShowVideo ? 'Preview feed (low FPS) until your turn.' : null}
showTurnCue={turnCueVisible}
turnTimerText={turnTimerText}
turnSeconds={turnSeconds}
isActiveDriver={isActiveDriver}
idleSkipSeconds={idleSkipSeconds}
/>
) : (
<div className="panel-muted content-center text-center text-sm text-slate-400 aspect-[4/3]">
<p>You are not assigned to a rover.</p>
{/* colored button to visit the spectator page */}
<p className="mt-0">
<a href="/spectate" className="text-blue-400 underline hover:text-blue-500">
Click here to visit the spectator page.
</a>
</p>
</div>
)}
</section>
);
}
@@ -8,11 +8,40 @@ const MOBILE_DISMISS_MS = 10000;
const MAX_FONT_PX = 28; const MAX_FONT_PX = 28;
const MIN_FONT_PX = 14; const MIN_FONT_PX = 14;
function hexToRgb(hex) {
const raw = String(hex || '').trim();
const normalized = raw.startsWith('#') ? raw.slice(1) : raw;
if (!/^[0-9a-fA-F]{3}$|^[0-9a-fA-F]{6}$/.test(normalized)) return null;
const expanded =
normalized.length === 3
? normalized
.split('')
.map((ch) => ch + ch)
.join('')
: normalized;
return {
r: Number.parseInt(expanded.slice(0, 2), 16),
g: Number.parseInt(expanded.slice(2, 4), 16),
b: Number.parseInt(expanded.slice(4, 6), 16),
};
}
function rgba(rgb, alpha) {
return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`;
}
export default function GlobalObjectiveBanner({ layout = 'desktop', className = '', dismissable = true }) { export default function GlobalObjectiveBanner({ layout = 'desktop', className = '', dismissable = true }) {
const goalText = useSessionSelector((state) => { const goalText = useSessionSelector((state) => {
const text = state.session?.globalObjective?.text; const text = state.session?.globalObjective?.text;
return text ? String(text).trim() : ''; return text ? String(text).trim() : '';
}); });
const ownRoverColor = useSessionSelector((state) => {
const roverId = String(state.session?.assignment?.roverId || '').trim();
if (!roverId) return null;
const roster = Array.isArray(state.session?.roster) ? state.session.roster : [];
const rover = roster.find((entry) => String(entry?.id) === roverId);
return rover?.color || null;
});
const isMobile = layout === 'mobile-portrait' || layout === 'mobile-landscape' || layout === 'mobile'; const isMobile = layout === 'mobile-portrait' || layout === 'mobile-landscape' || layout === 'mobile';
const [visible, setVisible] = useState(false); const [visible, setVisible] = useState(false);
const [fontSize, setFontSize] = useState(MAX_FONT_PX); const [fontSize, setFontSize] = useState(MAX_FONT_PX);
@@ -72,7 +101,7 @@ export default function GlobalObjectiveBanner({ layout = 'desktop', className =
const containerClass = useMemo( const containerClass = useMemo(
() => () =>
[ [
'panel-section flex w-full items-center justify-center', 'panel-section flex w-full items-center justify-center border border-neutral-500/60 shadow-[0_1px_0_rgba(255,255,255,0.05)_inset,0_10px_24px_rgba(0,0,0,0.28)]',
isMobile ? 'rounded-none' : 'rounded', isMobile ? 'rounded-none' : 'rounded',
'px-1 py-1 text-center font-semibold tracking-tight', 'px-1 py-1 text-center font-semibold tracking-tight',
className, className,
@@ -81,6 +110,13 @@ export default function GlobalObjectiveBanner({ layout = 'desktop', className =
.join(' '), .join(' '),
[className, isMobile], [className, isMobile],
); );
const accentRgb = hexToRgb(ownRoverColor);
const frameStyle = accentRgb
? {
borderColor: rgba(accentRgb, 0.35),
backgroundImage: `linear-gradient(90deg, rgba(23,23,23,0.96) 0%, rgba(38,38,38,0.94) 58%, ${rgba(accentRgb, 0.18)} 100%)`,
}
: undefined;
if (!goalText || !visible) return null; if (!goalText || !visible) return null;
@@ -94,7 +130,7 @@ export default function GlobalObjectiveBanner({ layout = 'desktop', className =
<div <div
ref={containerRef} ref={containerRef}
className={containerClass} className={containerClass}
style={{ fontSize: `${fontSize}px`, lineHeight: 1.1 }} style={{ ...(frameStyle || {}), fontSize: `${fontSize}px`, lineHeight: 1.1 }}
{...dismissProps} {...dismissProps}
> >
<span className="flex w-full items-stretch gap-0.5 whitespace-nowrap rounded-md"> <span className="flex w-full items-stretch gap-0.5 whitespace-nowrap rounded-md">
@@ -5,6 +5,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
import { useSessionActions, useSessionSelector } from '../../context/SessionContext.jsx'; import { useSessionActions, useSessionSelector } from '../../context/SessionContext.jsx';
import { useControlSystem } from '../../controls/index.js'; import { useControlSystem } from '../../controls/index.js';
import { formatKeyLabel } from '../../controls/keymapUtils.js'; import { formatKeyLabel } from '../../controls/keymapUtils.js';
import CardFrame from '../CardFrame/index.jsx';
function StatusBadge({ label, tone = 'muted' }) { function StatusBadge({ label, tone = 'muted' }) {
const styles = const styles =
@@ -255,32 +256,25 @@ export default function HomeAssistantControls() {
if (!ha?.enabled) { if (!ha?.enabled) {
return ( return (
<section className="panel-section space-y-0.5 text-sm text-slate-400"> <CardFrame title="Room Controls" bodyClassName="space-y-0.5 text-sm text-slate-400">
<p className="text-slate-300">Room Controls</p>
<p className="text-slate-500">Not configured on the server.</p> <p className="text-slate-500">Not configured on the server.</p>
</section> </CardFrame>
); );
} }
if (entities.length === 0) { if (entities.length === 0) {
return ( return (
<section className="panel-section space-y-0.5 text-sm text-slate-400"> <CardFrame title="Room Controls" bodyClassName="space-y-0.5 text-sm text-slate-400">
<p className="text-slate-300">Room Controls</p>
<p className="text-slate-500">No lights or switches configured.</p> <p className="text-slate-500">No lights or switches configured.</p>
</section> </CardFrame>
); );
} }
const connected = Boolean(ha?.connected); const connected = Boolean(ha?.connected);
return ( const actions = (
<section className="panel-section space-y-0.5 text-base"> <>
<header className="flex items-center justify-between gap-0.5 text-sm text-slate-400"> <div className="flex items-center gap-0.5 text-[0.68rem] text-slate-400">
<div className="flex items-center gap-0.5">
<p>Room Controls</p>
<span className="text-xs text-slate-500">{entities.length}</span>
{controlsLocked ? <StatusBadge label={lockState === 'off' ? 'Locked Off' : 'Locked On'} tone="warn" /> : null}
<div className="flex items-center gap-0.5 text-xs text-slate-300 background-black">
<span className="flex items-center gap-0.5"> <span className="flex items-center gap-0.5">
<span>On</span> <span>On</span>
{onKeyLabel ? <KeyPill label={onKeyLabel} /> : null} {onKeyLabel ? <KeyPill label={onKeyLabel} /> : null}
@@ -290,9 +284,13 @@ export default function HomeAssistantControls() {
{offKeyLabel ? <KeyPill label={offKeyLabel} /> : null} {offKeyLabel ? <KeyPill label={offKeyLabel} /> : null}
</span> </span>
</div> </div>
</div> {controlsLocked ? <StatusBadge label={lockState === 'off' ? 'Locked Off' : 'Locked On'} tone="warn" /> : null}
<StatusBadge label={connected ? 'Connected' : 'Offline'} tone={connected ? 'success' : 'warn'} /> <StatusBadge label={connected ? 'Connected' : 'Offline'} tone={connected ? 'success' : 'warn'} />
</header> </>
);
return (
<CardFrame title="Room Controls" actions={actions} bodyClassName="space-y-0.5 text-base">
{controlsLocked ? ( {controlsLocked ? (
<p className="rounded border border-amber-600/60 bg-amber-900/40 px-1 py-0.5 text-xs text-amber-100"> <p className="rounded border border-amber-600/60 bg-amber-900/40 px-1 py-0.5 text-xs text-amber-100">
{lockState === 'off' {lockState === 'off'
@@ -313,11 +311,11 @@ export default function HomeAssistantControls() {
/> />
))} ))}
</div> </div>
</section> </CardFrame>
); );
} }
function KeyPill({ label }) { function KeyPill({ label }) {
if (!label) return null; if (!label) return null;
return <span className="rounded border border-white/40 px-1 text-[0.7rem] text-white">{label}</span>; return <span className="rounded border border-slate-600 px-1 text-[0.65rem] text-slate-300">{label}</span>;
} }
+37 -6
View File
@@ -1,15 +1,16 @@
// Horn Control // Horn Control
// Purpose: Defines the Horn Control module and the local helpers/components used in this file. // Purpose: Defines the Horn Control module and the local helpers/components used in this file.
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit. // Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import { useCallback, useEffect, useMemo, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useSettingsNamespace } from '../../settings/index.js'; import { useSettingsNamespace } from '../../settings/index.js';
import { HORN_SETTINGS_DEFAULTS } from '../../settings/namespaces.js'; import { HORN_SETTINGS_DEFAULTS } from '../../settings/namespaces.js';
import { HORN_MAX_FREQUENCY } from '../../controls/constants.js';
function clampFreq(value) { function clampFreq(value) {
const num = Number(value); const num = Number(value);
if (!Number.isFinite(num)) return 0; if (!Number.isFinite(num)) return 0;
if (num <= 0) return 0; if (num <= 0) return 0;
return Math.min(5000, Math.round(num)); return Math.min(HORN_MAX_FREQUENCY, Math.round(num));
} }
export default function HornControl({ export default function HornControl({
@@ -31,6 +32,7 @@ export default function HornControl({
HORN_SETTINGS_DEFAULTS, HORN_SETTINGS_DEFAULTS,
); );
const [waveform, setWaveform] = useState(hornSettings?.waveform || HORN_SETTINGS_DEFAULTS.waveform); const [waveform, setWaveform] = useState(hornSettings?.waveform || HORN_SETTINGS_DEFAULTS.waveform);
const settingsRootRef = useRef(null);
const [freqs, setFreqs] = useState(() => { const [freqs, setFreqs] = useState(() => {
const base = Array.isArray(hornSettings?.freqs) ? hornSettings.freqs : HORN_SETTINGS_DEFAULTS.freqs; const base = Array.isArray(hornSettings?.freqs) ? hornSettings.freqs : HORN_SETTINGS_DEFAULTS.freqs;
return [...base, 0, 0, 0, 0].slice(0, 4).map((f) => clampFreq(f)); return [...base, 0, 0, 0, 0].slice(0, 4).map((f) => clampFreq(f));
@@ -99,6 +101,30 @@ export default function HornControl({
[saveHornSettings], [saveHornSettings],
); );
useEffect(() => {
const root = settingsRootRef.current;
if (!root) return undefined;
const handleWheel = (event) => {
const target = event.target;
if (!(target instanceof Element)) return;
const input = target.closest('input[data-horn-freq-index]');
if (!input) return;
const index = Number(input.dataset.hornFreqIndex);
if (!Number.isInteger(index) || index < 0 || index >= freqs.length) return;
event.preventDefault();
event.stopPropagation();
const direction = event.deltaY < 0 ? 1 : -1;
const current = Number(freqs[index]) || 0;
updateFreq(index, current + direction * 25);
};
root.addEventListener('wheel', handleWheel, { passive: false, capture: true });
return () => {
root.removeEventListener('wheel', handleWheel, { capture: true });
};
}, [freqs, updateFreq]);
const handlePointerDown = (event) => { const handlePointerDown = (event) => {
if (disabled) return; if (disabled) return;
const tag = event.target?.tagName?.toLowerCase(); const tag = event.target?.tagName?.toLowerCase();
@@ -176,7 +202,7 @@ export default function HornControl({
</div> </div>
{showSettings ? ( {showSettings ? (
compactSettings ? ( compactSettings ? (
<div className="relative z-10 flex flex-col gap-0.5 text-[0.65rem]"> <div ref={settingsRootRef} className="relative z-10 flex flex-col gap-0.5 text-[0.65rem]">
<label className="flex items-center justify-between gap-0.5 text-slate-200"> <label className="flex items-center justify-between gap-0.5 text-slate-200">
<span className="text-slate-300">Wave</span> <span className="text-slate-300">Wave</span>
<select <select
@@ -195,9 +221,10 @@ export default function HornControl({
<input <input
type="number" type="number"
min={0} min={0}
max={5000} max={HORN_MAX_FREQUENCY}
step={1} step={1}
value={freq} value={freq}
data-horn-freq-index={idx}
onChange={(event) => updateFreq(idx, event.target.value)} onChange={(event) => updateFreq(idx, event.target.value)}
className="w-full rounded border border-slate-700 bg-slate-900 px-1 py-[2px] text-right text-[0.65rem] font-mono text-slate-100" className="w-full rounded border border-slate-700 bg-slate-900 px-1 py-[2px] text-right text-[0.65rem] font-mono text-slate-100"
/> />
@@ -206,7 +233,10 @@ export default function HornControl({
</div> </div>
</div> </div>
) : ( ) : (
<div className="relative z-10 grid grid-cols-[minmax(0,1.2fr)_repeat(4,minmax(0,1fr))] items-center gap-0.5 text-[0.65rem]"> <div
ref={settingsRootRef}
className="relative z-10 grid grid-cols-[minmax(0,1.2fr)_repeat(4,minmax(0,1fr))] items-center gap-0.5 text-[0.65rem]"
>
<label className="flex items-center gap-0.5 text-slate-200"> <label className="flex items-center gap-0.5 text-slate-200">
<span className="text-slate-300">Wave</span> <span className="text-slate-300">Wave</span>
<select <select
@@ -224,9 +254,10 @@ export default function HornControl({
<input <input
type="number" type="number"
min={0} min={0}
max={5000} max={HORN_MAX_FREQUENCY}
step={1} step={1}
value={freq} value={freq}
data-horn-freq-index={idx}
onChange={(event) => updateFreq(idx, event.target.value)} onChange={(event) => updateFreq(idx, event.target.value)}
className="w-full rounded border border-slate-700 bg-slate-900 px-1 py-[2px] text-right text-[0.65rem] font-mono text-slate-100" className="w-full rounded border border-slate-700 bg-slate-900 px-1 py-[2px] text-right text-[0.65rem] font-mono text-slate-100"
/> />
@@ -0,0 +1,31 @@
import { useSessionSelector } from '../../../context/SessionContext.jsx';
import { useTelemetryFrame } from '../../../context/TelemetryContext.jsx';
import LightBumpBars from '../LightBumpBars/index.jsx';
import { buildBatteryVisual } from '../../../lib/battery.js';
import BatteryBar from '../../BatteryBar/index.jsx';
export default function DriverBottomStrip({ roverId = null, mobileHud = false }) {
const assignedRoverId = useSessionSelector((state) => state.session?.assignment?.roverId ?? null);
const effectiveRoverId = roverId ?? assignedRoverId;
const frame = useTelemetryFrame(effectiveRoverId);
const sensors = frame?.sensors ?? null;
const batteryConfig = useSessionSelector((state) => {
if (!effectiveRoverId) return null;
const roster = state.session?.roster || [];
const rover = roster.find((entry) => String(entry.id) === String(effectiveRoverId));
return rover?.battery ?? null;
});
const batteryVisual = buildBatteryVisual({
charge: sensors?.batteryChargeMah ?? null,
config: batteryConfig,
});
return (
<div className="space-y-0.5">
<LightBumpBars roverId={effectiveRoverId} />
<div className="panel-section space-y-0.5 text-sm">
<BatteryBar visual={batteryVisual} compact={mobileHud} />
</div>
</div>
);
}
@@ -2,9 +2,9 @@
// Purpose: Defines the Hud Chat Input module and the local helpers/components used in this file. // Purpose: Defines the Hud Chat Input module and the local helpers/components used in this file.
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit. // Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import { memo, useMemo, useState } from 'react'; import { memo, useMemo, useState } from 'react';
import { useChat } from '../../context/ChatContext.jsx'; import { useChat } from '../../../context/ChatContext.jsx';
import { useSessionSelector } from '../../context/SessionContext.jsx'; import { useSessionSelector } from '../../../context/SessionContext.jsx';
import { useSettingsNamespace } from '../../settings/index.js'; import { useSettingsNamespace } from '../../../settings/index.js';
function HudChatInput({ compact = false }) { function HudChatInput({ compact = false }) {
const role = useSessionSelector((state) => state.session?.role || null); const role = useSessionSelector((state) => state.session?.role || null);
@@ -0,0 +1,38 @@
import TopDownMap from '../../TopDownMap/index.jsx';
export default function HudMapOverlay({
sensors,
show = true,
mapPosition = 'top-center',
layoutFormat = 'desktop',
mobileHud = false,
}) {
if (!show) return null;
const portraitMobile = layoutFormat === 'mobile-portrait';
const mapSize = '240px';
const mapScale = portraitMobile ? 0.3 : mobileHud ? 0.33 : 0.7;
const mapOpacity = mobileHud ? 0.6 : 0.7;
const mapStyle = {
width: mapSize,
height: mapSize,
opacity: mapOpacity,
transform: mapPosition === 'top-center' ? `translateX(-50%) scale(${mapScale})` : `scale(${mapScale})`,
transformOrigin:
mapPosition === 'bottom-left'
? 'bottom left'
: mapPosition === 'top-center'
? 'top center'
: 'top right',
...(mapPosition === 'bottom-left'
? { left: '0.25rem', bottom: '0.25rem' }
: mapPosition === 'top-center'
? { left: '50%', top: '0.25rem' }
: { right: '0.25rem', top: '0.25rem' }),
};
return (
<div className="pointer-events-none absolute rounded" style={mapStyle}>
<TopDownMap sensors={sensors} size={240} overlay />
</div>
);
}
@@ -0,0 +1,50 @@
import { roverNameChromeStyle } from '../../../lib/roverColor.js';
export default function RoverLabelOverlay({
variant = 'default',
label,
roverColor = null,
driverLabel = null,
mobileHud = false,
labelScale = 1,
}) {
const labelPadClass = mobileHud ? 'px-0.25 py-0.25' : 'px-0.5 py-0.5';
const labelTextClass = mobileHud ? 'text-[0.55rem]' : 'text-[0.8rem]';
const labelPosClass = 'bottom-0.5';
const labelWrapperStyle = {
transform: `translateX(-50%) scale(${labelScale})`,
transformOrigin: 'center bottom',
};
if (variant === 'spectator') {
return (
<div className={`absolute ${labelPosClass} left-1/2`} style={labelWrapperStyle}>
<div className={`flex items-center gap-0.5 bg-black/80 text-slate-100 ${labelPadClass} ${labelTextClass}`}>
<span
className="font-semibold text-white rounded px-1 py-[1px] border border-transparent"
style={roverNameChromeStyle(roverColor, 0.18)}
>
{label || 'No rover'}
</span>
{driverLabel ? <span className="text-slate-300"> {driverLabel}</span> : null}
</div>
</div>
);
}
return (
<div className={`absolute ${labelPosClass} left-1/2`} style={labelWrapperStyle}>
<div className={`flex gap-0.5 bg-black/80 text-slate-100 ${labelPadClass} ${labelTextClass}`}>
<span>
Rover:{' '}
<span
className="rounded px-1 py-[1px] border border-transparent"
style={roverNameChromeStyle(roverColor, 0.18)}
>
"{label || 'No rover'}"
</span>
</span>
</div>
</div>
);
}
@@ -0,0 +1,52 @@
export default function SpectatorTelemetryOverlay({ sensors, mobileHud = false }) {
const statusPadClass = mobileHud ? 'px-0.25 py-0.25' : 'px-1 py-0.5';
const telemetryPosClass = mobileHud ? 'left-0.5 top-1/2' : 'left-1 top-1/2';
const telemetryTextClass = mobileHud ? 'text-[0.45rem]' : 'text-[0.65rem]';
const telemetryEntries = [
['Voltage', sensors?.voltageMv != null ? `${(sensors.voltageMv / 1000).toFixed(2)} V` : '--'],
['Current', sensors?.currentMa != null ? `${sensors.currentMa} mA` : '--'],
['Charge', sensors?.batteryChargeMah != null ? `${sensors.batteryChargeMah}` : '--'],
['OI', sensors?.oiMode?.label || '--'],
];
const docked = Boolean(sensors?.chargingSources?.homeBase);
const chargingLabel = sensors?.chargingState?.label || '';
const charging = Boolean(chargingLabel && chargingLabel.toLowerCase() !== 'not charging');
const oiLabel = sensors?.oiMode?.label || 'Unknown';
const oiNormalized = oiLabel.toLowerCase();
const oiTone =
oiNormalized === 'full'
? 'bg-emerald-500/80 text-emerald-50'
: oiNormalized === 'safe'
? 'bg-amber-400/80 text-amber-950'
: oiNormalized === 'passive'
? 'bg-slate-700/80 text-slate-100'
: 'bg-slate-700/60 text-slate-200';
const dockTone = docked ? 'bg-emerald-500/80 text-emerald-50' : 'bg-slate-700/70 text-slate-200';
const chargingTone = charging
? 'bg-emerald-500/80 text-emerald-50'
: docked
? 'bg-amber-400/80 text-amber-950'
: 'bg-slate-700/70 text-slate-200';
return (
<div
className={`absolute ${telemetryPosClass} flex -translate-y-1/2 flex-col gap-0.5 bg-black/70 text-slate-100 ${telemetryTextClass} ${statusPadClass}`}
>
<div className="space-y-0.5 leading-tight">
<div className="flex flex-col gap-0.5 text-[0.75rem] font-semibold uppercase tracking-wide">
<span className={`rounded px-1.5 py-0.5 ${dockTone}`}>{docked ? 'Docked' : 'Undocked'}</span>
<span className={`rounded px-1.5 py-0.5 ${chargingTone}`}>
{charging ? 'Charging' : docked ? 'Not charging' : 'Not charging'}
</span>
<span className={`rounded px-1.5 py-0.5 ${oiTone}`}>OI: {oiLabel}</span>
</div>
{telemetryEntries.map(([labelText, value]) => (
<span key={labelText} className="flex items-center justify-between gap-0.5">
<span className="text-slate-400">{labelText}</span>
<span className="font-semibold text-white">{value}</span>
</span>
))}
</div>
</div>
);
}
@@ -0,0 +1,110 @@
// Hud Overlay
// Purpose: Defines the Hud Overlay module and the local helpers/components used in this file.
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import React from 'react';
import { useHudMapSetting } from '../../../hooks/useHudMapSetting.js';
import { useSessionSelector } from '../../../context/SessionContext.jsx';
import { useTelemetryFrame } from '../../../context/TelemetryContext.jsx';
import RoverLabelOverlay from './RoverLabelOverlay.jsx';
import SpectatorTelemetryOverlay from './SpectatorTelemetryOverlay.jsx';
import HudMapOverlay from './HudMapOverlay.jsx';
function HudOverlay({
roverId = null,
sensors,
label,
roverColor = null,
layoutFormat = 'desktop',
variant = 'default',
driverLabel = null,
showTopDown = undefined,
mobileHud = false,
mapPosition = null,
labelScale = 1,
}) {
const assignedRoverId = useSessionSelector((state) => state.session?.assignment?.roverId ?? null);
const effectiveRoverId = roverId ?? assignedRoverId;
const frame = useTelemetryFrame(effectiveRoverId);
const rosterInfo = useSessionSelector((state) => {
if (!effectiveRoverId) return { label: null, roverColor: null };
const roster = state.session?.roster || [];
const rover = roster.find((entry) => String(entry.id) === String(effectiveRoverId));
return {
label: rover?.name || null,
roverColor: rover?.color || null,
};
});
const derivedDriverLabel = useSessionSelector((state) => {
if (!effectiveRoverId || variant !== 'spectator') return null;
const activeId = state.session?.activeDrivers?.[effectiveRoverId] || null;
const users = state.session?.users || [];
const match = users.find((u) => String(u.socketId || '') === String(activeId || ''));
return match?.nickname || match?.name || null;
});
const resolvedSensors = sensors ?? frame?.sensors ?? null;
const resolvedLabel = label ?? rosterInfo.label ?? null;
const resolvedRoverColor = roverColor ?? rosterInfo.roverColor ?? null;
const resolvedDriverLabel = driverLabel ?? derivedDriverLabel;
const isMobile = mobileHud;
const [showHudMapDesktop] = useHudMapSetting();
const resolvedShowTopDown =
typeof showTopDown === 'boolean'
? showTopDown
: variant === 'spectator'
? true
: isMobile
? true
: showHudMapDesktop;
const resolvedMapPosition =
mapPosition || (variant === 'spectator' ? 'top-center' : isMobile ? 'top-right' : 'top-center');
if (variant === 'none') {
return null;
}
if (variant === 'spectator') {
return (
<>
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<SpectatorTelemetryOverlay sensors={resolvedSensors} mobileHud={isMobile} />
<RoverLabelOverlay
variant="spectator"
label={resolvedLabel}
roverColor={resolvedRoverColor}
driverLabel={resolvedDriverLabel}
mobileHud={isMobile}
labelScale={labelScale}
/>
</div>
<HudMapOverlay
sensors={resolvedSensors}
show={resolvedShowTopDown}
mapPosition={resolvedMapPosition}
layoutFormat={layoutFormat}
mobileHud={isMobile}
/>
</>
);
}
return (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<RoverLabelOverlay
variant="default"
label={resolvedLabel}
roverColor={resolvedRoverColor}
mobileHud={isMobile}
labelScale={labelScale}
/>
<HudMapOverlay
sensors={resolvedSensors}
show={resolvedShowTopDown && variant !== 'spectator'}
mapPosition={resolvedMapPosition}
layoutFormat={layoutFormat}
mobileHud={isMobile}
/>
</div>
);
}
export default React.memo(HudOverlay);
@@ -2,15 +2,21 @@
// Purpose: Defines the Light Bump Bars module and the local helpers/components used in this file. // Purpose: Defines the Light Bump Bars module and the local helpers/components used in this file.
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit. // Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import React from 'react'; import React from 'react';
import { useSessionSelector } from '../../../context/SessionContext.jsx';
import { useTelemetryFrame } from '../../../context/TelemetryContext.jsx';
function LightBumpBars({ sensors }) { function LightBumpBars({ roverId = null, sensors }) {
const assignedRoverId = useSessionSelector((state) => state.session?.assignment?.roverId ?? null);
const effectiveRoverId = roverId ?? assignedRoverId;
const frame = useTelemetryFrame(effectiveRoverId);
const resolvedSensors = sensors ?? frame?.sensors ?? null;
const values = [ const values = [
sensors?.lightBumpLeftSignal, resolvedSensors?.lightBumpLeftSignal,
sensors?.lightBumpFrontLeftSignal, resolvedSensors?.lightBumpFrontLeftSignal,
sensors?.lightBumpCenterLeftSignal, resolvedSensors?.lightBumpCenterLeftSignal,
sensors?.lightBumpCenterRightSignal, resolvedSensors?.lightBumpCenterRightSignal,
sensors?.lightBumpFrontRightSignal, resolvedSensors?.lightBumpFrontRightSignal,
sensors?.lightBumpRightSignal, resolvedSensors?.lightBumpRightSignal,
]; ];
const max = values.filter((v) => v != null).reduce((acc, v) => Math.max(acc, v), 1200); const max = values.filter((v) => v != null).reduce((acc, v) => Math.max(acc, v), 1200);
const eased = (v) => Math.pow(Math.max(0, Math.min(1, (v ?? 0) / max)), 0.35); const eased = (v) => Math.pow(Math.max(0, Math.min(1, (v ?? 0) / max)), 0.35);
@@ -0,0 +1,46 @@
// Low Battery Overlay
// Purpose: Defines the Low Battery Overlay module and the local helpers/components used in this file.
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import React from 'react';
import { useSessionSelector } from '../../../context/SessionContext.jsx';
import { useTelemetryFrame } from '../../../context/TelemetryContext.jsx';
import { buildBatteryVisual } from '../../../lib/battery.js';
function LowBatteryOverlay({ roverId = null, sensors, batteryConfig, compact = false }) {
const assignedRoverId = useSessionSelector((state) => state.session?.assignment?.roverId ?? null);
const effectiveRoverId = roverId ?? assignedRoverId;
const frame = useTelemetryFrame(effectiveRoverId);
const rosterBatteryConfig = useSessionSelector((state) => {
if (!effectiveRoverId) return null;
const roster = state.session?.roster || [];
const rover = roster.find((entry) => String(entry.id) === String(effectiveRoverId));
return rover?.battery ?? null;
});
const resolvedSensors = sensors ?? frame?.sensors ?? null;
const resolvedBatteryConfig = batteryConfig ?? rosterBatteryConfig;
const battery = buildBatteryVisual({
charge: resolvedSensors?.batteryChargeMah ?? null,
config: resolvedBatteryConfig,
});
if (!battery?.available) return null;
if (!battery.warnActive && !battery.urgentActive) return null;
const message = battery.urgentActive
? 'BATTERY VERY LOW, DOCK THE ROVER AND CHARGE IMMEDIATELY!!'
: 'Battery low! please dock and charge the rover soon.';
const containerClass = compact ? 'p-2 top-6' : 'p-4 top-10';
const textClass = compact ? 'text-sm' : 'text-2xl';
return (
<div
className={`pointer-events-none absolute flex items-center justify-center bg-amber-900/60 left-1/2 -translate-x-1/2 ${containerClass}`}
>
<div className={`text-center font-semibold text-white animate-pulse ${textClass}`}>
<div>{message}</div>
</div>
</div>
);
}
export default React.memo(LowBatteryOverlay);
@@ -0,0 +1,72 @@
import React, { useEffect, useRef, useState } from 'react';
import { useManualDockAssist } from '../../../features/manualDockAssist/useManualDockAssist.js';
function ManualDockAssistOverlay({ mobileHud = false }) {
const { visible, statusLabel, statusTone, active, charging } = useManualDockAssist({ manageLifecycle: true });
const [popupMessage, setPopupMessage] = useState('');
const timerRef = useRef(null);
const prevActiveRef = useRef(active);
useEffect(() => {
const prevActive = prevActiveRef.current;
const enabledNow = active && !prevActive;
const autoDisabledOnCharge = !active && prevActive && charging;
if (enabledNow) {
setPopupMessage('Dock assist mode enabled');
} else if (autoDisabledOnCharge) {
setPopupMessage('Docking successful! Thank you!');
}
prevActiveRef.current = active;
}, [active, charging]);
useEffect(() => {
if (!popupMessage) return undefined;
if (timerRef.current) {
clearTimeout(timerRef.current);
}
timerRef.current = setTimeout(() => {
setPopupMessage('');
timerRef.current = null;
}, 2500);
return () => {
if (timerRef.current) {
clearTimeout(timerRef.current);
timerRef.current = null;
}
};
}, [popupMessage]);
if (!visible) return null;
const toneClass =
statusTone === 'good'
? 'border-emerald-200/90 bg-emerald-900/90 text-emerald-50'
: statusTone === 'warn'
? 'border-amber-200/90 bg-amber-900/90 text-amber-50'
: 'border-cyan-200/90 bg-cyan-900/90 text-cyan-50';
return (
<div className="pointer-events-none absolute inset-0">
{popupMessage ? (
<div className="absolute inset-0 flex items-center justify-center">
<div
className={`rounded-xl border border-indigo-200/95 bg-black/95 px-4 py-2 text-center font-semibold text-indigo-50 shadow-2xl ${
mobileHud ? 'text-lg' : 'text-2xl'
}`}
>
{popupMessage}
</div>
</div>
) : (
<div
className={`absolute right-2 top-1/2 -translate-y-1/2 rounded-lg border px-2 py-1 font-semibold shadow-lg ${toneClass} ${
mobileHud ? 'text-[0.65rem]' : 'text-xs'
}`}
>
{statusLabel}
</div>
)}
</div>
);
}
export default React.memo(ManualDockAssistOverlay);
@@ -0,0 +1,7 @@
export const OVERCURRENT_LABELS = {
leftWheel: 'Left wheel',
rightWheel: 'Right wheel',
mainBrush: 'Main brush',
sideBrush: 'Side brush',
limiter: 'Overcurrent limit',
};
@@ -0,0 +1,67 @@
// Overcurrent Overlay
// Purpose: Defines the Overcurrent Overlay module and the local helpers/components used in this file.
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import React from 'react';
import { useMemo } from 'react';
import { useSessionSelector } from '../../../context/SessionContext.jsx';
import { useTelemetryFrame } from '../../../context/TelemetryContext.jsx';
import { useOvercurrentLimiter } from '../../../controls/index.js';
import { OVERCURRENT_LABELS } from './constants.js';
function OvercurrentOverlay({ roverId = null, sensors, overcurrentLimiter = null, compact = false }) {
const assignedRoverId = useSessionSelector((state) => state.session?.assignment?.roverId ?? null);
const effectiveRoverId = roverId ?? assignedRoverId;
const frame = useTelemetryFrame(effectiveRoverId);
const internalLimiter = useOvercurrentLimiter(effectiveRoverId);
const resolvedSensors = sensors ?? frame?.sensors ?? null;
const resolvedOvercurrentLimiter = overcurrentLimiter ?? internalLimiter ?? null;
const wheelOvercurrents = resolvedSensors?.wheelOvercurrents || null;
const overcurrentMotors = useMemo(
() =>
wheelOvercurrents == null
? []
: Object.entries(wheelOvercurrents)
.filter(([, active]) => Boolean(active))
.map(([key]) => key),
[wheelOvercurrents],
);
const limiterCaps = resolvedOvercurrentLimiter?.caps || null;
const limiterFill = useMemo(() => {
if (!limiterCaps) return null;
const driveCap = Number.isFinite(limiterCaps?.drive?.cap) ? limiterCaps.drive.cap : 1;
const auxCap = Number.isFinite(limiterCaps?.aux?.cap) ? limiterCaps.aux.cap : 1;
return Math.max(0, Math.min(1, 1 - Math.min(driveCap, auxCap)));
}, [limiterCaps]);
const limiterActive = Boolean(resolvedOvercurrentLimiter?.isActive);
const motors = useMemo(
() => (overcurrentMotors.length ? overcurrentMotors : limiterActive ? ['limiter'] : []),
[overcurrentMotors, limiterActive],
);
const fill = limiterFill ?? (overcurrentMotors.length ? 1 : 0);
if (!motors?.length) return null;
const safeLabels = motors.map((name) => OVERCURRENT_LABELS[name] || name);
const containerClass = compact ? 'w-[12rem] h-[3.5rem]' : 'w-[20rem] h-[7rem]';
const padClass = compact ? 'px-2 py-1' : 'px-4 py-2';
const textClass = compact ? 'text-lg' : 'text-4xl';
const subTextClass = compact ? 'text-xs' : 'text-xl';
const safeFill = Math.max(0, Math.min(1, fill));
const fillWidth = `${Math.round(safeFill * 100)}%`;
return (
<div
className={`pointer-events-none absolute flex items-center justify-center bg-red-900/50 top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 ${containerClass}`}
>
<div className="relative h-full w-full">
<div className="absolute inset-0 overflow-hidden">
<div className="h-full bg-red-700/60" style={{ width: fillWidth }} />
</div>
<div className={`relative z-10 flex h-full w-full flex-col items-center justify-center text-center font-semibold text-white animate-pulse ${textClass} ${padClass}`}>
<div>OVERCURRENT</div>
<div className={`mt-0 font-medium text-white ${subTextClass}`}>{safeLabels.join(', ')}</div>
</div>
</div>
</div>
);
}
export default React.memo(OvercurrentOverlay);
@@ -0,0 +1,100 @@
import { useEffect, useRef, useState } from 'react';
import { useSessionSelector } from '../../../context/SessionContext.jsx';
const DISMISS_AFTER_INPUT_MS = 5000;
const LARGE_FADE_MS = 700;
export default function RoverDescriptionOverlay({
roverId = null,
description,
variant = 'default',
mobileHud = false,
displayKey = '',
controlIntentAt,
}) {
const assignedRoverId = useSessionSelector((state) => state.session?.assignment?.roverId ?? null);
const effectiveRoverId = roverId ?? assignedRoverId;
const rosterDescription = useSessionSelector((state) => {
if (!effectiveRoverId) return null;
const roster = state.session?.roster || [];
const rover = roster.find((entry) => String(entry.id) === String(effectiveRoverId));
return rover?.description || null;
});
const resolvedDescription = description ?? rosterDescription;
const resolvedControlIntentAt =
typeof controlIntentAt === 'number' ? controlIntentAt : 0;
const resolvedDisplayKey =
displayKey || `${effectiveRoverId || ''}::${resolvedDescription || ''}`;
const [largeVisible, setLargeVisible] = useState(false);
const [largeFading, setLargeFading] = useState(false);
const fadeTimerRef = useRef(null);
const hideTimerRef = useRef(null);
useEffect(
() => () => {
clearTimeout(fadeTimerRef.current);
clearTimeout(hideTimerRef.current);
},
[],
);
useEffect(() => {
if (variant !== 'default' || !resolvedDescription) {
setLargeVisible(false);
setLargeFading(false);
clearTimeout(fadeTimerRef.current);
clearTimeout(hideTimerRef.current);
return undefined;
}
clearTimeout(fadeTimerRef.current);
clearTimeout(hideTimerRef.current);
setLargeVisible(true);
setLargeFading(false);
return undefined;
}, [resolvedDescription, resolvedDisplayKey, variant]);
useEffect(() => {
if (variant !== 'default' || !resolvedDescription || !largeVisible || largeFading) return;
const nextIntent = Number(resolvedControlIntentAt) || 0;
if (nextIntent <= 0) return;
if (fadeTimerRef.current || hideTimerRef.current) return;
fadeTimerRef.current = setTimeout(() => {
setLargeFading(true);
fadeTimerRef.current = null;
}, DISMISS_AFTER_INPUT_MS);
hideTimerRef.current = setTimeout(() => {
setLargeVisible(false);
hideTimerRef.current = null;
}, DISMISS_AFTER_INPUT_MS + LARGE_FADE_MS);
}, [resolvedControlIntentAt, resolvedDescription, largeFading, largeVisible, variant]);
if (!resolvedDescription) return null;
if (variant === 'spectator') {
return (
<div className="pointer-events-none absolute inset-x-0 top-1 z-50 flex justify-center">
<div className="surface max-w-[92%] border border-slate-600/80 px-1 py-0.5 text-center text-[0.62rem] leading-tight text-slate-100 shadow-lg">
{resolvedDescription}
</div>
</div>
);
}
if (variant !== 'default' || !largeVisible) return null;
return (
<div className="pointer-events-none absolute inset-0 z-50 flex items-center justify-center">
<div
className={`surface max-w-[94%] border border-slate-400 bg-neutral-900 px-2 py-1 text-center font-semibold text-slate-100 shadow-xl transition-opacity duration-700 ${
largeFading ? 'opacity-0' : 'opacity-100'
} ${mobileHud ? 'text-[1rem] leading-tight' : 'text-[1.5rem] leading-tight'}`}
>
<p>Just so you know, this rover</p>
<p>{resolvedDescription}</p>
<p className={`${mobileHud ? 'text-[0.58rem]' : 'text-[0.72rem]'} mt-0.5 font-normal text-slate-300`}>
This fades 5 seconds after your first control input.
</p>
</div>
</div>
);
}
@@ -0,0 +1,215 @@
import React, { useEffect, useMemo, useRef, useState } from 'react';
import { useSessionSelector } from '../../../context/SessionContext.jsx';
import { useControlSystem } from '../../../controls/index.js';
import SocialButton from '../../SocialButton/index.jsx';
function TurnsOverlay({
roverId = null,
mobileHud = false,
}) {
const assignedRoverId = useSessionSelector((state) => state.session?.assignment?.roverId ?? null);
const effectiveRoverId = roverId ?? assignedRoverId;
const mode = useSessionSelector((state) => state.session?.mode || null);
const roster = useSessionSelector((state) => state.session?.roster ?? []);
const users = useSessionSelector((state) => state.session?.users ?? []);
const turnQueues = useSessionSelector((state) => state.session?.turnQueues ?? {});
const socketId = useSessionSelector((state) => state.session?.socketId || null);
const activeDrivers = useSessionSelector((state) => state.session?.activeDrivers ?? {});
const {
state: { lastControlIntentAt },
} = useControlSystem();
const [now, setNow] = useState(() => Date.now());
const [showTurnCue, setShowTurnCue] = useState(false);
const [turnCueStartAt, setTurnCueStartAt] = useState(null);
const [noticeFlashActive, setNoticeFlashActive] = useState(false);
const [notTurnFlashAt, setNotTurnFlashAt] = useState(0);
const lastTurnRef = useRef({ initialized: false, roverId: null, activeDriverId: null });
const lastIntentRef = useRef(lastControlIntentAt || 0);
const timerTextClass = mobileHud ? 'text-[0.5rem]' : 'text-[0.7rem]';
const timerPadClass = mobileHud ? 'px-0.5 py-0.25' : 'px-1 py-0.5';
const titleClass = mobileHud ? 'text-3xl' : 'text-5xl';
const subClass = mobileHud ? 'text-xs' : 'text-sm';
const cueTimerClass = mobileHud ? 'text-[0.55rem]' : 'text-[0.75rem]';
const cuePadClass = mobileHud ? 'px-4 py-3' : 'px-6 py-4';
const turnInfo = effectiveRoverId ? turnQueues?.[effectiveRoverId] : null;
const activeDriverId = effectiveRoverId ? activeDrivers?.[effectiveRoverId] : null;
const isActiveDriver = Boolean(socketId && activeDriverId === socketId);
const nextDriverId = useMemo(() => {
const queue = turnInfo?.queue || [];
if (!queue.length || !turnInfo?.current || queue.length <= 1) return null;
const idx = queue.findIndex((id) => id === turnInfo.current);
if (idx === -1) return queue[0] || null;
return queue[(idx + 1) % queue.length] || null;
}, [turnInfo?.queue, turnInfo?.current]);
const isNextDriver = Boolean(socketId && nextDriverId === socketId);
const deadline = turnInfo?.deadline || null;
const idleDeadline = turnInfo?.idleDeadline || null;
const msUntilTurn = deadline ? deadline - now : null;
const msUntilIdleSkip = idleDeadline ? idleDeadline - now : null;
const isTurnsMode = mode === 'turns';
const totalRovers = roster.length;
const totalDrivers = useMemo(() => {
const unique = new Set();
users.forEach((entry) => {
const role = String(entry?.role || '');
if (role === 'spectator') return;
const turnRoverId = String(entry?.roverId || '').trim();
const turnSocketId = String(entry?.socketId || '').trim();
if (!turnRoverId || !turnSocketId) return;
unique.add(turnSocketId);
});
return unique.size;
}, [users]);
const shouldUsePreviewByLoad = isTurnsMode && totalDrivers > totalRovers;
const isPreSwitchWindow =
isTurnsMode && isNextDriver && msUntilTurn != null && msUntilTurn <= 5000 && msUntilTurn > 0;
const showNotTurnNotice = isTurnsMode && !isActiveDriver;
const showPreviewReason = showNotTurnNotice && !isPreSwitchWindow && shouldUsePreviewByLoad;
const turnSeconds =
msUntilTurn != null && Number.isFinite(msUntilTurn) ? Math.max(0, Math.ceil(msUntilTurn / 1000)) : null;
const idleSkipSeconds =
msUntilIdleSkip != null && Number.isFinite(msUntilIdleSkip)
? Math.max(0, Math.ceil(msUntilIdleSkip / 1000))
: null;
const turnTimerText = useMemo(() => {
if (!isTurnsMode || !isActiveDriver) return null;
return turnSeconds != null ? `${turnSeconds}s left` : 'Your turn';
}, [isTurnsMode, isActiveDriver, turnSeconds]);
const notTurnCountdownText = useMemo(() => {
if (!showNotTurnNotice || !isNextDriver || turnSeconds == null) return null;
return `${turnSeconds} seconds until your turn.`;
}, [showNotTurnNotice, isNextDriver, turnSeconds]);
const showCountdown = isActiveDriver && typeof idleSkipSeconds === 'number';
const turnTimerFlashActive = noticeFlashActive;
useEffect(() => {
if (mode !== 'turns') return undefined;
const timer = setInterval(() => setNow(Date.now()), 250);
return () => clearInterval(timer);
}, [mode]);
useEffect(() => {
if (mode !== 'turns') {
setShowTurnCue(false);
setTurnCueStartAt(null);
lastTurnRef.current = { initialized: false, roverId: null, activeDriverId: null };
return;
}
const lastTurn = lastTurnRef.current;
const nextActiveDriverId = activeDriverId || null;
if (!socketId || !effectiveRoverId) {
setShowTurnCue(false);
setTurnCueStartAt(null);
lastTurnRef.current = { initialized: false, roverId: null, activeDriverId: null };
return;
}
if (!lastTurn.initialized || lastTurn.roverId !== effectiveRoverId) {
lastTurnRef.current = { initialized: true, roverId: effectiveRoverId, activeDriverId: nextActiveDriverId };
return;
}
const becameActive =
Boolean(lastTurn.activeDriverId) &&
lastTurn.activeDriverId !== socketId &&
nextActiveDriverId === socketId;
if (becameActive) {
setShowTurnCue(true);
setTurnCueStartAt(Date.now());
} else if (nextActiveDriverId !== socketId && showTurnCue) {
setShowTurnCue(false);
setTurnCueStartAt(null);
}
lastTurnRef.current = { initialized: true, roverId: effectiveRoverId, activeDriverId: nextActiveDriverId };
}, [activeDriverId, mode, effectiveRoverId, socketId, showTurnCue]);
useEffect(() => {
if (!showTurnCue || !turnCueStartAt) return;
if (lastControlIntentAt > turnCueStartAt) {
setShowTurnCue(false);
}
}, [lastControlIntentAt, showTurnCue, turnCueStartAt]);
useEffect(() => {
const lastIntent = Number(lastIntentRef.current) || 0;
const nextIntent = Number(lastControlIntentAt) || 0;
if (nextIntent > lastIntent && showNotTurnNotice) {
setNotTurnFlashAt(Date.now());
}
lastIntentRef.current = nextIntent;
}, [lastControlIntentAt, showNotTurnNotice]);
useEffect(() => {
if (!showNotTurnNotice || !notTurnFlashAt) return undefined;
setNoticeFlashActive(true);
const timer = setTimeout(() => setNoticeFlashActive(false), 650);
return () => clearTimeout(timer);
}, [showNotTurnNotice, notTurnFlashAt]);
return (
<>
{showTurnCue ? (
<div className="pointer-events-none absolute inset-0 z-30 flex items-center justify-center bg-black/55">
<div
className={`flex flex-col items-center gap-0.5 rounded border border-amber-300/80 bg-black/70 ${cuePadClass}`}
>
<div className={`font-semibold text-amber-200 ${titleClass}`}>IT IS YOUR TURN!</div>
<div className={`text-amber-200/80 ${subClass}`}>Start driving!</div>
{showCountdown ? (
<div className={`text-red-100/90 ${cueTimerClass}`}>
Idle skip in {idleSkipSeconds}s
</div>
) : null}
</div>
</div>
) : null}
{turnTimerText ? (
<div
className={`pointer-events-none absolute bottom-1 left-1 rounded border ${
turnTimerFlashActive
? 'border-red-300/90 bg-red-900/80 text-red-100'
: 'border-amber-300/80 bg-black/75 text-amber-200'
} ${timerPadClass} ${timerTextClass}`}
>
{turnTimerText}
</div>
) : null}
{showNotTurnNotice ? (
<div className="pointer-events-none absolute bottom-1 left-1 z-40">
<div
className={`w-fit rounded border ${
noticeFlashActive
? 'border-red-300/90 bg-red-900/80 text-red-100'
: 'border-amber-300/80 bg-black/75 text-amber-200'
} ${mobileHud ? 'px-2 py-1 text-[0.6rem]' : 'px-3 py-1.5 text-sm'}`}
>
<div
className={
noticeFlashActive
? 'text-[0.82rem] font-semibold text-red-50'
: 'text-[0.82rem] font-semibold text-white'
}
>
Not your turn to drive!
</div>
{notTurnCountdownText ? (
<div className={noticeFlashActive ? 'text-red-100/95' : 'text-amber-100'}>
{notTurnCountdownText}
</div>
) : null}
{showPreviewReason ? (
<div className={noticeFlashActive ? 'text-red-100/90' : 'text-amber-200/85'}>
Video switched to preview mode to save bandwidth.
</div>
) : null}
<div className="pointer-events-auto mt-0.5">
<SocialButton id="discord" label="Join our Discord while you wait!" layout='inline'/>
</div>
</div>
</div>
) : null}
</>
);
}
export default React.memo(TurnsOverlay);
@@ -0,0 +1,36 @@
import React from 'react';
import { useSessionSelector } from '../../../context/SessionContext.jsx';
import { useTelemetryFrame } from '../../../context/TelemetryContext.jsx';
import { buildBatteryVisual } from '../../../lib/battery.js';
import BatteryBar from '../../BatteryBar/index.jsx';
function VerticalBatteryOverlay({ show = false, roverId = null, sensors, batteryConfig, mobileHud = false }) {
const frame = useTelemetryFrame(roverId);
const rosterBatteryConfig = useSessionSelector((state) => {
if (!roverId) return null;
const roster = state.session?.roster || [];
const rover = roster.find((entry) => String(entry.id) === String(roverId));
return rover?.battery ?? null;
});
const resolvedSensors = sensors ?? frame?.sensors ?? null;
const resolvedBatteryConfig = batteryConfig ?? rosterBatteryConfig;
const batteryVisual = buildBatteryVisual({
charge: resolvedSensors?.batteryChargeMah ?? null,
config: resolvedBatteryConfig,
});
if (!show || !batteryVisual?.available) return null;
return (
<div className="pointer-events-none absolute right-1 top-1/2 flex h-[70%] -translate-y-1/2 flex-col items-center justify-center rounded bg-black/60 px-0.5 pb-1 pt-1">
<BatteryBar
visual={batteryVisual}
orientation="vertical"
variant="inline"
compact={mobileHud}
className="h-full w-4"
/>
</div>
);
}
export default React.memo(VerticalBatteryOverlay);
+3 -6
View File
@@ -3,16 +3,13 @@
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit. // Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import { useSessionSelector } from '../../context/SessionContext.jsx'; import { useSessionSelector } from '../../context/SessionContext.jsx';
import { useMemo } from 'react'; import { useMemo } from 'react';
import CardFrame from '../CardFrame/index.jsx';
export default function LogPanel() { export default function LogPanel() {
const logs = useSessionSelector((state) => state.logs); const logs = useSessionSelector((state) => state.logs);
const rendered = useMemo(() => logs.slice().reverse(), [logs]); const rendered = useMemo(() => logs.slice().reverse(), [logs]);
return ( return (
<div className="panel-section space-y-0.5 text-base"> <CardFrame title="Server logs" bodyClassName="space-y-0.5 text-base">
<div className="flex items-center justify-between text-sm text-slate-400">
<span>Server logs</span>
<span>{logs.length}</span>
</div>
<div className="surface h-64 overflow-y-auto font-mono text-xs"> <div className="surface h-64 overflow-y-auto font-mono text-xs">
{logs.length === 0 ? ( {logs.length === 0 ? (
<p>No logs yet.</p> <p>No logs yet.</p>
@@ -27,6 +24,6 @@ export default function LogPanel() {
)) ))
)} )}
</div> </div>
</div> </CardFrame>
); );
} }
@@ -18,6 +18,7 @@ import {
AUX_ALL_FORWARD, AUX_ALL_FORWARD,
AUX_ALL_BACKWARD, AUX_ALL_BACKWARD,
} from './constants.js'; } from './constants.js';
import { useManualDockAssist } from '../../features/manualDockAssist/useManualDockAssist.js';
function MobileJoystickPanel({ layout }) { function MobileJoystickPanel({ layout }) {
const { const {
@@ -99,6 +100,7 @@ function MobileActionsColumnContent({ layout }) {
pipeline, pipeline,
actions: { setServoAngle, setNightVision, setAuxMotors, startHorn, stopHorn }, actions: { setServoAngle, setNightVision, setAuxMotors, startHorn, stopHorn },
} = useControlSystem(); } = useControlSystem();
const dockAssist = useManualDockAssist();
const disabled = !roverId; const disabled = !roverId;
const activeRef = useRef(null); const activeRef = useRef(null);
const cameraConfig = camera?.config; const cameraConfig = camera?.config;
@@ -115,6 +117,7 @@ function MobileActionsColumnContent({ layout }) {
: typeof cameraConfig?.homeAngle === 'number' : typeof cameraConfig?.homeAngle === 'number'
? cameraConfig.homeAngle ? cameraConfig.homeAngle
: (cameraMin + cameraMax) / 2; : (cameraMin + cameraMax) / 2;
const cameraDisabled = Boolean(disabled || dockAssist.cameraLocked);
const handleNightVisionToggle = useCallback( const handleNightVisionToggle = useCallback(
(nextOn) => { (nextOn) => {
@@ -174,6 +177,7 @@ function MobileActionsColumnContent({ layout }) {
min={cameraMin} min={cameraMin}
max={cameraMax} max={cameraMax}
step={0.5} step={0.5}
disabled={cameraDisabled}
onChange={setServoAngle} onChange={setServoAngle}
orientation="vertical" orientation="vertical"
label="Camera Tilt" label="Camera Tilt"
+2 -16
View File
@@ -6,7 +6,6 @@ import AuthPanel from '../AuthPanel/index.jsx';
import { useSessionSelector } from '../../context/SessionContext.jsx'; import { useSessionSelector } from '../../context/SessionContext.jsx';
import SocialButton from '../SocialButton/index.jsx'; import SocialButton from '../SocialButton/index.jsx';
import ChatPanel from '../ChatPanel/index.jsx'; import ChatPanel from '../ChatPanel/index.jsx';
import NicknameForm from '../NicknameForm/index.jsx';
const PRIVILEGED_ROLES = new Set(['admin', 'lockdown', 'lockdown-admin']); const PRIVILEGED_ROLES = new Set(['admin', 'lockdown', 'lockdown-admin']);
const LOCKDOWN_ROLES = new Set(['lockdown', 'lockdown-admin']); const LOCKDOWN_ROLES = new Set(['lockdown', 'lockdown-admin']);
@@ -33,14 +32,6 @@ export default function ModeGateOverlay() {
const reason = useSessionSelector((state) => state.session?.adminReason?.text || ''); const reason = useSessionSelector((state) => state.session?.adminReason?.text || '');
const reasonUpdatedAt = useSessionSelector((state) => state.session?.adminReason?.updatedAt || null); const reasonUpdatedAt = useSessionSelector((state) => state.session?.adminReason?.updatedAt || null);
const timezone = useSessionSelector((state) => state.session?.timezone || 'UTC'); const timezone = useSessionSelector((state) => state.session?.timezone || 'UTC');
const discordUrl = useSessionSelector((state) => {
const socials = state.session?.socials || [];
const fromSocials = socials.find((entry) => {
const key = String(entry?.id || entry?.label || '').toLowerCase();
return key === 'discord';
})?.url;
return fromSocials || state.session?.discord?.invite || null;
});
const restricted = RESTRICTED_MODES.has(mode); const restricted = RESTRICTED_MODES.has(mode);
const privileged = mode === 'lockdown' ? LOCKDOWN_ROLES.has(role) : PRIVILEGED_ROLES.has(role); const privileged = mode === 'lockdown' ? LOCKDOWN_ROLES.has(role) : PRIVILEGED_ROLES.has(role);
const [now, setNow] = useState(() => new Date()); const [now, setNow] = useState(() => new Date());
@@ -92,17 +83,12 @@ export default function ModeGateOverlay() {
<AuthPanel /> <AuthPanel />
</div> </div>
<div className="w-full justify-center items-center"> <div className="w-full justify-center items-center">
<SocialButton <SocialButton id="discord" label="Join our Discord server for updates!"/>
id="discord"
label="Join our Discord server for updates!"
url={discordUrl}
/>
</div> </div>
You can still use the chat while the server is locked: You can still use the chat while the server is locked:
{/* set max height of this box */} {/* set max height of this box */}
<div className='max-h-80 overflow-y-auto'> <div className='max-h-80 overflow-y-auto'>
<ChatPanel /> <ChatPanel nicknameLayout="stacked" />
<NicknameForm />
</div> </div>
{/* <p className="text-xs text-slate-500"> {/* <p className="text-xs text-slate-500">
@@ -0,0 +1,50 @@
import { useSessionActions, useSessionSelector } from '../../context/SessionContext.jsx';
import { useSettingsNamespace } from '../../settings/index.js';
import CardFrame from '../CardFrame/index.jsx';
export default function OverseerPreferencePanel() {
const { identifySession } = useSessionActions();
const vote = useSessionSelector((state) => state.session?.overseerVote || null);
const { value: profile } = useSettingsNamespace('profile', { nickname: '' });
const { value: identity } = useSettingsNamespace('identity', { cookieUserId: '' });
const { value, save } = useSettingsNamespace('overseerPreference', { enabled: false });
const enabled = Boolean(value?.enabled);
const running = Boolean(vote?.running);
const onToggle = async (event) => {
const next = Boolean(event?.target?.checked);
await save((current) => ({ ...(current || {}), enabled: next }));
await identifySession({
cookieUserId: String(identity?.cookieUserId || '').trim(),
nickname: String(profile?.nickname || '').trim(),
overseerEnabled: next,
});
};
return (
<CardFrame title="Overseer vote" bodyClassName="space-y-0.5 text-center text-xs text-slate-200">
<label
className={`flex items-center justify-center gap-1.5 rounded px-1 py-0.5 ${
enabled ? 'bg-emerald-600/80 text-emerald-50' : 'bg-slate-600/70 text-slate-100'
}`}
>
<input type="checkbox" checked={enabled} onChange={onToggle} />
<span>Your vote: {enabled ? 'Yes' : 'No'}</span>
</label>
<span className="text-xs">Enable a local LLM in chat</span>
<div className="mt-0.5 text-slate-400">
Yes!: {Number(vote?.yesCount || 0)}, No...: {Number(vote?.noCount || 0)}
</div>
<div className="mt-0.5 flex justify-center">
<span
className={`inline-flex items-center rounded px-1.5 py-0.5 text-[0.7rem] font-medium ${
running ? 'bg-emerald-600/80 text-emerald-50' : 'bg-slate-600/70 text-slate-100'
}`}
>
{running ? 'Running!' : 'Stopped by vote.'}
</span>
</div>
</CardFrame>
);
}
@@ -4,7 +4,6 @@ import { formatKeyLabel } from '../../controls/keymapUtils.js';
import NicknameForm from '../NicknameForm/index.jsx'; import NicknameForm from '../NicknameForm/index.jsx';
import SocialButton from '../SocialButton/index.jsx'; import SocialButton from '../SocialButton/index.jsx';
import KeyPill from '../vip/VipAudioUploadCard/KeyPill.jsx'; import KeyPill from '../vip/VipAudioUploadCard/KeyPill.jsx';
import { useSessionSelector } from '../../context/SessionContext.jsx';
function ControlRow({ label, keyLabel }) { function ControlRow({ label, keyLabel }) {
return ( return (
@@ -30,7 +29,7 @@ function DesktopQuickstart({ keymap }) {
<ControlRow label="Move slower" keyLabel={formatKeyLabel(keymap?.slowModifier?.[0])} /> <ControlRow label="Move slower" keyLabel={formatKeyLabel(keymap?.slowModifier?.[0])} />
</div> </div>
</div> </div>
<p className="text-sm text-slate-200">3. When done, please dock your rover! Line up with the dock and press "Dock and Charge".</p> <p className="text-sm text-slate-200">3. When done, enter "Docking Assist" and line up the front sensor with the dock sensor.</p>
</div> </div>
); );
} }
@@ -41,7 +40,7 @@ function MobileQuickstart() {
<p>1. Press "Start Driving" put your rover into driving mode.</p> <p>1. Press "Start Driving" put your rover into driving mode.</p>
<p>2. Touch and hold in Joystick area to move.</p> <p>2. Touch and hold in Joystick area to move.</p>
<p>3. Use the other column for motor, horn, and camera controls.</p> <p>3. Use the other column for motor, horn, and camera controls.</p>
<p>4. When done, please dock your rover! Line up with the dock and press "Dock and Charge".</p> <p>4. When done, enter "Docking Assist" and line up the front sensor with the dock sensor.</p>
</div> </div>
); );
} }
@@ -56,15 +55,6 @@ export default function QuickstartOverlay({
}) { }) {
const { state } = useControlSystem(); const { state } = useControlSystem();
const isDesktop = layout === 'desktop'; const isDesktop = layout === 'desktop';
const discordUrl = useSessionSelector((sessionState) => {
const socials = sessionState.session?.socials || [];
const entry = socials.find((item) => {
const key = String(item?.id || item?.label || '').toLowerCase();
return key === 'discord';
});
return entry?.url || sessionState.session?.discord?.invite || null;
});
const keymap = useMemo(() => state?.keymap || {}, [state?.keymap]); const keymap = useMemo(() => state?.keymap || {}, [state?.keymap]);
if (!visible) return null; if (!visible) return null;
@@ -98,7 +88,7 @@ export default function QuickstartOverlay({
<div className="surface p-0.5"> <div className="surface p-0.5">
<p className="text-xl font-semibold text-slate-200">Join our Discord server!</p> <p className="text-xl font-semibold text-slate-200">Join our Discord server!</p>
<p className="text-sm font-semibold text-slate-200">We have an active and welcoming community :3</p> <p className="text-sm font-semibold text-slate-200">We have an active and welcoming community :3</p>
<SocialButton id="discord" label="Join Discord" url={discordUrl} /> <SocialButton id="discord" label="Join Discord" />
</div> </div>
</section> </section>
</div> </div>
@@ -5,6 +5,7 @@ import { useMemo } from 'react';
import { useSessionSelector } from '../../context/SessionContext.jsx'; import { useSessionSelector } from '../../context/SessionContext.jsx';
import NicknameForm from '../NicknameForm/index.jsx'; import NicknameForm from '../NicknameForm/index.jsx';
import SocialButtonsGrid from '../SocialButtonsGrid/index.jsx'; import SocialButtonsGrid from '../SocialButtonsGrid/index.jsx';
import CardFrame from '../CardFrame/index.jsx';
function roleColors(role) { function roleColors(role) {
switch (role) { switch (role) {
@@ -57,8 +58,13 @@ export default function RawUserPilePanel({
: 'h-48 overflow-y-auto'; : 'h-48 overflow-y-auto';
return ( return (
<section <CardFrame
className={`panel-section space-y-0.5 text-base ${fillHeight ? 'flex h-full min-h-0 flex-col overflow-hidden' : ''} ${className}`} title={!hideHeader ? 'Users' : ''}
hideHeader={hideHeader}
fillHeight={fillHeight}
className={className}
bodyClassName="space-y-0.5 text-base"
> >
{!hideNicknameForm && ( {!hideNicknameForm && (
<div className="space-y-0.5"> <div className="space-y-0.5">
@@ -75,12 +81,6 @@ export default function RawUserPilePanel({
)} )}
<div className={`space-y-0.5 ${fillHeight ? 'flex flex-1 min-h-0 flex-col' : ''}`}> <div className={`space-y-0.5 ${fillHeight ? 'flex flex-1 min-h-0 flex-col' : ''}`}>
{!hideHeader && (
<div className={`flex items-center justify-between text-sm text-slate-400 ${compact ? 'text-xs' : ''}`}>
<span>Users</span>
<span className="text-xs text-slate-500">{sorted.length}</span>
</div>
)}
<div <div
className={`surface flex flex-wrap content-start items-start gap-0.5 px-0 pb-0 ${baseListClass} ${compact ? 'text-[0.8rem]' : ''}`} className={`surface flex flex-wrap content-start items-start gap-0.5 px-0 pb-0 ${baseListClass} ${compact ? 'text-[0.8rem]' : ''}`}
> >
@@ -98,6 +98,6 @@ export default function RawUserPilePanel({
)} )}
</div> </div>
</div> </div>
</section> </CardFrame>
); );
} }
@@ -5,6 +5,7 @@ import { useEffect, useMemo, useState } from 'react';
import { useSessionActions, useSessionSelector } from '../../context/SessionContext.jsx'; import { useSessionActions, useSessionSelector } from '../../context/SessionContext.jsx';
import { useSettingsNamespace } from '../../settings/index.js'; import { useSettingsNamespace } from '../../settings/index.js';
import { roverNameChromeStyle } from '../../lib/roverColor.js'; import { roverNameChromeStyle } from '../../lib/roverColor.js';
import CardFrame from '../CardFrame/index.jsx';
function normalizeSources(list = []) { function normalizeSources(list = []) {
return list return list
@@ -63,13 +64,8 @@ export default function ReplaySourcesPanel({ panelId = 'replay-sources', fillHei
}, [users, selfSocketId, assignmentRoverId, roster]); }, [users, selfSocketId, assignmentRoverId, roster]);
useEffect(() => { useEffect(() => {
const saved = settings?.[panelId];
if (Array.isArray(saved) && saved.length) {
setSelected(saved);
return;
}
setSelected(defaults); setSelected(defaults);
}, [settings?.[panelId], defaults, panelId]); }, [defaults]);
useEffect(() => { useEffect(() => {
const saved = settings?.[`${panelId}:includeSidebar`]; const saved = settings?.[`${panelId}:includeSidebar`];
@@ -80,6 +76,16 @@ export default function ReplaySourcesPanel({ panelId = 'replay-sources', fillHei
setIncludeSidebar(true); setIncludeSidebar(true);
}, [settings?.[`${panelId}:includeSidebar`], panelId]); }, [settings?.[`${panelId}:includeSidebar`], panelId]);
useEffect(() => {
const saved = settings?.[`${panelId}:title`];
if (typeof saved === 'string') {
setTitle(saved);
setTitleDirty(true);
return;
}
setTitleDirty(false);
}, [settings?.[`${panelId}:title`], panelId]);
useEffect(() => { useEffect(() => {
if (!titleDirty) { if (!titleDirty) {
setTitle(defaultTitle); setTitle(defaultTitle);
@@ -116,9 +122,7 @@ export default function ReplaySourcesPanel({ panelId = 'replay-sources', fillHei
const toggleKey = (key) => { const toggleKey = (key) => {
setSelected((prev) => { setSelected((prev) => {
const next = prev.includes(key) ? prev.filter((value) => value !== key) : [...prev, key]; return prev.includes(key) ? prev.filter((value) => value !== key) : [...prev, key];
saveSettings((current) => ({ ...(current || {}), [panelId]: next }));
return next;
}); });
setSuccess(null); setSuccess(null);
}; };
@@ -143,15 +147,10 @@ export default function ReplaySourcesPanel({ panelId = 'replay-sources', fillHei
} }
}; };
const containerClass = fillHeight ? 'h-full flex flex-col' : '';
const listWrapClass = fillHeight ? 'flex-1 min-h-0 overflow-y-auto' : ''; const listWrapClass = fillHeight ? 'flex-1 min-h-0 overflow-y-auto' : '';
return ( return (
<section className={`panel-section p-0.75 text-sm ${containerClass}`}> <CardFrame title="Replay Sources" fillHeight={fillHeight} bodyClassName="space-y-0.5 text-sm">
<header className="panel-muted flex items-center justify-between text-xs">
<span>Replay Sources</span>
<span>{sources.length}</span>
</header>
<div className={`grid gap-0.5 md:grid-cols-2 ${listWrapClass}`}> <div className={`grid gap-0.5 md:grid-cols-2 ${listWrapClass}`}>
<GroupList title="Rovers" items={grouped.rovers} selected={selected} onToggle={toggleKey} /> <GroupList title="Rovers" items={grouped.rovers} selected={selected} onToggle={toggleKey} />
<GroupList title="Room Cams" items={grouped.rooms} selected={selected} onToggle={toggleKey} /> <GroupList title="Room Cams" items={grouped.rooms} selected={selected} onToggle={toggleKey} />
@@ -166,8 +165,10 @@ export default function ReplaySourcesPanel({ panelId = 'replay-sources', fillHei
className="field-input w-full text-xs" className="field-input w-full text-xs"
value={title} value={title}
onChange={(event) => { onChange={(event) => {
setTitle(event.target.value); const next = event.target.value;
setTitle(next);
setTitleDirty(true); setTitleDirty(true);
saveSettings((current) => ({ ...(current || {}), [`${panelId}:title`]: next }));
}} }}
placeholder={defaultTitle} placeholder={defaultTitle}
maxLength={120} maxLength={120}
@@ -196,7 +197,7 @@ export default function ReplaySourcesPanel({ panelId = 'replay-sources', fillHei
{error ? <div className="text-xs text-amber-400">{error}</div> : null} {error ? <div className="text-xs text-amber-400">{error}</div> : null}
{success ? <div className="text-xs text-emerald-300">{success}</div> : null} {success ? <div className="text-xs text-emerald-300">{success}</div> : null}
</div> </div>
</section> </CardFrame>
); );
} }
+12 -5
View File
@@ -6,7 +6,7 @@ import HomeAssistantControls from '../HomeAssistantControls/index.jsx';
import SettingsPanel from '../SettingsPanel/index.jsx'; import SettingsPanel from '../SettingsPanel/index.jsx';
import HelpPanel from '../HelpPanel/index.jsx'; import HelpPanel from '../HelpPanel/index.jsx';
import ChatPanel from '../ChatPanel/index.jsx'; import ChatPanel from '../ChatPanel/index.jsx';
import { LinkButtonsPanel, NicknameEntryPanel } from '../UserListPanel/index.jsx'; import { LinkButtonsPanel } from '../UserListPanel/index.jsx';
import ReplaySourcesPanel from '../ReplaySourcesPanel/index.jsx'; import ReplaySourcesPanel from '../ReplaySourcesPanel/index.jsx';
import Tabs, { Tab, TabList, TabPanel, TabPanels } from '../Tabs/index.jsx'; import Tabs, { Tab, TabList, TabPanel, TabPanels } from '../Tabs/index.jsx';
import TopDownMap from '../TopDownMap/index.jsx'; import TopDownMap from '../TopDownMap/index.jsx';
@@ -23,7 +23,10 @@ import VipPanel from '../VipPanel/index.jsx';
import { useSessionSelector } from '../../context/SessionContext.jsx'; import { useSessionSelector } from '../../context/SessionContext.jsx';
import { useSettingsNamespace } from '../../settings/index.js'; import { useSettingsNamespace } from '../../settings/index.js';
import ButtonBoxPanel from '../ButtonBoxPanel/index.jsx'; import ButtonBoxPanel from '../ButtonBoxPanel/index.jsx';
import OverseerPreferencePanel from '../OverseerPreferencePanel/index.jsx';
import CardFrame from '../CardFrame/index.jsx';
import { useState } from 'react'; import { useState } from 'react';
import { useManualDockAssist } from '../../features/manualDockAssist/useManualDockAssist.js';
function TopDownMapPanel() { function TopDownMapPanel() {
const { const {
@@ -33,11 +36,11 @@ function TopDownMapPanel() {
const sensors = frame?.sensors || {}; const sensors = frame?.sensors || {};
return ( return (
<section className="panel-section"> <CardFrame hideHeader>
<div className="aspect-square w-full"> <div className="aspect-square w-full">
<TopDownMap sensors={sensors} /> <TopDownMap sensors={sensors} />
</div> </div>
</section> </CardFrame>
); );
} }
@@ -47,6 +50,7 @@ function DriveDockPanel() {
pipeline, pipeline,
actions: { setServoAngle, setNightVision, startHorn, stopHorn }, actions: { setServoAngle, setNightVision, startHorn, stopHorn },
} = useControlSystem(); } = useControlSystem();
const dockAssist = useManualDockAssist();
const driveDockState = useDriveDockState(roverId); const driveDockState = useDriveDockState(roverId);
const hideInlineControls = driveDockState.docked && !driveDockState.driving; const hideInlineControls = driveDockState.docked && !driveDockState.driving;
@@ -68,6 +72,7 @@ function DriveDockPanel() {
const hornLabel = formatKeyLabel(keymap?.hornHonk?.[0]); const hornLabel = formatKeyLabel(keymap?.hornHonk?.[0]);
const upLabel = formatKeyLabel(keymap?.cameraUp?.[0]); const upLabel = formatKeyLabel(keymap?.cameraUp?.[0]);
const downLabel = formatKeyLabel(keymap?.cameraDown?.[0]); const downLabel = formatKeyLabel(keymap?.cameraDown?.[0]);
const cameraDisabled = Boolean(!roverId || dockAssist.cameraLocked);
return ( return (
<section className="panel-section grid h-full min-h-0 grid-rows-[minmax(0,1fr)_auto] gap-0.5"> <section className="panel-section grid h-full min-h-0 grid-rows-[minmax(0,1fr)_auto] gap-0.5">
@@ -97,6 +102,8 @@ function DriveDockPanel() {
value={value} value={value}
min={min} min={min}
max={max} max={max}
label="Camera tilt"
disabled={cameraDisabled}
onChange={setServoAngle} onChange={setServoAngle}
keyDownLabel={downLabel} keyDownLabel={downLabel}
keyUpLabel={upLabel} keyUpLabel={upLabel}
@@ -173,9 +180,9 @@ export default function RightPaneTabs({ layout, onOpenHelpOverlay }) {
</div> </div>
<div className="grid items-stretch gap-0.5 grid-cols-[minmax(0,1.3fr)_minmax(0,0.22fr)] h-[14rem]"> <div className="grid items-stretch gap-0.5 grid-cols-[minmax(0,1.3fr)_minmax(0,0.22fr)] h-[14rem]">
<ChatPanel fillHeight /> <ChatPanel fillHeight />
<div className="grid min-h-0 gap-0.5 grid-rows-[minmax(0,1fr)_auto]"> <div className="grid min-h-0 gap-0.5 grid-rows-[auto_minmax(0,1fr)]">
<OverseerPreferencePanel />
<RawUserPilePanel compact hideNicknameForm fillHeight /> <RawUserPilePanel compact hideNicknameForm fillHeight />
<NicknameEntryPanel compact />
</div> </div>
</div> </div>
<HomeAssistantControls /> <HomeAssistantControls />
+15 -17
View File
@@ -6,6 +6,7 @@ import { useSessionSelector } from '../../context/SessionContext.jsx';
import { useSettingsNamespace } from '../../settings/index.js'; import { useSettingsNamespace } from '../../settings/index.js';
import { useRoomCameraSnapshots } from '../../hooks/useRoomCameraSnapshots.js'; import { useRoomCameraSnapshots } from '../../hooks/useRoomCameraSnapshots.js';
import RoomCameraFeed from '../RoomCameraFeed/index.jsx'; import RoomCameraFeed from '../RoomCameraFeed/index.jsx';
import CardFrame from '../CardFrame/index.jsx';
function EmptyState() { function EmptyState() {
return ( return (
@@ -66,18 +67,9 @@ export default function RoomCameraPanel({
return <EmptyState />; return <EmptyState />;
} }
return ( const actions = showLayoutToggle ? (
<section className="panel-section space-y-0.5 text-base"> <div className="flex items-center gap-0.5 text-[0.68rem] text-slate-400">
{!hideHeader && ( <span>Layout</span>
<header className="flex flex-wrap items-center justify-between gap-0.5 text-sm text-slate-400">
<div className="flex items-center gap-0.5">
<p>Room cameras</p>
<span className="text-xs text-slate-500">{cameras.length}</span>
</div>
<div className="flex flex-wrap items-center gap-0.5 text-xs">
{showLayoutToggle && (
<div className="flex items-center gap-0.5">
<span className="text-slate-500">Layout:</span>
<div className="inline-flex overflow-hidden rounded border border-slate-700"> <div className="inline-flex overflow-hidden rounded border border-slate-700">
{ORIENTATIONS.map((option) => ( {ORIENTATIONS.map((option) => (
<button <button
@@ -91,10 +83,16 @@ export default function RoomCameraPanel({
))} ))}
</div> </div>
</div> </div>
)} ) : null;
</div>
</header> return (
)} <CardFrame
title="Room cameras"
actions={actions}
hideHeader={hideHeader}
bodyClassName="space-y-0.5 text-base"
>
<div className={containerClass}> <div className={containerClass}>
{cameras.map((camera) => { {cameras.map((camera) => {
const feed = feedMap[camera.id] || null; const feed = feedMap[camera.id] || null;
@@ -109,6 +107,6 @@ export default function RoomCameraPanel({
); );
})} })}
</div> </div>
</section> </CardFrame>
); );
} }
@@ -6,11 +6,3 @@ export const UNMUTE_RETRY_MS = 3000;
export const AUDIO_RETRY_MS = 3000; export const AUDIO_RETRY_MS = 3000;
export const BRUSH_CURRENT_THRESHOLD_MA = 40; export const BRUSH_CURRENT_THRESHOLD_MA = 40;
export const DUCK_RELEASE_FADE_MS = 1000; export const DUCK_RELEASE_FADE_MS = 1000;
export const OVERCURRENT_LABELS = {
leftWheel: 'Left wheel',
rightWheel: 'Right wheel',
mainBrush: 'Main brush',
sideBrush: 'Side brush',
limiter: 'Overcurrent limit',
};
@@ -1,21 +1,11 @@
// Video Tile
// Purpose: Defines the Video Tile module and the local helpers/components used in this file.
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { WhepPlayer } from '../../lib/whepPlayer.js'; import { WhepPlayer } from '../../lib/whepPlayer.js';
import { useHudMapSetting } from '../../hooks/useHudMapSetting.js'; import { useTelemetryFrame } from '../../context/TelemetryContext.jsx';
import { useSessionSelector } from '../../context/SessionContext.jsx'; import { useSessionSelector } from '../../context/SessionContext.jsx';
import { useVideoRequests } from '../../hooks/useVideoRequests.js';
import { useRoverSnapshots } from '../../hooks/useRoverSnapshots.js';
import { useSettingsNamespace } from '../../settings/index.js'; import { useSettingsNamespace } from '../../settings/index.js';
import { AUDIO_SETTINGS_DEFAULTS } from '../../settings/namespaces.js'; import { AUDIO_SETTINGS_DEFAULTS } from '../../settings/namespaces.js';
import SocialButton from '../SocialButton/index.jsx';
import BatteryBar from '../BatteryBar/index.jsx';
import { buildBatteryVisual } from '../../lib/battery.js';
import TurnCueOverlay from './TurnCueOverlay.jsx';
import HudOverlay from './HudOverlay.jsx';
import OvercurrentOverlay from './OvercurrentOverlay.jsx';
import LowBatteryOverlay from './LowBatteryOverlay.jsx';
import LightBumpBars from './LightBumpBars.jsx';
import HudChatInput from './HudChatInput.jsx';
import { import {
RESTART_DELAY_MS, RESTART_DELAY_MS,
UNMUTE_RETRY_MS, UNMUTE_RETRY_MS,
@@ -24,39 +14,54 @@ import {
DUCK_RELEASE_FADE_MS, DUCK_RELEASE_FADE_MS,
} from './constants.js'; } from './constants.js';
export default function VideoTile({ export default function RoverMediaPlayer({
sessionInfo, roverId = null,
audioSessionInfo, sessionInfo = null,
videoMode = 'whep', audioSessionInfo = null,
videoMode = null,
snapshotFeed = null, snapshotFeed = null,
qualityNotice = null,
label, label,
roverColor = null,
forceMute = false, forceMute = false,
telemetryFrame, sensors,
batteryConfig,
layoutFormat = 'desktop',
hudVariant = 'default',
driverLabel = null,
hudForceMap = false,
hudMapPosition = 'top-center',
hudLabelScale = 1,
fitParent = false,
overcurrentLimiter = null,
showTurnCue = false,
turnTimerText = null,
isActiveDriver = false,
idleSkipSeconds = null,
}) { }) {
const discordUrl = useSessionSelector((state) => { const assignedRoverId = useSessionSelector((state) => state.session?.assignment?.roverId ?? null);
const socials = state.session?.socials || []; const effectiveRoverId = roverId ?? assignedRoverId;
const socialUrl = const mode = useSessionSelector((state) => state.session?.mode || null);
socials.find((entry) => { const rosterEntry = useSessionSelector((state) =>
const key = String(entry?.id || entry?.label || '').toLowerCase(); effectiveRoverId && Array.isArray(state.session?.roster)
return key === 'discord'; ? state.session.roster.find((item) => String(item.id) === String(effectiveRoverId)) || null
})?.url || null; : null,
return socialUrl || state.session?.discord?.invite || null; );
const hasAudio = Boolean(rosterEntry?.media?.audioPublishUrl);
const autoVideoEnabled = videoMode ? videoMode === 'whep' : true;
const autoEntries = useMemo(() => {
if (!effectiveRoverId || !autoVideoEnabled) return [];
return [
{ type: 'rover', id: effectiveRoverId, key: effectiveRoverId },
...(hasAudio
? [{ type: 'rover', id: `${effectiveRoverId}-audio`, key: `${effectiveRoverId}-audio` }]
: []),
];
}, [effectiveRoverId, autoVideoEnabled, hasAudio]);
const autoSources = useVideoRequests(autoEntries, {
enabled: Boolean(effectiveRoverId && autoVideoEnabled),
version: mode,
}); });
const resolvedSessionInfo =
sessionInfo ?? (effectiveRoverId ? autoSources[effectiveRoverId] || null : null);
const resolvedAudioSessionInfo =
audioSessionInfo ??
(effectiveRoverId && hasAudio ? autoSources[`${effectiveRoverId}-audio`] || null : null);
const autoSnapshots = useRoverSnapshots(effectiveRoverId ? [effectiveRoverId] : [], {
enabled: Boolean(effectiveRoverId && !resolvedSessionInfo?.url),
version: mode,
});
const resolvedSnapshotFeed =
snapshotFeed ?? (effectiveRoverId ? autoSnapshots[effectiveRoverId] || null : null);
const resolvedLabel =
label || rosterEntry?.name || (effectiveRoverId ? `Rover ${effectiveRoverId}` : 'Rover');
const frame = useTelemetryFrame(effectiveRoverId);
const resolvedSensors = sensors ?? frame?.sensors ?? null;
const videoRef = useRef(null); const videoRef = useRef(null);
const audioRef = useRef(null); const audioRef = useRef(null);
const restartTimer = useRef(null); const restartTimer = useRef(null);
@@ -72,9 +77,8 @@ export default function VideoTile({
const [restartToken, setRestartToken] = useState(0); const [restartToken, setRestartToken] = useState(0);
const [audioRestartToken, setAudioRestartToken] = useState(0); const [audioRestartToken, setAudioRestartToken] = useState(0);
const [muted, setMuted] = useState(true); const [muted, setMuted] = useState(true);
const hasDedicatedAudio = Boolean(audioSessionInfo?.url); const hasDedicatedAudio = Boolean(resolvedAudioSessionInfo?.url);
const usingSnapshot = videoMode === 'snapshot'; const usingSnapshot = videoMode === 'snapshot' || (!videoMode && !resolvedSessionInfo?.url);
const sensors = telemetryFrame?.sensors;
const { value: audioSettings } = useSettingsNamespace('audio', AUDIO_SETTINGS_DEFAULTS); const { value: audioSettings } = useSettingsNamespace('audio', AUDIO_SETTINGS_DEFAULTS);
const masterVolume = Number.isFinite(audioSettings?.masterVolume) const masterVolume = Number.isFinite(audioSettings?.masterVolume)
? audioSettings.masterVolume ? audioSettings.masterVolume
@@ -92,63 +96,21 @@ export default function VideoTile({
? Math.max(0, Math.min(1, audioSettings.mainBrushDuckAmount)) ? Math.max(0, Math.min(1, audioSettings.mainBrushDuckAmount))
: AUDIO_SETTINGS_DEFAULTS.mainBrushDuckAmount; : AUDIO_SETTINGS_DEFAULTS.mainBrushDuckAmount;
const baseRoverGain = Math.max(0, Math.min(1, masterVolume * roverVolume)); const baseRoverGain = Math.max(0, Math.min(1, masterVolume * roverVolume));
const batteryCharge = sensors?.batteryChargeMah ?? null;
const desktopLayout = layoutFormat === 'desktop';
const mobileHud = !desktopLayout;
const effectiveHudMapPosition = mobileHud ? 'top-right' : hudMapPosition;
const [showHudMapDesktop] = useHudMapSetting();
const showHudMap = hudForceMap ? true : mobileHud ? true : showHudMapDesktop;
const batteryVisual = buildBatteryVisual({ charge: batteryCharge, config: batteryConfig });
const wheelOvercurrents = sensors?.wheelOvercurrents || null;
const overcurrentMotors = useMemo(
() =>
wheelOvercurrents == null
? []
: Object.entries(wheelOvercurrents)
.filter(([, active]) => Boolean(active))
.map(([key]) => key),
[wheelOvercurrents],
);
const limiterCaps = overcurrentLimiter?.caps || null;
const limiterGroups = overcurrentLimiter?.overcurrent?.groups || null;
const debugFlags = useMemo(() => {
if (typeof window === 'undefined') {
return { debugAudio: false, debugHud: false };
}
const params = new URLSearchParams(window.location.search);
return {
debugAudio: params.has('debugAudio'),
debugHud: params.has('debugHud'),
};
}, []);
const debugAudio = debugFlags.debugAudio;
const debugHud = debugFlags.debugHud;
const limiterFill = useMemo(() => {
if (!limiterCaps) return null;
const driveCap = Number.isFinite(limiterCaps?.drive?.cap) ? limiterCaps.drive.cap : 1;
const auxCap = Number.isFinite(limiterCaps?.aux?.cap) ? limiterCaps.aux.cap : 1;
return Math.max(0, Math.min(1, 1 - Math.min(driveCap, auxCap)));
}, [limiterCaps]);
const limiterActive = Boolean(overcurrentLimiter?.isActive);
const overlayState = useMemo(() => {
const motors = overcurrentMotors.length ? overcurrentMotors : limiterActive ? ['limiter'] : [];
const fill = limiterFill ?? (overcurrentMotors.length ? 1 : 0);
return {
motors,
fill,
visible: Boolean(motors.length),
};
}, [overcurrentMotors, limiterActive, limiterFill]);
const mainBrushActive = Boolean( const mainBrushActive = Boolean(
(Number(sensors?.mainBrushCurrentMa) || 0) > BRUSH_CURRENT_THRESHOLD_MA || (Number(resolvedSensors?.mainBrushCurrentMa) || 0) > BRUSH_CURRENT_THRESHOLD_MA ||
sensors?.wheelOvercurrents?.mainBrush, resolvedSensors?.wheelOvercurrents?.mainBrush,
); );
const duckGain = mainBrushDuckEnabled && mainBrushActive ? 1 - mainBrushDuckAmount : 1; const duckGain = mainBrushDuckEnabled && mainBrushActive ? 1 - mainBrushDuckAmount : 1;
const effectiveRoverGain = Math.max(0, Math.min(1, baseRoverGain * duckGain)); const effectiveRoverGain = Math.max(0, Math.min(1, baseRoverGain * duckGain));
const levelIndicator =
mainBrushDuckEnabled && mainBrushActive && mainBrushDuckAmount > 0 const debugAudio = useMemo(() => {
? `Volume decreased ${Math.round(mainBrushDuckAmount * 1000) / 10}%` if (typeof window === 'undefined') {
: null; return false;
}
const params = new URLSearchParams(window.location.search);
return params.has('debugAudio');
}, []);
const audioDebugStateRef = useRef({ const audioDebugStateRef = useRef({
hasDedicatedAudio: false, hasDedicatedAudio: false,
audioUrl: null, audioUrl: null,
@@ -161,7 +123,7 @@ export default function VideoTile({
useEffect(() => { useEffect(() => {
audioDebugStateRef.current = { audioDebugStateRef.current = {
hasDedicatedAudio, hasDedicatedAudio,
audioUrl: audioSessionInfo?.url || null, audioUrl: resolvedAudioSessionInfo?.url || null,
mainBrushDuckEnabled, mainBrushDuckEnabled,
mainBrushDuckAmount, mainBrushDuckAmount,
mainBrushActive, mainBrushActive,
@@ -170,13 +132,14 @@ export default function VideoTile({
}; };
}, [ }, [
hasDedicatedAudio, hasDedicatedAudio,
audioSessionInfo?.url, resolvedAudioSessionInfo?.url,
mainBrushDuckEnabled, mainBrushDuckEnabled,
mainBrushDuckAmount, mainBrushDuckAmount,
mainBrushActive, mainBrushActive,
baseRoverGain, baseRoverGain,
effectiveRoverGain, effectiveRoverGain,
]); ]);
const logAudio = useCallback( const logAudio = useCallback(
(event, meta = {}) => { (event, meta = {}) => {
if (!debugAudio) return; if (!debugAudio) return;
@@ -185,7 +148,7 @@ export default function VideoTile({
const payload = { const payload = {
event, event,
ts: Date.now(), ts: Date.now(),
roverLabel: label || null, roverLabel: resolvedLabel || null,
hasDedicatedAudio: state.hasDedicatedAudio, hasDedicatedAudio: state.hasDedicatedAudio,
audioUrl: state.audioUrl, audioUrl: state.audioUrl,
mainBrushDuckEnabled: state.mainBrushDuckEnabled, mainBrushDuckEnabled: state.mainBrushDuckEnabled,
@@ -211,20 +174,8 @@ export default function VideoTile({
console.log('[AudioDebug]', event, payload); console.log('[AudioDebug]', event, payload);
} }
}, },
[debugAudio, label], [debugAudio, resolvedLabel],
); );
useEffect(() => {
if (!debugHud) return;
console.log('[OvercurrentHUD]', {
overlayVisible: overlayState.visible,
overlayMotors: overlayState.motors,
overlayFill: overlayState.fill,
limiterActive,
limiterCaps,
limiterGroups,
wheelOvercurrents,
});
}, [debugHud, overlayState, limiterActive, limiterCaps, limiterGroups, wheelOvercurrents]);
useEffect(() => { useEffect(() => {
logAudio('settings/update'); logAudio('settings/update');
@@ -312,7 +263,7 @@ export default function VideoTile({
}, [usingSnapshot]); }, [usingSnapshot]);
useEffect(() => { useEffect(() => {
if (usingSnapshot || !sessionInfo?.url || !videoRef.current) { if (usingSnapshot || !resolvedSessionInfo?.url || !videoRef.current) {
return undefined; return undefined;
} }
let active = true; let active = true;
@@ -332,8 +283,8 @@ export default function VideoTile({
}; };
player = new WhepPlayer({ player = new WhepPlayer({
url: sessionInfo.url, url: resolvedSessionInfo.url,
token: sessionInfo.token, token: resolvedSessionInfo.token,
video: videoRef.current, video: videoRef.current,
receiveAudio: !hasDedicatedAudio, receiveAudio: !hasDedicatedAudio,
onStatus: handleStatus, onStatus: handleStatus,
@@ -351,17 +302,26 @@ export default function VideoTile({
clearTimeout(resetMuteId); clearTimeout(resetMuteId);
player?.stop(); player?.stop();
}; };
}, [usingSnapshot, sessionInfo?.url, sessionInfo?.token, restartToken, scheduleRestart, ensurePlayback, hasDedicatedAudio, logAudio]); }, [
usingSnapshot,
resolvedSessionInfo?.url,
resolvedSessionInfo?.token,
restartToken,
scheduleRestart,
ensurePlayback,
hasDedicatedAudio,
logAudio,
]);
useEffect(() => { useEffect(() => {
if (status === 'stopped' && sessionInfo?.url) { if (status === 'stopped' && resolvedSessionInfo?.url) {
scheduleRestart(); scheduleRestart();
} }
}, [status, sessionInfo?.url, scheduleRestart]); }, [status, resolvedSessionInfo?.url, scheduleRestart]);
useEffect(() => { useEffect(() => {
const audioEl = audioRef.current; const audioEl = audioRef.current;
if (!audioEl || !audioSessionInfo?.url) { if (!audioEl || !resolvedAudioSessionInfo?.url) {
logAudio('route/no-audio-url'); logAudio('route/no-audio-url');
appliedVolumeRef.current = null; appliedVolumeRef.current = null;
return; return;
@@ -402,7 +362,7 @@ export default function VideoTile({
duckAmount: mainBrushDuckAmount, duckAmount: mainBrushDuckAmount,
}); });
}, [ }, [
audioSessionInfo?.url, resolvedAudioSessionInfo?.url,
effectiveRoverGain, effectiveRoverGain,
mainBrushDuckEnabled, mainBrushDuckEnabled,
mainBrushActive, mainBrushActive,
@@ -410,9 +370,8 @@ export default function VideoTile({
logAudio, logAudio,
]); ]);
// Audio-only WHEP (no pausing/muting; keeps trying to play)
useEffect(() => { useEffect(() => {
if (!audioSessionInfo?.url || !audioRef.current) { if (!resolvedAudioSessionInfo?.url || !audioRef.current) {
return undefined; return undefined;
} }
let active = true; let active = true;
@@ -420,24 +379,16 @@ export default function VideoTile({
const handleStatus = (nextStatus, info) => { const handleStatus = (nextStatus, info) => {
if (!active) return; if (!active) return;
logAudio('audio/status', { nextStatus, info: info || null }); logAudio('audio/status', { nextStatus, info: info || null });
setAudioDetail(info || (nextStatus === 'connected' ? 'connected' : null)); setAudioStatus(nextStatus);
setAudioStatus((prev) => { setAudioDetail(info || null);
if (nextStatus === 'connected' && (prev === 'playing' || prev === 'connecting')) {
return prev;
}
if (nextStatus === 'new') {
return prev;
}
return nextStatus;
});
if (['error', 'failed'].includes(nextStatus)) { if (['error', 'failed'].includes(nextStatus)) {
scheduleAudioRestart(); scheduleAudioRestart();
} }
}; };
player = new WhepPlayer({ player = new WhepPlayer({
url: audioSessionInfo.url, url: resolvedAudioSessionInfo.url,
token: audioSessionInfo.token, token: resolvedAudioSessionInfo.token,
video: audioRef.current, video: audioRef.current,
audioOnly: true, audioOnly: true,
onStatus: handleStatus, onStatus: handleStatus,
@@ -455,17 +406,16 @@ export default function VideoTile({
player?.stop(); player?.stop();
}; };
}, [ }, [
audioSessionInfo?.url, resolvedAudioSessionInfo?.url,
audioSessionInfo?.token, resolvedAudioSessionInfo?.token,
audioRestartToken, audioRestartToken,
scheduleAudioRestart, scheduleAudioRestart,
logAudio, logAudio,
]); ]);
// Keep nudging the audio element to play in case autoplay was blocked.
useEffect(() => { useEffect(() => {
const audioEl = audioRef.current; const audioEl = audioRef.current;
if (!audioSessionInfo?.url || !audioEl) { if (!resolvedAudioSessionInfo?.url || !audioEl) {
clearInterval(audioPlayInterval.current); clearInterval(audioPlayInterval.current);
return undefined; return undefined;
} }
@@ -498,13 +448,8 @@ export default function VideoTile({
audioPlayInterval.current = setInterval(attemptPlay, AUDIO_RETRY_MS); audioPlayInterval.current = setInterval(attemptPlay, AUDIO_RETRY_MS);
return () => clearInterval(audioPlayInterval.current); return () => clearInterval(audioPlayInterval.current);
}, [ }, [resolvedAudioSessionInfo?.url, audioStatus, logAudio]);
audioSessionInfo?.url,
audioStatus,
logAudio,
]);
// Reflect audio element events back into status/detail so the HUD stays accurate.
useEffect(() => { useEffect(() => {
const audioEl = audioRef.current; const audioEl = audioRef.current;
if (!audioEl) return undefined; if (!audioEl) return undefined;
@@ -555,44 +500,43 @@ export default function VideoTile({
audioEl.removeEventListener('canplay', handleCanPlay); audioEl.removeEventListener('canplay', handleCanPlay);
audioEl.removeEventListener('stalled', handleStalled); audioEl.removeEventListener('stalled', handleStalled);
}; };
}, [audioSessionInfo?.url, logAudio]); }, [resolvedAudioSessionInfo?.url, logAudio]);
const snapshotStatus = snapshotFeed?.error const snapshotStatus = resolvedSnapshotFeed?.error
? `Error: ${snapshotFeed.error}` ? `Error: ${resolvedSnapshotFeed.error}`
: snapshotFeed?.objectUrl : resolvedSnapshotFeed?.objectUrl
? 'snapshot' ? 'snapshot'
: snapshotFeed?.status || 'waiting'; : resolvedSnapshotFeed?.status || 'waiting';
const renderedStatus = usingSnapshot const renderedStatus = usingSnapshot
? snapshotStatus ? snapshotStatus
: !sessionInfo?.url : !resolvedSessionInfo?.url
? 'waiting' ? 'waiting'
: status === 'error' : status === 'error'
? `Error: ${detail || 'unknown'}` ? `Error: ${detail || 'unknown'}`
: detail : detail
? `${status} (${detail})` ? `${status} (${detail})`
: status; : status;
const renderedAudioStatus = audioSessionInfo?.error const renderedAudioStatus = resolvedAudioSessionInfo?.error
? `Error: ${audioSessionInfo.error}` ? `Error: ${resolvedAudioSessionInfo.error}`
: !audioSessionInfo?.url : !resolvedAudioSessionInfo?.url
? null ? null
: audioStatus === 'error' : audioStatus === 'error'
? `Error: ${audioDetail || 'unknown'}` ? `Error: ${audioDetail || 'unknown'}`
: audioDetail : audioDetail
? `${audioStatus} (${audioDetail})` ? `${audioStatus} (${audioDetail})`
: audioStatus; : audioStatus;
const showVerticalBattery = hudVariant === 'spectator'; const showConnectingOverlay =
const noHud = hudVariant === 'none'; !usingSnapshot &&
!resolvedSessionInfo?.error &&
['idle', 'new', 'connecting'].includes(status);
return ( return (
<div className={`flex flex-col gap-0.5 ${fitParent ? 'h-full' : ''}`}> <>
<div
className={`relative w-full overflow-hidden bg-black ${fitParent ? 'h-full flex-1' : 'aspect-[4/3]'}`}
>
{usingSnapshot ? ( {usingSnapshot ? (
snapshotFeed?.objectUrl ? ( resolvedSnapshotFeed?.objectUrl ? (
<img <img
src={snapshotFeed.objectUrl} src={resolvedSnapshotFeed.objectUrl}
alt={label} alt={resolvedLabel}
className="h-full w-full object-contain" className="h-full w-full object-contain"
draggable={false} draggable={false}
/> />
@@ -611,80 +555,20 @@ export default function VideoTile({
className="h-full w-full object-contain" className="h-full w-full object-contain"
/> />
)} )}
{showConnectingOverlay ? (
<div className="pointer-events-none absolute inset-0 z-10 flex items-center justify-center bg-black/45">
<div className="rounded border border-slate-500/70 bg-black/70 px-3 py-1 text-sm font-semibold text-slate-100">
Connecting to video....
</div>
</div>
) : null}
<audio ref={audioRef} autoPlay hidden /> <audio ref={audioRef} autoPlay hidden />
{!noHud && showTurnCue ? ( <div className="pointer-events-none absolute left-1 top-1 z-20 font-medium text-slate-100 text-[0.65rem]">
<TurnCueOverlay <div className="flex flex-col gap-0.5 leading-none">
mobileHud={mobileHud} <span>Status: {renderedStatus}</span>
isActiveDriver={isActiveDriver} {renderedAudioStatus ? <span>Audio: {renderedAudioStatus}</span> : null}
idleSkipSeconds={idleSkipSeconds}
/>
) : null}
{!noHud ? (
<HudOverlay
sensors={sensors}
label={label}
roverColor={roverColor}
status={renderedStatus}
audioStatus={renderedAudioStatus}
levelStatus={levelIndicator}
layoutFormat={layoutFormat}
variant={hudVariant}
driverLabel={driverLabel}
showTopDown={showHudMap}
mobileHud={mobileHud}
mapPosition={effectiveHudMapPosition}
turnTimerText={turnTimerText}
labelScale={hudLabelScale}
/>
) : null}
{!noHud ? <HudChatInput compact={mobileHud} /> : null}
{!noHud && debugHud ? (
<div className="pointer-events-none absolute left-1 top-1 z-40 rounded bg-black/80 px-1 py-0.5 text-[0.6rem] text-lime-200">
{`OC vis:${overlayState.visible ? 1 : 0} motors:${overlayState.motors.length} fill:${Math.round(
overlayState.fill * 100,
)}%`}
</div>
) : null}
{!noHud ? <OvercurrentOverlay motors={overlayState.motors} fill={overlayState.fill} compact={mobileHud} /> : null}
{!noHud ? <LowBatteryOverlay battery={batteryVisual} compact={mobileHud} /> : null}
{!noHud && showVerticalBattery && batteryVisual.available ? (
<div className="pointer-events-none absolute right-1 top-1/2 flex h-[70%] -translate-y-1/2 flex-col items-center justify-center rounded bg-black/60 px-0.5 pb-1 pt-1">
<BatteryBar
visual={batteryVisual}
orientation="vertical"
variant="inline"
compact={mobileHud}
className="h-full w-4"
/>
</div>
) : null}
{!noHud && qualityNotice ? (
<div className="pointer-events-none absolute inset-x-0 top-1/2 -translate-y-1/2">
<div
className={`mx-auto w-fit rounded border border-amber-300/80 bg-black/75 text-amber-200 ${
mobileHud ? 'px-2 py-1 text-[0.6rem]' : 'px-3 py-1.5 text-sm'
}`}
>
<div className="text-center">{qualityNotice}</div>
<div className="pointer-events-auto mt-0">
<SocialButton
id="discord"
label="Join our Discord server while you wait!"
url={discordUrl}
/>
</div> </div>
</div> </div>
</div> </>
) : null}
</div>
{!noHud && !showVerticalBattery && (
<div className="space-y-0.5">
<LightBumpBars sensors={sensors} />
<div className="panel-section space-y-0.5 text-sm">
<BatteryBar visual={batteryVisual} compact={mobileHud} />
</div>
</div>
)}
</div>
); );
} }
@@ -4,6 +4,7 @@
import { useEffect, useMemo, useState } from 'react'; import { useEffect, useMemo, useState } from 'react';
import { useSessionActions, useSessionSelector } from '../../context/SessionContext.jsx'; import { useSessionActions, useSessionSelector } from '../../context/SessionContext.jsx';
import { roverNameChromeStyle } from '../../lib/roverColor.js'; import { roverNameChromeStyle } from '../../lib/roverColor.js';
import CardFrame from '../CardFrame/index.jsx';
function classNames(...values) { function classNames(...values) {
return values.filter(Boolean).join(' '); return values.filter(Boolean).join(' ');
@@ -96,8 +97,7 @@ export default function RoverQueuesPanel({ title = 'Rovers' }) {
users.find((u) => u.socketId === socketId) || { socketId, nickname: null, role: null }; users.find((u) => u.socketId === socketId) || { socketId, nickname: null, role: null };
return ( return (
<div className="space-y-0.5 text-sm"> <CardFrame title={title} bodyClassName="space-y-0.5 text-sm">
{title && <p className="text-sm text-slate-400">{title}</p>}
{rosterItems.length === 0 ? ( {rosterItems.length === 0 ? (
<p className="text-sm text-slate-500">No rovers registered.</p> <p className="text-sm text-slate-500">No rovers registered.</p>
) : ( ) : (
@@ -145,11 +145,16 @@ export default function RoverQueuesPanel({ title = 'Rovers' }) {
> >
<div className="flex min-w-0 flex-1 flex-col gap-0.5"> <div className="flex min-w-0 flex-1 flex-col gap-0.5">
<div className="flex items-center justify-between gap-0.5"> <div className="flex items-center justify-between gap-0.5">
<div className="flex items-center gap-0.5"> <div className="flex min-w-0 items-center gap-0.5">
<p className="text-slate-200"> <p className="min-w-0 flex items-center gap-0.5 whitespace-nowrap text-slate-200">
<span className="rounded px-1 py-[1px] border border-transparent" style={roverNameChromeStyle(rover.color, 0.16)}> <span className="rounded px-1 py-[1px] border border-transparent" style={roverNameChromeStyle(rover.color, 0.16)}>
{rover.name} {rover.name}
</span> </span>
{rover.description ? (
<span className="min-w-0 flex-1 truncate text-[0.7rem] text-slate-400">
{rover.description}
</span>
) : null}
</p> </p>
{showTimer ? ( {showTimer ? (
<span className="rounded bg-slate-800 px-1 text-[0.7rem] text-slate-200"> <span className="rounded bg-slate-800 px-1 text-[0.7rem] text-slate-200">
@@ -211,6 +216,6 @@ export default function RoverQueuesPanel({ title = 'Rovers' }) {
})} })}
</ul> </ul>
)} )}
</div> </CardFrame>
); );
} }
+41 -79
View File
@@ -1,97 +1,59 @@
// Social Button // Social Button
// Purpose: Defines the Social Button module and the local helpers/components used in this file. // Purpose: Defines the Social Button module and the local helpers/components used in this file.
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit. // Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import { useEffect } from 'react'; import * as FaIcons from 'react-icons/fa';
import { FaBook, FaCoffee, FaCrown, FaDiscord, FaLink } from 'react-icons/fa'; import { FaLink } from 'react-icons/fa';
import { useSessionSelector } from '../../context/SessionContext.jsx';
import { getSocialById } from '../../lib/socials.js';
const ICONS_BY_ID = { function sanitizeCssColor(value) {
discord: FaDiscord, if (typeof value !== 'string') return null;
kofi: FaCoffee, const trimmed = value.trim();
'ko-fi': FaCoffee, if (!trimmed) return null;
wiki: FaBook, if (/^#[0-9a-fA-F]{3,8}$/.test(trimmed)) return trimmed;
throne: FaCrown, if (/^(rgb|rgba|hsl|hsla)\([^)]+\)$/.test(trimmed)) return trimmed;
}; return null;
const GRADIENT_STYLE_BY_ID = {
discord: {
backgroundImage:
'linear-gradient(270deg,#5865F2,#404EED,#5865F2)',
backgroundSize: '600% 600%',
animation: 'socialGradient 180s ease infinite',
},
kofi: {
backgroundImage: 'linear-gradient(270deg,#FF6433,#E04822,#FF6433)',
backgroundSize: '600% 600%',
animation: 'socialGradient 170s ease infinite',
},
'ko-fi': {
backgroundImage: 'linear-gradient(270deg,#FF6433,#E04822,#FF6433)',
backgroundSize: '600% 600%',
animation: 'socialGradient 170s ease infinite',
},
wiki: {
backgroundImage: 'linear-gradient(270deg,#EE8019,#C65C08,#EE8019)',
backgroundSize: '600% 600%',
animation: 'socialGradient 180s ease infinite',
},
throne: {
backgroundImage: 'linear-gradient(270deg,#7C3AED,#5B21B6,#7C3AED)',
backgroundSize: '600% 600%',
animation: 'socialGradient 180s ease infinite',
},
};
function useSocialButtonStyles() {
useEffect(() => {
if (typeof document === 'undefined') return;
const styleId = 'social-button-keyframes';
if (document.getElementById(styleId)) return;
const style = document.createElement('style');
style.id = styleId;
style.textContent = `
@keyframes socialGradient {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
`;
document.head.appendChild(style);
}, []);
} }
function normalizeId(id, label) { function resolveIcon(iconName) {
if (typeof id === 'string' && id.trim()) return id.trim().toLowerCase(); if (typeof iconName !== 'string' || !iconName.trim()) return FaLink;
if (typeof label === 'string' && label.trim()) { const icon = FaIcons[iconName.trim()];
return label return typeof icon === 'function' ? icon : FaLink;
.trim()
.toLowerCase()
.replace(/\s+/g, '-')
.replace(/[^a-z0-9-]/g, '');
}
return '';
} }
export default function SocialButton({ id, label, url, className = '' }) { export default function SocialButton({ id = null, label, url, icon, color, layout = 'stacked', className = '' }) {
if (!url) return null; const socialFromId = useSessionSelector((state) => (id ? getSocialById(state, id) : null));
useSocialButtonStyles(); const resolvedUrl = url || socialFromId?.url || null;
const key = normalizeId(id, label); if (!resolvedUrl) return null;
const Icon = ICONS_BY_ID[key] || FaLink; const resolvedIcon = icon || socialFromId?.icon || null;
const gradientStyle = GRADIENT_STYLE_BY_ID[key] || null; const resolvedColor = color || socialFromId?.color || null;
const text = label || id || 'Link'; const Icon = resolveIcon(resolvedIcon);
const bgColor = sanitizeCssColor(resolvedColor);
const text = label || socialFromId?.label || 'Link';
const isInline = layout === 'inline';
return ( return (
<a <a
href={url} href={resolvedUrl}
target="_blank" target="_blank"
rel="noopener noreferrer" rel="noopener noreferrer"
aria-label={text} aria-label={text}
className={`inline-flex items-center w-full px-0.5 py-0.5 text-sm font-medium text-white transition justify-center gap-1 rounded-md ${ className={`grid h-full min-h-0 w-full place-items-center rounded-md bg-slate-700 px-0.5 ${isInline ? 'py-0.5' : 'pb-3'} text-center text-sm font-medium text-white transition hover:opacity-90 ${className}`}
gradientStyle ? '' : 'bg-slate-700 hover:bg-slate-600' style={bgColor ? { backgroundColor: bgColor } : undefined}
} ${className}`}
style={gradientStyle || undefined}
> >
<Icon className="mr-0" /> {isInline ? (
{text} <span className="inline-flex max-w-full items-center justify-center gap-1 text-center leading-tight">
<Icon className="shrink-0" style={{ fontSize: '1.1em' }} />
<span className="break-words">{text}</span>
</span>
) : (
<span className="flex h-full w-full max-w-full flex-col items-center justify-between text-center leading-tight">
<span className="flex min-h-0 flex-1 items-center justify-center">
<Icon className="shrink-0" style={{ fontSize: 'clamp(1rem, 2.2vh + 1.2vw, 3rem)' }} />
</span>
<span className="w-full break-words leading-tight">{text}</span>
</span>
)}
</a> </a>
); );
} }
@@ -4,46 +4,18 @@
import { useSessionSelector } from '../../context/SessionContext.jsx'; import { useSessionSelector } from '../../context/SessionContext.jsx';
import SocialButton from '../SocialButton/index.jsx'; import SocialButton from '../SocialButton/index.jsx';
function normalizeSocials({ socials, discordInvite, kofiLink }) {
const configured = Array.isArray(socials) ? socials : null;
if (configured && configured.length) {
return configured;
}
const fallback = [];
if (discordInvite) {
fallback.push({ id: 'discord', label: 'Discord', url: discordInvite });
}
if (kofiLink) {
fallback.push({ id: 'kofi', label: 'Ko-fi', url: kofiLink });
}
return fallback;
}
function normalizeEntry(entry) {
if (!entry || typeof entry !== 'object') return null;
const id = entry.id || entry.service || entry.key || entry.name || null;
const label = entry.label || entry.title || entry.name || id || 'Link';
const url = entry.url || entry.link || entry.href || null;
return url ? { id, label, url } : null;
}
export default function SocialButtonsGrid({ className = '' }) { export default function SocialButtonsGrid({ className = '' }) {
const socialsInput = useSessionSelector((state) => ({ const socials = useSessionSelector((state) => state.session?.socials ?? []).slice(0, 4);
socials: state.session?.socials ?? [],
discordInvite: state.session?.discord?.invite || null,
kofiLink: state.session?.kofi?.link || null,
}));
const socials = normalizeSocials(socialsInput)
.map(normalizeEntry)
.filter(Boolean)
.slice(0, 4);
if (!socials.length) return null; if (!socials.length) return null;
return ( return (
<div className={`grid grid-cols-2 grid-rows-2 gap-0.5 ${className}`}> <div className={`grid grid-cols-2 grid-rows-2 gap-0.5 ${className}`}>
{socials.map((entry) => ( {socials.map((entry) => (
<SocialButton key={`${entry.id || entry.label}-${entry.url}`} {...entry} /> <SocialButton
key={`${entry?.id || entry?.label || 'social'}-${entry?.url || ''}`}
id={entry?.id || entry?.key || entry?.service || null}
/>
))} ))}
</div> </div>
); );
@@ -0,0 +1,39 @@
import RoverMediaPlayer from '../RoverMediaPlayer/index.jsx';
import HudOverlay from '../HudOverlays/HudOverlay/index.jsx';
import RoverDescriptionOverlay from '../HudOverlays/RoverDescriptionOverlay/index.jsx';
import OvercurrentOverlay from '../HudOverlays/OvercurrentOverlay/index.jsx';
import LowBatteryOverlay from '../HudOverlays/LowBatteryOverlay/index.jsx';
import VerticalBatteryOverlay from '../HudOverlays/VerticalBatteryOverlay/index.jsx';
export default function SpectateVideo({
roverId = null,
label,
fitParent = false,
layoutFormat = 'desktop',
}) {
return (
<div className={`flex flex-col gap-0.5 ${fitParent ? 'h-full' : ''}`}>
<div className={`relative w-full overflow-hidden bg-black ${fitParent ? 'h-full flex-1' : 'aspect-[4/3]'}`}>
<RoverMediaPlayer
roverId={roverId}
label={label}
/>
<RoverDescriptionOverlay
roverId={roverId}
variant="spectator"
mobileHud={false}
/>
<HudOverlay
roverId={roverId}
layoutFormat={layoutFormat}
variant="spectator"
mobileHud={false}
labelScale={1}
/>
<OvercurrentOverlay roverId={roverId} compact={false} />
<LowBatteryOverlay roverId={roverId} compact={false} />
<VerticalBatteryOverlay show roverId={roverId} mobileHud={false} />
</div>
</div>
);
}
+49 -1
View File
@@ -2,6 +2,7 @@
// Purpose: Defines the Tabs module and the local helpers/components used in this file. // Purpose: Defines the Tabs module and the local helpers/components used in this file.
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit. // Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import { createContext, useCallback, useContext, useMemo, useState, useEffect } from 'react'; import { createContext, useCallback, useContext, useMemo, useState, useEffect } from 'react';
import { useSessionSelector } from '../../context/SessionContext.jsx';
const TabsContext = createContext(null); const TabsContext = createContext(null);
@@ -33,6 +34,28 @@ function classNames(...parts) {
return parts.filter(Boolean).join(' '); return parts.filter(Boolean).join(' ');
} }
function hexToRgb(hex) {
const raw = String(hex || '').trim();
const normalized = raw.startsWith('#') ? raw.slice(1) : raw;
if (!/^[0-9a-fA-F]{3}$|^[0-9a-fA-F]{6}$/.test(normalized)) return null;
const expanded =
normalized.length === 3
? normalized
.split('')
.map((ch) => ch + ch)
.join('')
: normalized;
return {
r: Number.parseInt(expanded.slice(0, 2), 16),
g: Number.parseInt(expanded.slice(2, 4), 16),
b: Number.parseInt(expanded.slice(4, 6), 16),
};
}
function rgba(rgb, alpha) {
return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${alpha})`;
}
export default function Tabs({ children, defaultTab, currentTab, onTabChange, variant = DEFAULT_VARIANT }) { export default function Tabs({ children, defaultTab, currentTab, onTabChange, variant = DEFAULT_VARIANT }) {
const [internalTab, setInternalTab] = useState(defaultTab ?? null); const [internalTab, setInternalTab] = useState(defaultTab ?? null);
const [tabOrder, setTabOrder] = useState([]); const [tabOrder, setTabOrder] = useState([]);
@@ -95,7 +118,32 @@ export default function Tabs({ children, defaultTab, currentTab, onTabChange, va
} }
export function TabList({ children, className = '' }) { export function TabList({ children, className = '' }) {
return <div className={classNames('flex gap-0.5', className)}>{children}</div>; const ownRoverColor = useSessionSelector((state) => {
const roverId = String(state.session?.assignment?.roverId || '').trim();
if (!roverId) return null;
const roster = Array.isArray(state.session?.roster) ? state.session.roster : [];
const rover = roster.find((entry) => String(entry?.id) === roverId);
return rover?.color || null;
});
const accentRgb = hexToRgb(ownRoverColor);
const frameStyle = accentRgb ? { borderColor: rgba(accentRgb, 0.35) } : undefined;
const headerStyle = accentRgb
? {
backgroundImage: `linear-gradient(90deg, rgba(23,23,23,0.96) 0%, rgba(38,38,38,0.94) 58%, ${rgba(accentRgb, 0.18)} 100%)`,
}
: undefined;
return (
<div
className={classNames(
'panel-section overflow-hidden border border-neutral-500/60 bg-neutral-900/95 p-0.5 shadow-[0_1px_0_rgba(255,255,255,0.05)_inset,0_10px_24px_rgba(0,0,0,0.28)]',
className
)}
style={frameStyle}
>
<div className="flex gap-0.5" style={headerStyle}>{children}</div>
</div>
);
} }
export function Tab({ id, children, className = '', disabled = false, highlight = 'none' }) { export function Tab({ id, children, className = '', disabled = false, highlight = 'none' }) {
@@ -5,6 +5,7 @@ import { useMemo } from 'react';
import { useSessionSelector } from '../../context/SessionContext.jsx'; import { useSessionSelector } from '../../context/SessionContext.jsx';
import { useTelemetryFrame } from '../../context/TelemetryContext.jsx'; import { useTelemetryFrame } from '../../context/TelemetryContext.jsx';
import { useDockIr } from '../../hooks/useDockIr.js'; import { useDockIr } from '../../hooks/useDockIr.js';
import CardFrame from '../CardFrame/index.jsx';
function formatMetric(value, fallback = '--') { function formatMetric(value, fallback = '--') {
if (value == null || value === '') return fallback; if (value == null || value === '') return fallback;
@@ -39,7 +40,7 @@ export default function TelemetryPanel() {
}, [activeDriverId, roverId, selfSocketId, users]); }, [activeDriverId, roverId, selfSocketId, users]);
return ( return (
<section className="panel-section space-y-0.5 text-base text-slate-100"> <CardFrame hideHeader clipOverflow={false} bodyClassName="space-y-0.5 text-base text-slate-100">
{/* <div className="text-sm text-slate-400"> {/* <div className="text-sm text-slate-400">
<span>{connected ? 'online' : 'offline'}</span> <span>{connected ? 'online' : 'offline'}</span>
<span> · role {session?.role || 'unknown'}</span> <span> · role {session?.role || 'unknown'}</span>
@@ -48,7 +49,7 @@ export default function TelemetryPanel() {
<span> · driver {driverLabel}</span> <span> · driver {driverLabel}</span>
</div> */} </div> */}
{!roverId ? ( {!roverId ? (
<p className="text-sm text-slate-500">Assign a rover to view sensors.</p> <p className="text-sm text-slate-500">You are not assigned to a rover!!!!!!</p>
) : !frame ? ( ) : !frame ? (
<p className="text-sm text-slate-500">Waiting for sensor frames</p> <p className="text-sm text-slate-500">Waiting for sensor frames</p>
) : ( ) : (
@@ -60,7 +61,7 @@ export default function TelemetryPanel() {
{rawSnippet && ( {rawSnippet && (
<pre className="surface whitespace-pre-wrap break-words text-xs text-lime-300">{rawSnippet}</pre> <pre className="surface whitespace-pre-wrap break-words text-xs text-lime-300">{rawSnippet}</pre>
)} )}
</section> </CardFrame>
); );
} }
@@ -173,7 +174,7 @@ function SensorDetails({ sensors, dockState }) {
function DetailCard({ title, children }) { function DetailCard({ title, children }) {
return ( return (
<div className="surface space-y-0.5 p-1 text-sm"> <div className="surface space-y-0.5 p-1 text-sm">
<div className="text-[0.8rem] uppercase tracking-wide text-slate-400">{title}</div> <div className="text-[0.78rem] font-semibold leading-none text-slate-200">{title}</div>
<div className="space-y-0.5">{children}</div> <div className="space-y-0.5">{children}</div>
</div> </div>
); );
@@ -68,12 +68,6 @@ function TopDownMapContent({ sensors = {}, variant = 'full', size: overrideSize,
className={`${overlay ? 'relative' : 'surface relative p-1'}`} className={`${overlay ? 'relative' : 'surface relative p-1'}`}
style={overlay ? { width: `${size}px`, height: `${size}px` } : { height: '100%', width: '100%', aspectRatio: '1 / 1' }} style={overlay ? { width: `${size}px`, height: `${size}px` } : { height: '100%', width: '100%', aspectRatio: '1 / 1' }}
> >
{!overlay ? (
<>
<div className="absolute left-1 top-1 text-xs text-slate-400">Top-down</div>
<div className="absolute right-1 top-1 text-[0.65rem] text-slate-500">0{maxLight}</div>
</>
) : null}
<svg width="100%" height="100%" viewBox={`0 0 ${size} ${size}`} preserveAspectRatio="xMidYMid meet" className="mx-auto block"> <svg width="100%" height="100%" viewBox={`0 0 ${size} ${size}`} preserveAspectRatio="xMidYMid meet" className="mx-auto block">
<circle cx={centerX} cy={centerY} r={innerCircle} fill="#0f172a" stroke="#334155" strokeWidth="2" /> <circle cx={centerX} cy={centerY} r={innerCircle} fill="#0f172a" stroke="#334155" strokeWidth="2" />
<WheelVisual cx={centerX - wheelLineOffset} cy={centerY} current={wheelCurrentLeft} drop={bumps.wheelDropLeft} overcurrent={wheelOver.leftWheel} label="L" /> <WheelVisual cx={centerX - wheelLineOffset} cy={centerY} current={wheelCurrentLeft} drop={bumps.wheelDropLeft} overcurrent={wheelOver.leftWheel} label="L" />
+3 -2
View File
@@ -6,6 +6,7 @@ import { useSessionSelector } from '../../context/SessionContext.jsx';
import NicknameForm from '../NicknameForm/index.jsx'; import NicknameForm from '../NicknameForm/index.jsx';
import SocialButtonsGrid from '../SocialButtonsGrid/index.jsx'; import SocialButtonsGrid from '../SocialButtonsGrid/index.jsx';
import { roverBadgeStyle, roverNameChromeStyle } from '../../lib/roverColor.js'; import { roverBadgeStyle, roverNameChromeStyle } from '../../lib/roverColor.js';
import CardFrame from '../CardFrame/index.jsx';
export function NicknameEntryPanel({ compact = false }) { export function NicknameEntryPanel({ compact = false }) {
return ( return (
@@ -19,9 +20,9 @@ export function NicknameEntryPanel({ compact = false }) {
export function LinkButtonsPanel() { export function LinkButtonsPanel() {
return ( return (
<section className="panel-section flex h-full min-h-0 flex-col gap-0.5 text-base"> <CardFrame title="Links!" fillHeight bodyClassName="flex flex-1 min-h-0 flex-col gap-0.5 text-base">
<SocialButtonsGrid className="flex-1 min-h-0" /> <SocialButtonsGrid className="flex-1 min-h-0" />
</section> </CardFrame>
); );
} }
@@ -1,178 +0,0 @@
// Hud Overlay
// Purpose: Defines the Hud Overlay module and the local helpers/components used in this file.
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import React from 'react';
import TopDownMap from '../TopDownMap/index.jsx';
import { roverNameChromeStyle } from '../../lib/roverColor.js';
function HudOverlay({
sensors,
label,
roverColor = null,
status,
audioStatus,
levelStatus,
layoutFormat = 'desktop',
variant = 'default',
driverLabel = null,
showTopDown = false,
mobileHud = false,
mapPosition = 'top-center',
turnTimerText = null,
labelScale = 1,
}) {
const isMobile = mobileHud;
const portraitMobile = layoutFormat === 'mobile-portrait';
const statusTextClass = isMobile ? 'text-[0.45rem]' : 'text-[0.65rem]';
const statusPadClass = isMobile ? 'px-0.25 py-0.25' : 'px-1 py-0.5';
const labelPadClass = isMobile ? 'px-0.25 py-0.25' : 'px-0.5 py-0.5';
const labelTextClass = isMobile ? 'text-[0.55rem]' : 'text-[0.8rem]';
const statusPosClass = isMobile ? 'left-0.5 top-0.5' : 'left-1 top-1';
const timerTextClass = isMobile ? 'text-[0.5rem]' : 'text-[0.7rem]';
const timerPadClass = isMobile ? 'px-0.5 py-0.25' : 'px-1 py-0.5';
const telemetryPosClass = isMobile ? 'left-0.5 top-1/2' : 'left-1 top-1/2';
const labelPosClass = isMobile ? 'bottom-0.5' : 'bottom-0.5';
const labelWrapperStyle = {
transform: `translateX(-50%) scale(${labelScale})`,
transformOrigin: 'center bottom',
};
const mapSize = '240px';
const mapScale = portraitMobile ? 0.3 : isMobile ? 0.33 : 0.7;
const mapOpacity = isMobile ? 0.6 : 0.7;
const mapStyle = {
width: mapSize,
height: mapSize,
opacity: mapOpacity,
transform: mapPosition === 'top-center' ? `translateX(-50%) scale(${mapScale})` : `scale(${mapScale})`,
transformOrigin:
mapPosition === 'bottom-left' ? 'bottom left' : mapPosition === 'top-center' ? 'top center' : 'top right',
...(mapPosition === 'bottom-left'
? { left: '0.25rem', bottom: '0.25rem' }
: mapPosition === 'top-center'
? { left: '50%', top: '0.25rem' }
: { right: '0.25rem', top: '0.25rem' }),
};
if (variant === 'none') {
return null;
}
if (variant === 'spectator') {
const telemetryEntries = [
['Voltage', sensors?.voltageMv != null ? `${(sensors.voltageMv / 1000).toFixed(2)} V` : '--'],
['Current', sensors?.currentMa != null ? `${sensors.currentMa} mA` : '--'],
['Charge', sensors?.batteryChargeMah != null ? `${sensors.batteryChargeMah}` : '--'],
['OI', sensors?.oiMode?.label || '--'],
];
const docked = Boolean(sensors?.chargingSources?.homeBase);
const chargingLabel = sensors?.chargingState?.label || '';
const charging = Boolean(chargingLabel && chargingLabel.toLowerCase() !== 'not charging');
const oiLabel = sensors?.oiMode?.label || 'Unknown';
const oiNormalized = oiLabel.toLowerCase();
const oiTone =
oiNormalized === 'full'
? 'bg-emerald-500/80 text-emerald-50'
: oiNormalized === 'safe'
? 'bg-amber-400/80 text-amber-950'
: oiNormalized === 'passive'
? 'bg-slate-700/80 text-slate-100'
: 'bg-slate-700/60 text-slate-200';
const dockTone = docked ? 'bg-emerald-500/80 text-emerald-50' : 'bg-slate-700/70 text-slate-200';
const chargingTone = charging
? 'bg-emerald-500/80 text-emerald-50'
: docked
? 'bg-amber-400/80 text-amber-950'
: 'bg-slate-700/70 text-slate-200';
return (
<>
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className={`absolute ${statusPosClass} font-medium text-slate-100 ${statusTextClass}`}>
<div className="flex flex-col gap-0.5 leading-none">
<span>Status: {status}</span>
{audioStatus ? <span>Audio: {audioStatus}</span> : null}
{levelStatus ? <span className="text-cyan-300">{levelStatus}</span> : null}
</div>
</div>
<div
className={`absolute ${telemetryPosClass} flex -translate-y-1/2 flex-col gap-0.5 bg-black/70 text-slate-100 ${statusTextClass} ${statusPadClass}`}
>
<div className="space-y-0.5 leading-tight">
<div className="flex flex-col gap-0.5 text-[0.75rem] font-semibold uppercase tracking-wide">
<span className={`rounded px-1.5 py-0.5 ${dockTone}`}>{docked ? 'Docked' : 'Undocked'}</span>
<span className={`rounded px-1.5 py-0.5 ${chargingTone}`}>
{charging ? 'Charging' : docked ? 'Not charging' : 'Not charging'}
</span>
<span className={`rounded px-1.5 py-0.5 ${oiTone}`}>OI: {oiLabel}</span>
</div>
{telemetryEntries.map(([labelText, value]) => (
<span key={labelText} className="flex items-center justify-between gap-0.5">
<span className="text-slate-400">{labelText}</span>
<span className="font-semibold text-white">{value}</span>
</span>
))}
</div>
</div>
<div className={`absolute ${labelPosClass} left-1/2`} style={labelWrapperStyle}>
<div
className={`flex items-center gap-0.5 bg-black/80 text-slate-100 ${labelPadClass} ${labelTextClass}`}
>
<span
className="font-semibold text-white rounded px-1 py-[1px] border border-transparent"
style={roverNameChromeStyle(roverColor, 0.18)}
>
{label || 'Unnamed Rover'}
</span>
{driverLabel ? <span className="text-slate-300"> {driverLabel}</span> : null}
</div>
</div>
</div>
{showTopDown ? (
<div className="pointer-events-none absolute rounded" style={{ ...mapStyle }}>
<TopDownMap sensors={sensors} size={240} overlay />
</div>
) : null}
</>
);
}
return (
<div className="pointer-events-none absolute inset-0 flex items-center justify-center">
<div className={`absolute ${statusPosClass} font-medium text-slate-100 ${statusTextClass}`}>
<div className="flex flex-col gap-0.5 leading-none">
<span>Status: {status}</span>
{audioStatus ? <span>Audio: {audioStatus}</span> : null}
{levelStatus ? <span className="text-cyan-300">{levelStatus}</span> : null}
</div>
</div>
{turnTimerText ? (
<div
className={`absolute left-1/2 top-0.5 -translate-x-1/2 rounded bg-black/70 text-slate-100 ${timerPadClass} ${timerTextClass}`}
>
{turnTimerText}
</div>
) : null}
<div className={`absolute ${labelPosClass} left-1/2`} style={labelWrapperStyle}>
<div className={`flex gap-0.5 bg-black/80 text-slate-100 ${labelPadClass} ${labelTextClass}`}>
<span>
Rover:{' '}
<span
className="rounded px-1 py-[1px] border border-transparent"
style={roverNameChromeStyle(roverColor, 0.18)}
>
"{label || 'Unnamed Rover'}"
</span>
</span>
</div>
</div>
{showTopDown && variant !== 'spectator' ? (
<div className="pointer-events-none absolute rounded" style={{ ...mapStyle }}>
<TopDownMap sensors={sensors} size={240} overlay />
</div>
) : null}
</div>
);
}
export default React.memo(HudOverlay);
@@ -1,28 +0,0 @@
// Low Battery Overlay
// Purpose: Defines the Low Battery Overlay module and the local helpers/components used in this file.
// Scope: Keeps behavior unchanged while isolating this concern into a clear, single-responsibility unit.
import React from 'react';
function LowBatteryOverlay({ battery, compact = false }) {
if (!battery?.available) return null;
if (!battery.warnActive && !battery.urgentActive) return null;
const message = battery.urgentActive
? 'BATTERY VERY LOW, DOCK THE ROVER AND CHARGE IMMEDIATELY!!'
: 'Battery low! please dock and charge the rover soon.';
const containerClass = compact ? 'p-2 top-6' : 'p-4 top-10';
const textClass = compact ? 'text-sm' : 'text-2xl';
return (
<div
className={`pointer-events-none absolute flex items-center justify-center bg-amber-900/60 left-1/2 -translate-x-1/2 ${containerClass}`}
>
<div className={`text-center font-semibold text-white animate-pulse ${textClass}`}>
<div>{message}</div>
</div>
</div>
);
}
export default React.memo(LowBatteryOverlay);

Some files were not shown because too many files have changed in this diff Show More