Skip to content

Commit 7cc0037

Browse files
committed
fix(pairing): retain uncertain delivery and terminal cancellation
Signed-off-by: klopez4212 <[email protected]>
1 parent 72ec901 commit 7cc0037

10 files changed

Lines changed: 182 additions & 77 deletions

File tree

‎docs/images/pairing/code.png‎

10.1 KB
Loading

‎docs/images/pairing/qr.png‎

15 KB
Loading

‎docs/pairing.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -30,10 +30,11 @@ new plugin security sandbox. The frontend CSP is unchanged.
3030
4. Older phones retain explicit **Codes match** confirmation. Desktop never uses
3131
that action to bypass a code-entry phone's proof.
3232
5. **Phone paired** requires the phone's successful import acknowledgement.
33-
If a sent transfer times out awaiting acknowledgement, **Check your phone**
33+
If a sent transfer times out or loses its connection awaiting acknowledgement, **Check your phone**
3434
preserves the uncertain outcome and requires a deliberate new attempt.
3535
Closing or reloading the window, leaving the Settings section, switching accounts/communities, disabling the
36-
plugin disposes the attempt. Retries use a fresh native session.
36+
plugin disposes the attempt. Native cancellation remains terminal until an explicit retry
37+
or reopening the pairing section. Retries use a fresh native session.
3738

3839
Pairing uses the current native app identity through a purpose-bound
3940
`IdentityHost.with_key` operation. The public viewer is checked before producing

‎src-tauri/src/pairing/mod.rs‎

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -70,15 +70,18 @@ impl Pairing {
7070
}
7171
}
7272
fn expire(&self, id: &str) {
73+
self.fail(id, Status::Expired, true);
74+
}
75+
fn fail(&self, id: &str, status: Status, ambiguous: bool) {
7376
if let Ok(mut active) = self.0.lock() {
7477
if let Some(active) = active
7578
.as_mut()
7679
.filter(|a| a.id == id && !a.cancel.is_cancelled())
7780
{
78-
active.status = if active.payload_sent {
81+
active.status = if active.payload_sent && ambiguous {
7982
Status::Uncertain
8083
} else {
81-
Status::Expired
84+
status
8285
};
8386
}
8487
}
@@ -189,16 +192,36 @@ pub fn pairing_start(
189192
};
190193
match result {
191194
Ok(Ok(())) => pairing.update(&id, Status::Complete),
192-
Ok(Err(message)) => pairing.update(&id, Status::Error { message }),
195+
Ok(Err(failure)) => {
196+
let ambiguous = matches!(failure, Failure::Transport(_));
197+
let (Failure::Transport(message) | Failure::Rejected(message)) = failure;
198+
pairing.fail(&id, Status::Error { message }, ambiguous);
199+
}
193200
Err(_) => pairing.expire(&id),
194201
}
195202
});
196203
Ok(())
197204
}
198205

