Skip to content

Commit 9a59e30

Browse files
wpfleger96npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7
andauthored
feat(desktop): refresh Agents tab live on inbound relay sync (#1256)
Signed-off-by: Will Pfleger <[email protected]> Co-authored-by: npub1mn7jgtj4w2pd0g0zeuhxsa6jy6p0rewxz4kujt98my82ahfmp72sxjexk7 <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@sprout-oss.stage.blox.sqprod.co>
1 parent 0379247 commit 9a59e30

7 files changed

Lines changed: 355 additions & 3 deletions

File tree

‎desktop/playwright.config.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ export default defineConfig({
6969
"**/sidebar-relay-card.spec.ts",
7070
"**/tokens.spec.ts",
7171
"**/persona-env-vars.spec.ts",
72+
"**/persona-sync.spec.ts",
7273
"**/mesh-compute.spec.ts",
7374
],
7475
use: {

‎desktop/scripts/check-file-sizes.mjs‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,9 @@ const overrides = new Map([
5454
// (reconcile_inbound_tombstone), the two apply_inbound_* fns, the
5555
// event_d_tag/parse_deletion_coordinate helpers, and the preserve/overwrite +
5656
// secret-injection + tombstone test coverage. Load-bearing feature growth,
57-
// queued to split with the list.
58-
["src-tauri/src/commands/personas.rs", 1271],
57+
// queued to split with the list. The two `agents-data-changed` emits (live
58+
// UI refresh on inbound reconcile + tombstone) add the latest growth.
59+
["src-tauri/src/commands/personas.rs", 1279],
5960
["src-tauri/src/managed_agents/persona_card.rs", 1050],
6061
// applyWorkspace reposDir parameter plus the validateReposDir binding,
6162
// threaded through Tauri invokes for configurable repos_dir, plus the

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

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use tauri::{AppHandle, State};
1+
use tauri::{AppHandle, Emitter, State};
22
use uuid::Uuid;
33

44
use super::export_util::save_json_with_dialog;
@@ -442,6 +442,10 @@ pub fn reconcile_inbound_persona_event(
442442
}
443443
try_regenerate_nest(&app);
444444

445+
// Signal the live UI to refetch agents data — inbound relay events otherwise
446+
// land on disk silently, leaving the Agents tab stale until restart.
447+
let _ = app.emit("agents-data-changed", ());
448+
445449
Ok(())
446450
}
447451

@@ -539,6 +543,10 @@ fn reconcile_inbound_tombstone(
539543
}
540544
try_regenerate_nest(app);
541545

546+
// Refresh the live UI on inbound deletion — a removal is as user-visible as
547+
// an upsert and the Agents tab must drop the tombstoned record without restart.
548+
let _ = app.emit("agents-data-changed", ());
549+
542550
Ok(())
543551
}
544552

‎desktop/src/app/AppShell.tsx‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import {
3737
import { setDesktopAppBadge } from "@/features/notifications/lib/desktop";
3838
import { PreventSleepProvider } from "@/features/agents/usePreventSleep";
3939
import { requestOpenCreateAgent } from "@/features/agents/openCreateAgentEvent";
40+
import { useAgentsDataRefresh } from "@/features/agents/lib/useAgentsDataRefresh";
4041
import { usePersonaSync } from "@/features/agents/lib/usePersonaSync";
4142
import {
4243
usePresenceSession,
@@ -139,6 +140,7 @@ export function AppShell() {
139140
identityQuery.data?.pubkey,
140141
);
141142
usePersonaSync(identityQuery.data?.pubkey);
143+
useAgentsDataRefresh();
142144
const profileQuery = useProfileQuery();
143145
const deferredPubkey = startupReady ? identityQuery.data?.pubkey : undefined;
144146
useRelayAutoHeal();
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { listen } from "@tauri-apps/api/event";
2+
import { useQueryClient } from "@tanstack/react-query";
3+
import { useEffect } from "react";
4+
5+
import {
6+
managedAgentsQueryKey,
7+
personasQueryKey,
8+
relayAgentsQueryKey,
9+
teamsQueryKey,
10+
} from "@/features/agents/hooks";
11+
12+
// Trailing-coalesce window: a backfill burst (up to 500 inbound events fed
13+
// one-by-one through reconcile) fires one `agents-data-changed` per event.
14+
// Collapsing them into a single invalidate after the burst settles keeps the
15+
// refetch off React Query's implicit in-flight dedup and avoids redundant
16+
// disk-read IPC.
17+
const COALESCE_MS = 200;
18+
19+
// Invalidate the live Agents-tab queries when the backend signals that inbound
20+
// relay events changed the on-disk agents data. Mounted once at the app root
21+
// with empty deps — invalidation is global and has no reason to be
22+
// pubkey-scoped, so it must NOT live inside the pubkey-keyed `usePersonaSync`
23+
// (re-registering per identity switch would leak a listener each time).
24+
export function useAgentsDataRefresh(): void {
25+
const queryClient = useQueryClient();
26+
27+
useEffect(() => {
28+
let timer: ReturnType<typeof setTimeout> | undefined;
29+
30+
const unlisten = listen("agents-data-changed", () => {
31+
if (timer !== undefined) clearTimeout(timer);
32+
timer = setTimeout(() => {
33+
void queryClient.invalidateQueries({ queryKey: personasQueryKey });
34+
void queryClient.invalidateQueries({ queryKey: teamsQueryKey });
35+
void queryClient.invalidateQueries({ queryKey: managedAgentsQueryKey });
36+
void queryClient.invalidateQueries({ queryKey: relayAgentsQueryKey });
37+
}, COALESCE_MS);
38+
});
39+
40+
return () => {
41+
if (timer !== undefined) clearTimeout(timer);
42+
void unlisten.then((fn) => fn());
43+
};
44+
}, [queryClient]);
45+
}

‎desktop/src/testing/e2eBridge.ts‎

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1616,6 +1616,8 @@ function resetMockMesh() {
16161616
}
16171617
let mockPersonas: RawPersona[] = [];
16181618
let mockTeams: RawTeam[] = [];
1619+
// Listeners registered via the mock __TAURI_INTERNALS__.listen — keyed by event name.
1620+
const tauriEventListeners = new Map<string, Set<() => void>>();
16191621
const defaultMockRelayAgents: RawRelayAgent[] = [
16201622
{
16211623
pubkey: ALICE_PUBKEY,
@@ -6644,6 +6646,61 @@ export function maybeInstallE2eTauriMocks() {
66446646
return handleDeletePersona(
66456647
payload as Parameters<typeof handleDeletePersona>[0],
66466648
);
6649+
case "reconcile_inbound_persona_event": {
6650+
const nostrEvent = JSON.parse(
6651+
(payload as { eventJson: string }).eventJson,
6652+
) as {
6653+
kind: number;
6654+
tags: string[][];
6655+
content: string;
6656+
created_at: number;
6657+
};
6658+
if (nostrEvent.kind === 30175) {
6659+
// Persona upsert — parse content and upsert into mockPersonas by d-tag
6660+
const dTag = nostrEvent.tags.find((t) => t[0] === "d")?.[1];
6661+
if (dTag) {
6662+
const content = JSON.parse(nostrEvent.content) as {
6663+
display_name?: string;
6664+
system_prompt?: string;
6665+
};
6666+
const now = new Date().toISOString();
6667+
const existing = mockPersonas.find((p) => p.id === dTag);
6668+
if (existing) {
6669+
existing.display_name =
6670+
content.display_name ?? existing.display_name;
6671+
existing.system_prompt =
6672+
content.system_prompt ?? existing.system_prompt;
6673+
existing.updated_at = now;
6674+
} else {
6675+
mockPersonas.push({
6676+
id: dTag,
6677+
display_name: content.display_name ?? dTag,
6678+
avatar_url: null,
6679+
system_prompt: content.system_prompt ?? "",
6680+
is_builtin: false,
6681+
is_active: true,
6682+
env_vars: {},
6683+
created_at: now,
6684+
updated_at: now,
6685+
});
6686+
}
6687+
}
6688+
} else if (nostrEvent.kind === 5) {
6689+
// Tombstone — extract d-tag from a-tag "30175:<pubkey>:<d_tag>" and remove
6690+
const aTagValue = nostrEvent.tags.find((t) => t[0] === "a")?.[1];
6691+
if (aTagValue) {
6692+
const dTag = aTagValue.split(":")[2];
6693+
if (dTag) {
6694+
mockPersonas = mockPersonas.filter((p) => p.id !== dTag);
6695+
}
6696+
}
6697+
}
6698+
// Mirror the real Rust backend: emit "agents-data-changed" after reconcile.
6699+
for (const cb of tauriEventListeners.get("agents-data-changed") ?? []) {
6700+
cb();
6701+
}
6702+
return undefined;
6703+
}
66476704
case "set_persona_active":
66486705
return handleSetPersonaActive(
66496706
payload as Parameters<typeof handleSetPersonaActive>[0],
@@ -7028,5 +7085,26 @@ export function maybeInstallE2eTauriMocks() {
70287085
handleMockCommand(command, payload ?? null);
70297086
mockIPC(handleMockCommand);
70307087

7088+
// Wire up __TAURI_INTERNALS__.listen so tests can subscribe to backend-emitted
7089+
// events (e.g. "agents-data-changed"). mockIPC already ensures __TAURI_INTERNALS__
7090+
// exists; we just add the listen property without clobbering invoke.
7091+
(
7092+
window as unknown as {
7093+
__TAURI_INTERNALS__: {
7094+
listen?: (event: string, cb: () => void) => Promise<() => void>;
7095+
};
7096+
}
7097+
).__TAURI_INTERNALS__.listen = async (event: string, cb: () => void) => {
7098+
let listeners = tauriEventListeners.get(event);
7099+
if (!listeners) {
7100+
listeners = new Set();
7101+
tauriEventListeners.set(event, listeners);
7102+
}
7103+
listeners.add(cb);
7104+
return () => {
7105+
tauriEventListeners.get(event)?.delete(cb);
7106+
};
7107+
};
7108+
70317109
installed = true;
70327110
}

0 commit comments

Comments
 (0)