BlueGit

ict rusty-teams

feat(app): single instance, a second start brings the running window to front

- Windows: named pipe per user; the second process grants foreground rights and exits
- Linux: Unix socket, stale sockets are reclaimed
- Updater relaunch waits up to 15 s for the old process, then starts anyway
- Demo and --database profiles stay independent
- ROADMAP: single instance Done, parity 68 %

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-09 · 7 weeks ago

Hash
fd0a29ba36df673fc0570713549205fcd9dab009
Parent
6bf26611
7 files changed +236 −3
README.md +1 −0
@@ -23,6 +23,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
23 23 - Activity bell: feed of new messages, @mentions and reactions to your messages, kept for 14 days
24 24 - Dark theme, opens instantly from the local cache
25 25 - Self-update from an update folder
26 - Single instance: a second start brings the running window to the front
26 27
27 28 ## Status
28 29
@@ -23,6 +23,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
23- Activity bell: feed of new messages, @mentions and reactions to your messages, kept for 14 days
23- Activity bell: feed of new messages, @mentions and reactions to your messages, kept for 14 days
24- Dark theme, opens instantly from the local cache
24- Dark theme, opens instantly from the local cache
25- Self-update from an update folder
25- Self-update from an update folder
26- Single instance: a second start brings the running window to the front
26
27
27## Status
28## Status
28
29
ROADMAP.md +3 −3
@@ -2,13 +2,13 @@
2 2
3 3 Feature parity with the Microsoft Teams desktop client.
4 4
5 **Parity: 67 %** (55 done, 4 partial, 26 missing of 85). Partial counts half.
5 **Parity: 68 %** (56 done, 4 partial, 25 missing of 85). Partial counts half.
6 6
7 7 ## By area
8 8
9 9 | Area | Parity | Done | Partial | Missing |
10 10 |---|---|---|---|---|
11 | [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
11 | [Sign-in and app](#sign-in-and-app) | 92 % | 5 | 1 | 0 |
12 12 | [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13 13 | [Reading](#reading) | 87 % | 16 | 1 | 2 |
14 14 | [Writing](#writing) | 75 % | 10 | 1 | 3 |
@@ -39,7 +39,7 @@ Feature parity with the Microsoft Teams desktop client.
39 39 | Self-update | Done | |
40 40 | Tray icon, close to tray | Done | |
41 41 | Sign in on Linux without starting Chrome by hand | Partial | Works with a Chrome on a debug port |
42 | Single instance, second start brings the window to front | Missing | |
42 | Single instance, second start brings the window to front | Done | |
43 43
44 44 ## Chat list
45 45
@@ -2,13 +2,13 @@
2
2
3Feature parity with the Microsoft Teams desktop client.
3Feature parity with the Microsoft Teams desktop client.
4
4
5**Parity: 67 %** (55 done, 4 partial, 26 missing of 85). Partial counts half.
5**Parity: 68 %** (56 done, 4 partial, 25 missing of 85). Partial counts half.
6
6
7## By area
7## By area
8
8
9| Area | Parity | Done | Partial | Missing |
9| Area | Parity | Done | Partial | Missing |
10|---|---|---|---|---|
10|---|---|---|---|---|
11| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
11| [Sign-in and app](#sign-in-and-app) | 92 % | 5 | 1 | 0 |
12| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
12| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13| [Reading](#reading) | 87 % | 16 | 1 | 2 |
13| [Reading](#reading) | 87 % | 16 | 1 | 2 |
14| [Writing](#writing) | 75 % | 10 | 1 | 3 |
14| [Writing](#writing) | 75 % | 10 | 1 | 3 |
@@ -39,7 +39,7 @@ Feature parity with the Microsoft Teams desktop client.
39| Self-update | Done | |
39| Self-update | Done | |
40| Tray icon, close to tray | Done | |
40| Tray icon, close to tray | Done | |
41| Sign in on Linux without starting Chrome by hand | Partial | Works with a Chrome on a debug port |
41| Sign in on Linux without starting Chrome by hand | Partial | Works with a Chrome on a debug port |
42| Single instance, second start brings the window to front | Missing | |
42| Single instance, second start brings the window to front | Done | |
43
43
44## Chat list
44## Chat list
45
45
crates/app/Cargo.toml +3 −0
@@ -43,7 +43,10 @@ windows = { version = "0.62", features = [
43 43 "Win32_Foundation",
44 44 "Win32_Graphics_Dwm",
45 45 "Win32_Graphics_Gdi",
46 "Win32_Security",
47 "Win32_Storage_FileSystem",
46 48 "Win32_System_Com",
49 "Win32_System_Pipes",
47 50 "Win32_UI_HiDpi",
48 51 "Win32_UI_Shell",
49 52 "Win32_UI_WindowsAndMessaging",
@@ -43,7 +43,10 @@ windows = { version = "0.62", features = [
43 "Win32_Foundation",
43 "Win32_Foundation",
44 "Win32_Graphics_Dwm",
44 "Win32_Graphics_Dwm",
45 "Win32_Graphics_Gdi",
45 "Win32_Graphics_Gdi",
46 "Win32_Security",
47 "Win32_Storage_FileSystem",
46 "Win32_System_Com",
48 "Win32_System_Com",
49 "Win32_System_Pipes",
47 "Win32_UI_HiDpi",
50 "Win32_UI_HiDpi",
48 "Win32_UI_Shell",
51 "Win32_UI_Shell",
49 "Win32_UI_WindowsAndMessaging",
52 "Win32_UI_WindowsAndMessaging",
crates/app/src/main.rs +10 −0
@@ -28,6 +28,7 @@ mod read_state;
28 28 mod render;
29 29 mod rows;
30 30 mod runtime;
31 mod single_instance;
31 32 mod sidebar_model;
32 33 mod task_dialog;
33 34 mod theme;
@@ -53,6 +54,7 @@ const WINDOW_WIDTH: f32 = 1240.;
53 54 const WINDOW_HEIGHT: f32 = 820.;
54 55 const WINDOW_MIN_WIDTH: f32 = 640.;
55 56 const WINDOW_MIN_HEIGHT: f32 = 480.;
57 const SINGLE_INSTANCE_NAME: &str = "rusty-teams";
56 58 const DATABASE_FILE: &str = "cache.sqlite3";
57 59 #[cfg(windows)]
58 60 const WEBVIEW_FOLDER: &str = "WebView2";
@@ -141,6 +143,14 @@ fn transport(endpoint: Option<&str>, database: Option<&std::path::Path>) -> Arc<
141 143 fn main() {
142 144 crash_log::install(data_path(crash_log::CRASH_LOG_FILE));
143 145 let arguments = parse_arguments();
146 if !arguments.demo && arguments.database.is_none() {
147 let relaunched = std::env::var_os(updater::RELAUNCH_ENV).is_some();
148 if single_instance::claim(SINGLE_INSTANCE_NAME, relaunched)
149 == single_instance::Claim::Forwarded
150 {
151 return;
152 }
153 }
144 154 #[cfg(windows)]
145 155 updater::clean_up_old_binary();
146 156 let mode = Mode {
@@ -28,6 +28,7 @@ mod read_state;
28mod render;
28mod render;
29mod rows;
29mod rows;
30mod runtime;
30mod runtime;
31mod single_instance;
31mod sidebar_model;
32mod sidebar_model;
32mod task_dialog;
33mod task_dialog;
33mod theme;
34mod theme;
@@ -53,6 +54,7 @@ const WINDOW_WIDTH: f32 = 1240.;
53const WINDOW_HEIGHT: f32 = 820.;
54const WINDOW_HEIGHT: f32 = 820.;
54const WINDOW_MIN_WIDTH: f32 = 640.;
55const WINDOW_MIN_WIDTH: f32 = 640.;
55const WINDOW_MIN_HEIGHT: f32 = 480.;
56const WINDOW_MIN_HEIGHT: f32 = 480.;
57const SINGLE_INSTANCE_NAME: &str = "rusty-teams";
56const DATABASE_FILE: &str = "cache.sqlite3";
58const DATABASE_FILE: &str = "cache.sqlite3";
57#[cfg(windows)]
59#[cfg(windows)]
58const WEBVIEW_FOLDER: &str = "WebView2";
60const WEBVIEW_FOLDER: &str = "WebView2";
@@ -141,6 +143,14 @@ fn transport(endpoint: Option<&str>, database: Option<&std::path::Path>) -> Arc<
141fn main() {
143fn main() {
142 crash_log::install(data_path(crash_log::CRASH_LOG_FILE));
144 crash_log::install(data_path(crash_log::CRASH_LOG_FILE));
143 let arguments = parse_arguments();
145 let arguments = parse_arguments();
146 if !arguments.demo && arguments.database.is_none() {
147 let relaunched = std::env::var_os(updater::RELAUNCH_ENV).is_some();
148 if single_instance::claim(SINGLE_INSTANCE_NAME, relaunched)
149 == single_instance::Claim::Forwarded
150 {
151 return;
152 }
153 }
144 #[cfg(windows)]
154 #[cfg(windows)]
145 updater::clean_up_old_binary();
155 updater::clean_up_old_binary();
146 let mode = Mode {
156 let mode = Mode {
crates/app/src/notify/center.rs +4 −0
@@ -23,6 +23,7 @@ use super::toast::{PillView, ToastView};
23 23 use crate::app_state::{AppEvent, AppState, Selection};
24 24 use crate::data::{self, Directory, PresenceKind};
25 25 use crate::runtime;
26 use crate::single_instance;
26 27
27 28 const TICK: Duration = Duration::from_millis(33);
28 29 const SLIDE_DURATION: Duration = Duration::from_millis(180);
@@ -471,6 +472,9 @@ impl NotificationCenter {
471 472 cx.notify();
472 473 }
473 474 self.poll_tray(cx);
475 if single_instance::take_activation() {
476 self.raise_main_window(cx);
477 }
474 478 }
475 479
476 480 fn poll_tray(&mut self, cx: &mut Context<Self>) {
@@ -23,6 +23,7 @@ use super::toast::{PillView, ToastView};
23use crate::app_state::{AppEvent, AppState, Selection};
23use crate::app_state::{AppEvent, AppState, Selection};
24use crate::data::{self, Directory, PresenceKind};
24use crate::data::{self, Directory, PresenceKind};
25use crate::runtime;
25use crate::runtime;
26use crate::single_instance;
26
27
27const TICK: Duration = Duration::from_millis(33);
28const TICK: Duration = Duration::from_millis(33);
28const SLIDE_DURATION: Duration = Duration::from_millis(180);
29const SLIDE_DURATION: Duration = Duration::from_millis(180);
@@ -471,6 +472,9 @@ impl NotificationCenter {
471 cx.notify();
472 cx.notify();
472 }
473 }
473 self.poll_tray(cx);
474 self.poll_tray(cx);
475 if single_instance::take_activation() {
476 self.raise_main_window(cx);
477 }
474 }
478 }
475
479
476 fn poll_tray(&mut self, cx: &mut Context<Self>) {
480 fn poll_tray(&mut self, cx: &mut Context<Self>) {
crates/app/src/single_instance.rs added +213 −0
@@ -0,0 +1,213 @@
1 use std::sync::atomic::{AtomicBool, Ordering};
2 use std::time::{Duration, Instant};
3
4 static ACTIVATION: AtomicBool = AtomicBool::new(false);
5
6 const RETRY_INTERVAL: Duration = Duration::from_millis(200);
7 const RETRY_TIMEOUT: Duration = Duration::from_secs(15);
8
9 #[derive(Debug, PartialEq, Eq)]
10 pub enum Claim {
11 Primary,
12 Forwarded,
13 }
14
15 pub fn take_activation() -> bool {
16 ACTIVATION.swap(false, Ordering::AcqRel)
17 }
18
19 pub fn claim(name: &str, wait_for_previous: bool) -> Claim {
20 let started = Instant::now();
21 loop {
22 if platform::try_become_primary(name) {
23 return Claim::Primary;
24 }
25 if !wait_for_previous {
26 platform::notify_primary(name);
27 return Claim::Forwarded;
28 }
29 if started.elapsed() >= RETRY_TIMEOUT {
30 return Claim::Primary;
31 }
32 std::thread::sleep(RETRY_INTERVAL);
33 }
34 }
35
36 fn user_name() -> String {
37 std::env::var("USERNAME")
38 .or_else(|_| std::env::var("USER"))
39 .unwrap_or_default()
40 }
41
42 #[cfg(windows)]
43 mod platform {
44 use std::fs::OpenOptions;
45 use std::sync::atomic::Ordering;
46 use std::time::Duration;
47
48 use windows::Win32::Foundation::{
49 ERROR_ACCESS_DENIED, ERROR_NO_DATA, ERROR_PIPE_BUSY, ERROR_PIPE_CONNECTED, GetLastError,
50 INVALID_HANDLE_VALUE,
51 };
52 use windows::Win32::Storage::FileSystem::{FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_ACCESS_INBOUND};
53 use windows::Win32::System::Pipes::{
54 ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, PIPE_REJECT_REMOTE_CLIENTS,
55 PIPE_TYPE_BYTE, PIPE_WAIT,
56 };
57 use windows::Win32::UI::WindowsAndMessaging::{ASFW_ANY, AllowSetForegroundWindow};
58 use windows::core::PCWSTR;
59
60 use super::{ACTIVATION, user_name};
61
62 const CONNECT_ATTEMPTS: u32 = 20;
63 const CONNECT_INTERVAL: Duration = Duration::from_millis(100);
64
65 fn pipe_path(name: &str) -> String {
66 format!(r"\\.\pipe\{name}-{}", user_name())
67 }
68
69 pub fn try_become_primary(name: &str) -> bool {
70 let wide_path: Vec<u16> = pipe_path(name)
71 .encode_utf16()
72 .chain(std::iter::once(0))
73 .collect();
74 let handle = unsafe {
75 CreateNamedPipeW(
76 PCWSTR(wide_path.as_ptr()),
77 PIPE_ACCESS_INBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE,
78 PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
79 1,
80 0,
81 0,
82 0,
83 None,
84 )
85 };
86 if handle == INVALID_HANDLE_VALUE {
87 let error = unsafe { GetLastError() };
88 return error != ERROR_ACCESS_DENIED && error != ERROR_PIPE_BUSY;
89 }
90 let raw_handle = handle.0 as usize;
91 std::thread::spawn(move || {
92 let handle = windows::Win32::Foundation::HANDLE(raw_handle as *mut _);
93 loop {
94 let connected = unsafe { ConnectNamedPipe(handle, None) }.is_ok()
95 || matches!(
96 unsafe { GetLastError() },
97 ERROR_PIPE_CONNECTED | ERROR_NO_DATA
98 );
99 if connected {
100 ACTIVATION.store(true, Ordering::Release);
101 } else {
102 std::thread::sleep(CONNECT_INTERVAL);
103 }
104 let _ = unsafe { DisconnectNamedPipe(handle) };
105 }
106 });
107 true
108 }
109
110 pub fn notify_primary(name: &str) {
111 let path = pipe_path(name);
112 let _ = unsafe { AllowSetForegroundWindow(ASFW_ANY) };
113 for _ in 0..CONNECT_ATTEMPTS {
114 if OpenOptions::new().write(true).open(&path).is_ok() {
115 return;
116 }
117 std::thread::sleep(CONNECT_INTERVAL);
118 }
119 }
120 }
121
122 #[cfg(unix)]
123 mod platform {
124 use std::io::ErrorKind;
125 use std::os::unix::net::{UnixListener, UnixStream};
126 use std::path::PathBuf;
127 use std::sync::atomic::Ordering;
128
129 use super::{ACTIVATION, user_name};
130
131 pub(super) fn socket_path(name: &str) -> PathBuf {
132 let directory = std::env::var_os("XDG_RUNTIME_DIR")
133 .map(PathBuf::from)
134 .unwrap_or_else(std::env::temp_dir);
135 directory.join(format!("{name}-{}.sock", user_name()))
136 }
137
138 enum Bound {
139 Listening(UnixListener),
140 Taken,
141 Unavailable,
142 }
143
144 fn bind(path: &PathBuf) -> Bound {
145 match UnixListener::bind(path) {
146 Ok(listener) => Bound::Listening(listener),
147 Err(error) if error.kind() == ErrorKind::AddrInUse => {
148 if UnixStream::connect(path).is_ok() {
149 return Bound::Taken;
150 }
151 let _ = std::fs::remove_file(path);
152 UnixListener::bind(path).map_or(Bound::Unavailable, Bound::Listening)
153 }
154 Err(_) => Bound::Unavailable,
155 }
156 }
157
158 pub fn try_become_primary(name: &str) -> bool {
159 let listener = match bind(&socket_path(name)) {
160 Bound::Listening(listener) => listener,
161 Bound::Taken => return false,
162 Bound::Unavailable => return true,
163 };
164 std::thread::spawn(move || {
165 for connection in listener.incoming() {
166 if connection.is_ok() {
167 ACTIVATION.store(true, Ordering::Release);
168 }
169 }
170 });
171 true
172 }
173
174 pub fn notify_primary(name: &str) {
175 let _ = UnixStream::connect(socket_path(name));
176 }
177 }
178
179 #[cfg(test)]
180 mod tests {
181 use super::*;
182
183 #[test]
184 fn second_claim_forwards_and_stale_socket_is_reclaimed() {
185 let name = format!("rusty-teams-test-{}", std::process::id());
186 assert_eq!(claim(&name, false), Claim::Primary);
187 assert_eq!(claim(&name, false), Claim::Forwarded);
188 let started = Instant::now();
189 while !take_activation() {
190 assert!(started.elapsed() < Duration::from_secs(1));
191 std::thread::sleep(Duration::from_millis(10));
192 }
193 assert!(!take_activation());
194
195 let stale_name = format!("{name}-stale");
196 #[cfg(unix)]
197 {
198 let path = platform::socket_path(&stale_name);
199 drop(std::os::unix::net::UnixListener::bind(&path).unwrap());
200 assert!(path.exists());
201 }
202 assert_eq!(claim(&stale_name, false), Claim::Primary);
203 assert_eq!(
204 claim("missing-directory/rusty-teams", false),
205 Claim::Primary
206 );
207
208 #[cfg(unix)]
209 for leftover in [&name, &stale_name] {
210 let _ = std::fs::remove_file(platform::socket_path(leftover));
211 }
212 }
213 }
@@ -0,0 +1,213 @@
1use std::sync::atomic::{AtomicBool, Ordering};
2use std::time::{Duration, Instant};
3
4static ACTIVATION: AtomicBool = AtomicBool::new(false);
5
6const RETRY_INTERVAL: Duration = Duration::from_millis(200);
7const RETRY_TIMEOUT: Duration = Duration::from_secs(15);
8
9#[derive(Debug, PartialEq, Eq)]
10pub enum Claim {
11 Primary,
12 Forwarded,
13}
14
15pub fn take_activation() -> bool {
16 ACTIVATION.swap(false, Ordering::AcqRel)
17}
18
19pub fn claim(name: &str, wait_for_previous: bool) -> Claim {
20 let started = Instant::now();
21 loop {
22 if platform::try_become_primary(name) {
23 return Claim::Primary;
24 }
25 if !wait_for_previous {
26 platform::notify_primary(name);
27 return Claim::Forwarded;
28 }
29 if started.elapsed() >= RETRY_TIMEOUT {
30 return Claim::Primary;
31 }
32 std::thread::sleep(RETRY_INTERVAL);
33 }
34}
35
36fn user_name() -> String {
37 std::env::var("USERNAME")
38 .or_else(|_| std::env::var("USER"))
39 .unwrap_or_default()
40}
41
42#[cfg(windows)]
43mod platform {
44 use std::fs::OpenOptions;
45 use std::sync::atomic::Ordering;
46 use std::time::Duration;
47
48 use windows::Win32::Foundation::{
49 ERROR_ACCESS_DENIED, ERROR_NO_DATA, ERROR_PIPE_BUSY, ERROR_PIPE_CONNECTED, GetLastError,
50 INVALID_HANDLE_VALUE,
51 };
52 use windows::Win32::Storage::FileSystem::{FILE_FLAG_FIRST_PIPE_INSTANCE, PIPE_ACCESS_INBOUND};
53 use windows::Win32::System::Pipes::{
54 ConnectNamedPipe, CreateNamedPipeW, DisconnectNamedPipe, PIPE_REJECT_REMOTE_CLIENTS,
55 PIPE_TYPE_BYTE, PIPE_WAIT,
56 };
57 use windows::Win32::UI::WindowsAndMessaging::{ASFW_ANY, AllowSetForegroundWindow};
58 use windows::core::PCWSTR;
59
60 use super::{ACTIVATION, user_name};
61
62 const CONNECT_ATTEMPTS: u32 = 20;
63 const CONNECT_INTERVAL: Duration = Duration::from_millis(100);
64
65 fn pipe_path(name: &str) -> String {
66 format!(r"\\.\pipe\{name}-{}", user_name())
67 }
68
69 pub fn try_become_primary(name: &str) -> bool {
70 let wide_path: Vec<u16> = pipe_path(name)
71 .encode_utf16()
72 .chain(std::iter::once(0))
73 .collect();
74 let handle = unsafe {
75 CreateNamedPipeW(
76 PCWSTR(wide_path.as_ptr()),
77 PIPE_ACCESS_INBOUND | FILE_FLAG_FIRST_PIPE_INSTANCE,
78 PIPE_TYPE_BYTE | PIPE_WAIT | PIPE_REJECT_REMOTE_CLIENTS,
79 1,
80 0,
81 0,
82 0,
83 None,
84 )
85 };
86 if handle == INVALID_HANDLE_VALUE {
87 let error = unsafe { GetLastError() };
88 return error != ERROR_ACCESS_DENIED && error != ERROR_PIPE_BUSY;
89 }
90 let raw_handle = handle.0 as usize;
91 std::thread::spawn(move || {
92 let handle = windows::Win32::Foundation::HANDLE(raw_handle as *mut _);
93 loop {
94 let connected = unsafe { ConnectNamedPipe(handle, None) }.is_ok()
95 || matches!(
96 unsafe { GetLastError() },
97 ERROR_PIPE_CONNECTED | ERROR_NO_DATA
98 );
99 if connected {
100 ACTIVATION.store(true, Ordering::Release);
101 } else {
102 std::thread::sleep(CONNECT_INTERVAL);
103 }
104 let _ = unsafe { DisconnectNamedPipe(handle) };
105 }
106 });
107 true
108 }
109
110 pub fn notify_primary(name: &str) {
111 let path = pipe_path(name);
112 let _ = unsafe { AllowSetForegroundWindow(ASFW_ANY) };
113 for _ in 0..CONNECT_ATTEMPTS {
114 if OpenOptions::new().write(true).open(&path).is_ok() {
115 return;
116 }
117 std::thread::sleep(CONNECT_INTERVAL);
118 }
119 }
120}
121
122#[cfg(unix)]
123mod platform {
124 use std::io::ErrorKind;
125 use std::os::unix::net::{UnixListener, UnixStream};
126 use std::path::PathBuf;
127 use std::sync::atomic::Ordering;
128
129 use super::{ACTIVATION, user_name};
130
131 pub(super) fn socket_path(name: &str) -> PathBuf {
132 let directory = std::env::var_os("XDG_RUNTIME_DIR")
133 .map(PathBuf::from)
134 .unwrap_or_else(std::env::temp_dir);
135 directory.join(format!("{name}-{}.sock", user_name()))
136 }
137
138 enum Bound {
139 Listening(UnixListener),
140 Taken,
141 Unavailable,
142 }
143
144 fn bind(path: &PathBuf) -> Bound {
145 match UnixListener::bind(path) {
146 Ok(listener) => Bound::Listening(listener),
147 Err(error) if error.kind() == ErrorKind::AddrInUse => {
148 if UnixStream::connect(path).is_ok() {
149 return Bound::Taken;
150 }
151 let _ = std::fs::remove_file(path);
152 UnixListener::bind(path).map_or(Bound::Unavailable, Bound::Listening)
153 }
154 Err(_) => Bound::Unavailable,
155 }
156 }
157
158 pub fn try_become_primary(name: &str) -> bool {
159 let listener = match bind(&socket_path(name)) {
160 Bound::Listening(listener) => listener,
161 Bound::Taken => return false,
162 Bound::Unavailable => return true,
163 };
164 std::thread::spawn(move || {
165 for connection in listener.incoming() {
166 if connection.is_ok() {
167 ACTIVATION.store(true, Ordering::Release);
168 }
169 }
170 });
171 true
172 }
173
174 pub fn notify_primary(name: &str) {
175 let _ = UnixStream::connect(socket_path(name));
176 }
177}
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182
183 #[test]
184 fn second_claim_forwards_and_stale_socket_is_reclaimed() {
185 let name = format!("rusty-teams-test-{}", std::process::id());
186 assert_eq!(claim(&name, false), Claim::Primary);
187 assert_eq!(claim(&name, false), Claim::Forwarded);
188 let started = Instant::now();
189 while !take_activation() {
190 assert!(started.elapsed() < Duration::from_secs(1));
191 std::thread::sleep(Duration::from_millis(10));
192 }
193 assert!(!take_activation());
194
195 let stale_name = format!("{name}-stale");
196 #[cfg(unix)]
197 {
198 let path = platform::socket_path(&stale_name);
199 drop(std::os::unix::net::UnixListener::bind(&path).unwrap());
200 assert!(path.exists());
201 }
202 assert_eq!(claim(&stale_name, false), Claim::Primary);
203 assert_eq!(
204 claim("missing-directory/rusty-teams", false),
205 Claim::Primary
206 );
207
208 #[cfg(unix)]
209 for leftover in [&name, &stale_name] {
210 let _ = std::fs::remove_file(platform::socket_path(leftover));
211 }
212 }
213}
crates/app/src/updater.rs +2 −0
@@ -12,6 +12,7 @@ const UPDATE_DIRECTORY: &str = "update";
12 12 const EXE_NAME: &str = "teams.exe";
13 13 const OLD_EXE_NAME: &str = "teams.old.exe";
14 14 const VERSION_FILE_NAME: &str = "version.txt";
15 pub const RELAUNCH_ENV: &str = "RUSTY_TEAMS_RELAUNCH";
15 16 const CLEANUP_ATTEMPTS: u32 = 30;
16 17 const CLEANUP_INTERVAL: Duration = Duration::from_secs(1);
17 18
@@ -165,6 +166,7 @@ pub fn install_and_relaunch(paths: &UpdatePaths) -> Result<(), String> {
165 166 let completed = apply_plan(&files, &swap_plan(paths))?;
166 167 match Command::new(&paths.exe)
167 168 .args(std::env::args_os().skip(1))
169 .env(RELAUNCH_ENV, "1")
168 170 .spawn()
169 171 {
170 172 Ok(_) => Ok(()),
@@ -12,6 +12,7 @@ const UPDATE_DIRECTORY: &str = "update";
12const EXE_NAME: &str = "teams.exe";
12const EXE_NAME: &str = "teams.exe";
13const OLD_EXE_NAME: &str = "teams.old.exe";
13const OLD_EXE_NAME: &str = "teams.old.exe";
14const VERSION_FILE_NAME: &str = "version.txt";
14const VERSION_FILE_NAME: &str = "version.txt";
15pub const RELAUNCH_ENV: &str = "RUSTY_TEAMS_RELAUNCH";
15const CLEANUP_ATTEMPTS: u32 = 30;
16const CLEANUP_ATTEMPTS: u32 = 30;
16const CLEANUP_INTERVAL: Duration = Duration::from_secs(1);
17const CLEANUP_INTERVAL: Duration = Duration::from_secs(1);
17
18
@@ -165,6 +166,7 @@ pub fn install_and_relaunch(paths: &UpdatePaths) -> Result<(), String> {
165 let completed = apply_plan(&files, &swap_plan(paths))?;
166 let completed = apply_plan(&files, &swap_plan(paths))?;
166 match Command::new(&paths.exe)
167 match Command::new(&paths.exe)
167 .args(std::env::args_os().skip(1))
168 .args(std::env::args_os().skip(1))
169 .env(RELAUNCH_ENV, "1")
168 .spawn()
170 .spawn()
169 {
171 {
170 Ok(_) => Ok(()),
172 Ok(_) => Ok(()),