206+
#[derive(Debug)]
207+
enum Failure {
208+
Transport(String),
209+
Rejected(String),
210+
}
211+
impl From<String> for Failure {
212+
fn from(message: String) -> Self {
213+
Self::Transport(message)
214+
}
215+
}
216+
impl From<&str> for Failure {
217+
fn from(message: &str) -> Self {
218+
Self::Transport(message.into())
219+
}
220+
}
221+
199222
async fn guard(
200-
future: impl std::future::Future<Output = Result<(), String>>,
201-
) -> Result<(), String> {
223+
future: impl std::future::Future<Output = Result<(), Failure>>,
224+
) -> Result<(), Failure> {
202225
std::panic::AssertUnwindSafe(future)
203226
.catch_unwind()
204227
.await
@@ -214,7 +237,7 @@ async fn run(
214237
viewer: String,
215238
origin: url::Url,
216239
mut confirm: mpsc::Receiver<()>,
217-
) -> Result<(), String> {
240+
) -> Result<(), Failure> {
218241
let origin_string = origin.as_str().trim_end_matches('/').to_string();
219242
let payload = identity::prepare(host, viewer, origin_string).await?;
220243
let relay_url = relay::discover(&origin).await?;
@@ -242,14 +265,14 @@ async fn run(
242265
let mut pending = std::collections::VecDeque::from(pending);
243266
loop {
244267
let output = if let Some(event) = pending.pop_front() {
245-
exchange.receive(&event)?
268+
exchange.receive(&event).map_err(Failure::Rejected)?
246269
} else {
247270
tokio::select! {
248-
Some(())=confirm.recv()=>exchange.confirm()?,
271+
Some(())=confirm.recv()=>exchange.confirm().map_err(Failure::Rejected)?,
249272
message=relay::next(&mut socket)=>{
250273
let message=message?;
251274
if auth.handle(&mut socket, &exchange.session, &relay_url, &message).await? {continue;}
252-
if let Some(event)=relay::event(&message) {exchange.receive(&event)?} else {continue;}
275+
if let Some(event)=relay::event(&message) {exchange.receive(&event).map_err(Failure::Rejected)?} else {continue;}
253276
}
254277
}
255278
};
@@ -268,7 +291,7 @@ async fn run(
268291
return Ok(());
269292
}
270293
if let Status::Error { message } = status {
271-
return Err(message);
294+
return Err(Failure::Rejected(message));
272295
}
273296
pairing.update(id, status);
274297
}

‎src-tauri/src/pairing/tests.rs‎

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -269,7 +269,38 @@ fn window_reload_or_destruction_cancels_the_live_attempt() {
269269
async fn unexpected_connection_failure_becomes_a_visible_error() {
270270
let result = guard(async { panic!("simulated connection setup failure") }).await;
271271
assert_eq!(
272-
result.unwrap_err(),
272+
match result.unwrap_err() {
273+
Failure::Transport(message) => message,
274+
other => panic!("{other:?}"),
275+
},
273276
"Pairing stopped unexpectedly. Create a new code and try again."
274277
);
275278
}
279+
280+
#[test]
281+
fn transport_failure_is_uncertain_after_publication_but_phone_rejection_is_definite() {
282+
let manager = Pairing::default();
283+
let (tx, _) = mpsc::channel(1);
284+
*manager.0.lock().unwrap() = Some(Active {
285+
id: "live".into(),
286+
cancel: CancellationToken::new(),
287+
confirm: tx,
288+
status: Status::Transferring,
289+
payload_sent: false,
290+
});
291+
let error = Status::Error {
292+
message: "connection lost".into(),
293+
};
294+
manager.fail("live", error.clone(), true);
295+
assert_eq!(manager.0.lock().unwrap().as_ref().unwrap().status, error);
296+
manager.mark_payload_sent("live");
297+
manager.fail("stale", error.clone(), true);
298+
assert_eq!(manager.0.lock().unwrap().as_ref().unwrap().status, error);
299+
manager.fail("live", error.clone(), true);
300+
assert_eq!(
301+
manager.0.lock().unwrap().as_ref().unwrap().status,
302+
Status::Uncertain
303+
);
304+
manager.fail("live", error.clone(), false);
305+
assert_eq!(manager.0.lock().unwrap().as_ref().unwrap().status, error);
306+
}

‎src/bundled/pairing/PairingSettings.test.tsx‎

Lines changed: 85 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -96,65 +96,94 @@ it.each([true, false])(
9696
},
9797
);
9898

99-
it("keeps an unacknowledged transfer visible until a deliberate new attempt", async () => {
100-
vi.useFakeTimers();
101-
vi.stubGlobal("matchMedia", () => ({
102-
matches: false,
103-
addEventListener() {},
104-
removeEventListener() {},
105-
}));
106-
const viewer = "a".repeat(64);
107-
const snapshot: ClientSnapshot = {
108-
status: "ready",
109-
relayAvailable: true,
110-
viewer,
111-
selected: "https://community.example",
112-
profile: { name: "", picture: "" },
113-
memberships: [],
114-
};
115-
let status: PairingStatus = { phase: "idle" };
116-
const native = {
117-
account: vi.fn(async () => viewer),
118-
start: vi.fn<PairingNative["start"]>(async () => {
119-
status = { phase: "qr", svg: "<svg/>" };
120-
}),
121-
status: vi.fn(async () => status),
122-
cancel: vi.fn(async () => {}),
123-
confirm: vi.fn(async () => {}),
124-
} satisfies PairingNative;
125-
await act(async () => {
126-
render(
99+
it.each(["uncertain", "cancelled"] as const)(
100+
"keeps %s terminal until a deliberate new attempt",
101+
async (phase) => {
102+
vi.useFakeTimers();
103+
vi.stubGlobal("matchMedia", () => ({
104+
matches: false,
105+
addEventListener() {},
106+
removeEventListener() {},
107+
}));
108+
const viewer = "a".repeat(64);
109+
let snapshot: ClientSnapshot = {
110+
status: "ready",
111+
relayAvailable: true,
112+
viewer,
113+
selected: "https://community.example",
114+
profile: { name: "", picture: "" },
115+
memberships: [],
116+
};
117+
let status: PairingStatus = { phase: "idle" };
118+
const native = {
119+
account: vi.fn(async () => viewer),
120+
start: vi.fn<PairingNative["start"]>(async () => {
121+
status = { phase: "qr", svg: "<svg/>" };
122+
}),
123+
status: vi.fn(async () => status),
124+
cancel: vi.fn(async () => {}),
125+
confirm: vi.fn(async () => {}),
126+
} satisfies PairingNative;
127+
let mounted!: ReturnType<typeof render>;
128+
const view = () => (
127129
<PairingSettings
128130
communities={{ snapshot: () => snapshot, subscribe: () => () => {} }}
129131
active={() => true}
130132
available
131133
native={native}
132-
/>,
133-
);
134-
});
135-
expect(native.start).toHaveBeenCalledTimes(1);
136-
status = { phase: "transferring" };
137-
await act(async () => {
138-
await vi.advanceTimersByTimeAsync(400);
139-
});
140-
status = { phase: "uncertain" };
141-
await act(async () => {
142-
await vi.advanceTimersByTimeAsync(400);
143-
});
144-
expect(
145-
screen.getByRole("heading", { name: "Check your phone" }),
146-
).toBeTruthy();
147-
expect(
148-
screen.queryByAltText("Scan this QR code with Buzz on your phone"),
149-
).toBeNull();
150-
await act(async () => {
151-
await vi.advanceTimersByTimeAsync(240000);
152-
});
153-
expect(native.start).toHaveBeenCalledTimes(1);
154-
await act(async () => {
155-
fireEvent.click(
156-
screen.getByRole("button", { name: "Start a new pairing" }),
134+
/>
157135
);
158-
});
159-
expect(native.start).toHaveBeenCalledTimes(2);
160-
});
136+
await act(async () => {
137+
mounted = render(
138+
<PairingSettings
139+
communities={{ snapshot: () => snapshot, subscribe: () => () => {} }}
140+
active={() => true}
141+
available
142+
native={native}
143+
/>,
144+
);
145+
});
146+
expect(native.start).toHaveBeenCalledTimes(1);
147+
status = { phase: "transferring" };
148+
await act(async () => {
149+
await vi.advanceTimersByTimeAsync(400);
150+
});
151+
status = { phase };
152+
await act(async () => {
153+
await vi.advanceTimersByTimeAsync(400);
154+
});
155+
if (phase === "uncertain")
156+
expect(
157+
screen.getByRole("heading", { name: "Check your phone" }),
158+
).toBeTruthy();
159+
expect(
160+
screen.queryByAltText("Scan this QR code with Buzz on your phone"),
161+
).toBeNull();
162+
await act(async () => {
163+
await vi.advanceTimersByTimeAsync(240000);
164+
});
165+
expect(native.start).toHaveBeenCalledTimes(1);
166+
await act(async () => {
167+
fireEvent.click(
168+
screen.getByRole("button", {
169+
name: phase === "uncertain" ? "Start a new pairing" : "Try again",
170+
}),
171+
);
172+
});
173+
expect(native.start).toHaveBeenCalledTimes(2);
174+
snapshot = {
175+
...snapshot,
176+
viewer: "b".repeat(64),
177+
selected: "https://other.example",
178+
};
179+
await act(async () => {
180+
mounted.rerender(view());
181+
});
182+
expect(native.start).toHaveBeenCalledTimes(3);
183+
expect(native.start.mock.calls[2]).toEqual([
184+
expect.any(String),
185+
"b".repeat(64),
186+
"https://other.example",
187+
]);
188+
},
189+
);

‎src/bundled/pairing/PairingSettings.tsx‎

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,7 @@ export function PairingSettings({
6161
lifetime.current++;
6262
return () => {
6363
lifetime.current++;
64-
void pairing.cancel();
64+
void pairing.cancel(true);
6565
};
6666
}, [pairing]);
6767
// Changing accounts/communities invalidates the pairing being displayed.
@@ -72,7 +72,7 @@ export function PairingSettings({
7272
setAccount(client.viewer);
7373
setRelay(client.selected ? communityDestination(client.selected).url : "");
7474
return () => {
75-
void pairing.cancel();
75+
void pairing.cancel(true);
7676
};
7777
}, [client.viewer, client.selected, pairing]);
7878
const busy = ["connecting", "qr", "code", "transferring"].includes(
@@ -116,7 +116,7 @@ export function PairingSettings({
116116
(client.viewer && account !== client.viewer) ||
117117
(client.selected &&
118118
relay !== communityDestination(client.selected).url) ||
119-
!["idle", "cancelled", "expired"].includes(state.phase)
119+
!["idle", "expired"].includes(state.phase)
120120
)
121121
return;
122122
const origin = client.selected ? relayOrigin(relay) : manualOrigin;
@@ -224,7 +224,7 @@ export function PairingSettings({
224224
/>
225225
</div>
226226
)}
227-
{state.phase === "error" && (
227+
{["error", "cancelled"].includes(state.phase) && (
228228
<Button variant="prominent" onClick={start}>
229229
Try again
230230
</Button>
@@ -324,9 +324,7 @@ export function PairingSettings({
324324
className="text-success"
325325
/>
326326
<h3 className="m-0 text-label">Phone paired</h3>
327-
<Button onClick={() => void pairing.cancel()}>
328-
Pair another phone
329-
</Button>
327+
<Button onClick={start}>Pair another phone</Button>
330328
</div>
331329
)}
332330
{(error || state.phase === "error") && (

‎src/features/pairing/client.test.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -118,3 +118,17 @@ it("does not revive legacy confirmation from a status response already in flight
118118
expect(api.confirm).toHaveBeenCalledTimes(1);
119119
await client.cancel();
120120
});
121+
122+
it("resets client-controlled cleanup without treating native cancellation as idle", async () => {
123+
const api = native();
124+
const client = createPairingClient(api);
125+
api.status.mockResolvedValue({ phase: "cancelled" });
126+
await client.start("viewer", "https://relay.test");
127+
expect(client.snapshot().phase).toBe("cancelled");
128+
await client.cancel(true);
129+
expect(client.snapshot().phase).toBe("idle");
130+
api.cancel.mockRejectedValue(new Error("cleanup failed"));
131+
await client.start("viewer", "https://relay.test");
132+
await client.cancel(true);
133+
expect(client.snapshot().phase).toBe("error");
134+
});

‎src/features/pairing/client.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,11 +124,12 @@ export function createPairingClient(native: PairingNative = nativePairing) {
124124
update({ phase: "error", message: String(error) });
125125
}
126126
},
127-
async cancel() {
127+
async cancel(reset = false) {
128128
const attempt = ++generation;
129129
update({ phase: "cancelled" });
130130
try {
131131
await stop();
132+
if (reset && attempt === generation) update({ phase: "idle" });
132133
} catch {
133134
if (attempt === generation)
134135
update({

0 commit comments

Comments
 (0)