Skip to content

Commit c59067d

Browse files
loganjLarry
andcommitted
fix(desktop): preserve failed presence and share surface snapshots
Propagate native query errors; share aggregate presence with cards, menus and lifecycle actions. Keep failed aggregate siblings unknown through live/self updates until successful snapshot retry. Add native command, mounted lifecycle and real-surface request-count regressions. Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz> Signed-off-by: Logan Johnson <[email protected]>
1 parent 41d3bd3 commit c59067d

16 files changed

Lines changed: 531 additions & 60 deletions

‎desktop/src-tauri/src/commands/profile.rs‎

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -344,17 +344,16 @@ pub async fn get_presence(
344344
}
345345

346346
// Presence is published as kind:20001 ephemeral events. Query the most
347-
// recent per author. Some relays don't retain ephemeral events — we
348-
// best-effort and return what we get.
347+
// recent per author. Only a successful empty snapshot establishes absence;
348+
// transport/auth/storage failures must reject so consumers remain unknown.
349349
let events = query_relay(
350350
&state,
351351
&[serde_json::json!({
352352
"kinds": [20001],
353353
"authors": pubkeys,
354354
})],
355355
)
356-
.await
357-
.unwrap_or_default();
356+
.await?;
358357

359358
let mut latest: HashMap<String, (u64, PresenceStatus)> = HashMap::new();
360359
for ev in &events {
@@ -482,3 +481,7 @@ mod tests {
482481
assert_eq!(filter["page"], serde_json::json!(1));
483482
}
484483
}
484+
485+
#[cfg(test)]
486+
#[path = "profile_presence_tests.rs"]
487+
mod presence_tests;
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
//! Drive the actual get_presence command through its authenticated HTTP query.
2+
//! In particular, an error must not become a successful empty IPC snapshot.
3+
use super::get_presence;
4+
use crate::app_state::build_app_state;
5+
use crate::relay_admission::{reset_rate_limit_gate, TEST_SERIAL};
6+
use tauri::Manager;
7+
use tokio::io::{AsyncReadExt, AsyncWriteExt};
8+
9+
#[tokio::test]
10+
async fn presence_command_preserves_query_failure_and_successful_absence() {
11+
let _serial = TEST_SERIAL.lock().await;
12+
reset_rate_limit_gate();
13+
for (status, body) in [
14+
("200 OK", "[]"),
15+
("401 Unauthorized", r#"{"error":"unauthorized"}"#),
16+
("429 Too Many Requests", r#"{"error":"retry in 1s"}"#),
17+
(
18+
"500 Internal Server Error",
19+
r#"{"error":"storage unavailable"}"#,
20+
),
21+
("200 OK", "not json"),
22+
] {
23+
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
24+
let addr = listener.local_addr().unwrap();
25+
let server = tokio::spawn(async move {
26+
let (mut stream, _) = listener.accept().await.unwrap();
27+
let mut request = Vec::new();
28+
loop {
29+
let mut buf = [0; 4096];
30+
let count = stream.read(&mut buf).await.unwrap();
31+
assert!(count > 0);
32+
request.extend_from_slice(&buf[..count]);
33+
assert!(request.len() < 16384);
34+
if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") {
35+
let headers = String::from_utf8_lossy(&request[..end]).to_lowercase();
36+
let length: usize = headers
37+
.lines()
38+
.find_map(|line| {
39+
line.strip_prefix("content-length:")
40+
.map(|v| v.trim().parse().unwrap())
41+
})
42+
.unwrap();
43+
if request.len() >= end + 4 + length {
44+
break;
45+
}
46+
}
47+
}
48+
let request = String::from_utf8(request).unwrap();
49+
assert!(request.starts_with("POST /query "));
50+
assert!(request.to_lowercase().contains("authorization: nostr "));
51+
assert!(request.contains("20001"));
52+
let response = format!("HTTP/1.1 {status}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", body.len());
53+
stream.write_all(response.as_bytes()).await.unwrap();
54+
});
55+
let state = build_app_state();
56+
*state.relay_url_override.lock().unwrap() = Some(format!("ws://{addr}"));
57+
let app = tauri::test::mock_builder()
58+
.manage(state)
59+
.build(tauri::test::mock_context(tauri::test::noop_assets()))
60+
.unwrap();
61+
let result = tokio::time::timeout(
62+
std::time::Duration::from_secs(5),
63+
get_presence(vec!["a".repeat(64)], app.state()),
64+
)
65+
.await
66+
.unwrap();
67+
tokio::time::timeout(std::time::Duration::from_secs(5), server)
68+
.await
69+
.unwrap()
70+
.unwrap();
71+
if status == "200 OK" && body == "[]" {
72+
assert_eq!(
73+
serde_json::to_value(result.unwrap()).unwrap(),
74+
serde_json::json!({})
75+
);
76+
} else {
77+
assert!(
78+
result.is_err(),
79+
"{status} / {body} must reject, not return Offline: {result:?}"
80+
);
81+
}
82+
reset_rate_limit_gate();
83+
}
84+
}
85+
86+
#[tokio::test]
87+
async fn presence_command_transport_failure_is_not_offline() {
88+
let _serial = TEST_SERIAL.lock().await;
89+
reset_rate_limit_gate();
90+
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
91+
let addr = listener.local_addr().unwrap();
92+
drop(listener);
93+
let state = build_app_state();
94+
*state.relay_url_override.lock().unwrap() = Some(format!("ws://{addr}"));
95+
let app = tauri::test::mock_builder()
96+
.manage(state)
97+
.build(tauri::test::mock_context(tauri::test::noop_assets()))
98+
.unwrap();
99+
let result = get_presence(vec!["a".repeat(64)], app.state()).await;
100+
assert!(result.is_err(), "transport failure must reject: {result:?}");
101+
// Empty input does not require a relay and remains a genuine empty result.
102+
assert!(get_presence(vec![], app.state()).await.unwrap().is_empty());
103+
}

‎desktop/src/features/agents/lib/useAgentAvailability.ts‎

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import * as React from "react";
12
import { usePresenceQuery } from "@/features/presence/hooks";
23
import type { PresenceStatus } from "@/shared/api/types";
34
import { useRelayConnection } from "@/shared/api/useRelayConnection";
@@ -27,14 +28,36 @@ export function agentPresenceStartBlockReason(
2728
: undefined;
2829
}
2930

30-
/** Share the existing presence query/subscription; no separate status cache. */
31-
export function useAgentAvailability(pubkey: string | null | undefined) {
32-
const query = usePresenceQuery(pubkey ? [pubkey] : []);
31+
/** Read availability from the surface-owned snapshot, not per-row polling. */
32+
export type AgentAvailabilityReader = (
33+
pubkey: string | null | undefined,
34+
) => PresenceStatus | undefined;
35+
36+
/** One query/connection observer for a surface's cards and lifecycle actions. */
37+
export function useAgentAvailabilityLookup(
38+
pubkeys: string[],
39+
options?: { enabled?: boolean },
40+
) {
41+
const query = usePresenceQuery(pubkeys, options);
3342
const connection = useRelayConnection();
34-
const status = resolveAgentAvailability(
35-
pubkey ? query.data?.[normalizePubkey(pubkey)] : undefined,
36-
query.isSuccess,
37-
connection === "connected",
43+
const getAvailability: AgentAvailabilityReader = React.useCallback(
44+
(pubkey) =>
45+
pubkey
46+
? resolveAgentAvailability(
47+
query.data?.[normalizePubkey(pubkey)],
48+
query.isSuccess,
49+
connection === "connected",
50+
)
51+
: undefined,
52+
[query.data, query.isSuccess, connection],
53+
);
54+
return { query, getAvailability };
55+
}
56+
57+
/** Single-identity surfaces use the same authority as aggregate surfaces. */
58+
export function useAgentAvailability(pubkey: string | null | undefined) {
59+
const { query, getAvailability } = useAgentAvailabilityLookup(
60+
pubkey ? [pubkey] : [],
3861
);
39-
return { query, status };
62+
return { query, status: getAvailability(pubkey) };
4063
}

‎desktop/src/features/agents/ui/AgentsView.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@ export function AgentsView() {
219219
/>
220220
<div className="flex flex-col gap-8">
221221
<UnifiedAgentsSection
222+
getAvailability={agents.getAvailability}
222223
defaultModel={inheritedDefaults.model.value}
223224
actionErrorMessage={agents.actionErrorMessage}
224225
actionNoticeMessage={agents.actionNoticeMessage}

‎desktop/src/features/agents/ui/UnifiedAgentsSection.tsx‎

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import {
88
import { resolveAgentCardModelLabel } from "@/features/agents/lib/agentCardModelLabel";
99
import { effectiveAgentDescription } from "@/features/agents/lib/agentDescription";
1010
import { friendlyAgentLastError } from "@/features/agents/lib/friendlyAgentLastError";
11-
import { useAgentAvailability } from "@/features/agents/lib/useAgentAvailability";
11+
import type { AgentAvailabilityReader } from "@/features/agents/lib/useAgentAvailability";
1212
import { isManagedAgentActive } from "@/features/agents/lib/managedAgentControlActions";
1313
import { pickProfileAgent } from "@/features/agents/lib/pickProfileAgent";
1414
import { useIsArchivedPredicate } from "@/features/identity-archive/hooks";
@@ -26,6 +26,7 @@ import { buildUnifiedGroups } from "./unifiedAgentGroups";
2626

2727
type UnifiedAgentsSectionProps = {
2828
defaultModel: string;
29+
getAvailability: AgentAvailabilityReader;
2930
actionErrorMessage: string | null;
3031
actionNoticeMessage: string | null;
3132
agents: ManagedAgent[];
@@ -71,6 +72,7 @@ export function UnifiedAgentsSection(props: UnifiedAgentsSectionProps) {
7172
actionErrorMessage,
7273
actionNoticeMessage,
7374
defaultModel,
75+
getAvailability,
7476
agents,
7577
agentsError,
7678
isActionPending,
@@ -154,6 +156,7 @@ export function UnifiedAgentsSection(props: UnifiedAgentsSectionProps) {
154156
/>
155157
)}
156158
agent={profileAgent}
159+
getAvailability={getAvailability}
157160
defaultModel={defaultModel}
158161
key={group.persona.id}
159162
persona={group.persona}
@@ -174,6 +177,7 @@ export function UnifiedAgentsSection(props: UnifiedAgentsSectionProps) {
174177
<CollapsibleAgentGroup
175178
agents={unknown}
176179
collapsed={collapsed}
180+
getAvailability={getAvailability}
177181
defaultModel={defaultModel}
178182
groupKey="__unknown__"
179183
label="Unknown agents"
@@ -189,6 +193,7 @@ export function UnifiedAgentsSection(props: UnifiedAgentsSectionProps) {
189193
<CollapsibleAgentGroup
190194
agents={ungrouped}
191195
collapsed={collapsed}
196+
getAvailability={getAvailability}
192197
defaultModel={defaultModel}
193198
groupKey="__ungrouped__"
194199
label="Custom agents"
@@ -225,6 +230,7 @@ function AgentPersonaCard({
225230
actions,
226231
agent,
227232
defaultModel,
233+
getAvailability,
228234
persona,
229235
restartingAgentPubkey,
230236
startingAgentPubkey,
@@ -241,6 +247,7 @@ function AgentPersonaCard({
241247
) => React.ReactNode;
242248
agent: ManagedAgent | undefined;
243249
defaultModel: string;
250+
getAvailability: AgentAvailabilityReader;
244251
persona: AgentPersona;
245252
restartingAgentPubkey: string | null;
246253
startingAgentPubkey: string | null;
@@ -254,7 +261,7 @@ function AgentPersonaCard({
254261
onStartAgent: (pubkey: string) => void;
255262
onStartPersona: (persona: AgentPersona) => void;
256263
}) {
257-
const { status: availability } = useAgentAvailability(agent?.pubkey);
264+
const availability = getAvailability(agent?.pubkey);
258265
const title = persona.displayName;
259266
// Card face second line: the authored description when one exists;
260267
// otherwise fall back to the model label as before.
@@ -348,6 +355,7 @@ function AgentPersonaCard({
348355
function StandaloneAgentCard({
349356
agent,
350357
defaultModel,
358+
getAvailability,
351359
restartingAgentPubkey,
352360
startingAgentPubkey,
353361
onOpenAgentProfile,
@@ -356,6 +364,7 @@ function StandaloneAgentCard({
356364
}: {
357365
agent: ManagedAgent;
358366
defaultModel: string;
367+
getAvailability: AgentAvailabilityReader;
359368
restartingAgentPubkey: string | null;
360369
startingAgentPubkey: string | null;
361370
onOpenAgentProfile: (
@@ -365,7 +374,7 @@ function StandaloneAgentCard({
365374
onRestartAgent: (pubkey: string) => void;
366375
onStartAgent: (pubkey: string) => void;
367376
}) {
368-
const { status: availability } = useAgentAvailability(agent.pubkey);
377+
const availability = getAvailability(agent.pubkey);
369378
const title = agent.name;
370379
const profileQuery = useUserProfileQuery(agent.pubkey);
371380
const friendlyError = friendlyAgentLastError(
@@ -457,6 +466,7 @@ function CollapsibleAgentGroup({
457466
agents,
458467
collapsed,
459468
defaultModel,
469+
getAvailability,
460470
restartingAgentPubkey,
461471
startingAgentPubkey,
462472
onToggle,
@@ -469,6 +479,7 @@ function CollapsibleAgentGroup({
469479
agents: ManagedAgent[];
470480
collapsed: ReadonlySet<string>;
471481
defaultModel: string;
482+
getAvailability: AgentAvailabilityReader;
472483
restartingAgentPubkey: string | null;
473484
startingAgentPubkey: string | null;
474485
onToggle: (key: string) => void;
@@ -500,6 +511,7 @@ function CollapsibleAgentGroup({
500511
{agents.map((agent) => (
501512
<StandaloneAgentCard
502513
agent={agent}
514+
getAvailability={getAvailability}
503515
defaultModel={defaultModel}
504516
key={agent.pubkey}
505517
restartingAgentPubkey={restartingAgentPubkey}

0 commit comments

Comments
 (0)