GitHub Actions commited on
Commit
e6bca78
Β·
1 Parent(s): 8514223

fix: node identity, Gradio 6 chatbot format, peer discovery; add routing+special-node docs; screenshots

Browse files

Bug fixes:
- hearthnet/ui/app.py: extract node_id/community_id from bus.node_id_full when
not passed in meta (fixes 'Node: unknown' header)
- hearthnet/ui/tabs/settings.py: same fix for Settings identity accordion;
fix peer refresh to use bus.registry.all_remote() (CapabilityEntry objects,
not snapshot dicts) β€” fixes 'dict has no attribute node_id' error
- hearthnet/ui/tabs/ask.py: Gradio 6 requires {role, content} dicts in chatbot,
not [[user, assistant]] pairs β€” fixes 'Data incompatible with messages format'
- hearthnet/ui/tabs/chat.py: same Gradio 6 chatbot format fix

Documentation:
- docs/HOWTO.md: added sections 11 (How Routing Works) and 12 (Special-Feature
Nodes) β€” covers score formula, params routing, sticky sessions, offline
fallback, OCR/medical/anchor/translation/civil-defense node examples
- Updated Table of Contents

Screenshots (two real nodes, Alice + Bob, services + peer discovery):
- 01-alice-ask-empty.png: Ask tab with correct node identity
- 02-alice-ask-response.png: LLM echo response from demo-local backend
- 03-alice-chat.png: Chat tab β€” Alice sends to Bob, delivered=queued + event_id
- 04-alice-marketplace.png: Marketplace tab
- 05-alice-files.png: Files tab
- 06-alice-emergency.png: Emergency mode + probe button
- 07-alice-settings.png: Settings with Node ID=alice, Community=ed25519:hearthnet-demo
- 08-alice-settings-peers.png: Peer list after Refresh β€” Bob visible + 10 caps
- 09-bob-ask-tab.png: Bob's independent UI, Node=bob
- 09b-bob-ask-response.png: Bob's LLM response
- 10-bob-settings.png: Bob's settings
- 10b-bob-settings-peers.png: Bob sees Alice as peer

Scripts:
- scripts/demo_two_nodes.py: launch two-node mesh locally (Alice+Bob)
- scripts/gen_screenshots.py: automated screenshot generator (Playwright)

Tests: 51 unit tests still passing

docs/HOWTO.md CHANGED
@@ -16,6 +16,8 @@ This document answers the most common setup and usage questions.
16
  8. [Inviting Other Nodes](#8-inviting)
17
  9. [How to Extend HearthNet (developer)](#9-extending)
18
  10. [Troubleshooting](#10-troubleshooting)
 
 
19
 
20
  ---
21
 
@@ -518,3 +520,183 @@ python -m hearthnet.cli log --follow
518
  python -m hearthnet.cli call emergency.probe@1.0 '{}'
519
  # Or in UI: Emergency tab β†’ Run Connectivity Probe
520
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  8. [Inviting Other Nodes](#8-inviting)
17
  9. [How to Extend HearthNet (developer)](#9-extending)
18
  10. [Troubleshooting](#10-troubleshooting)
19
+ 11. [How Routing Works](#11-routing)
20
+ 12. [Creating a Special-Feature Node](#12-special-feature-nodes)
21
 
22
  ---
23
 
 
520
  python -m hearthnet.cli call emergency.probe@1.0 '{}'
521
  # Or in UI: Emergency tab β†’ Run Connectivity Probe
522
  ```
523
+
524
+ ---
525
+
526
+ ## 11. How Routing Works
527
+
528
+ **Spec:** [docs/M03-bus.md](M03-bus.md) Β§3.5 / Β§5.4
529
+ **Implementation:** `hearthnet/bus/router.py`, `hearthnet/bus/__init__.py`
530
+
531
+ ### The capability bus
532
+
533
+ Every node has a `CapabilityBus`. Services register their capabilities on startup.
534
+ When another node or the UI calls `bus.call("llm.chat", (1, 0), body)`, the bus:
535
+
536
+ 1. **Route selection** β€” `Router.route(req)` scores all registered providers (local and remote) using the score formula below.
537
+ 2. **Local-first** β€” local handlers always get priority over remote ones (lower latency, no serialization).
538
+ 3. **Call dispatch** β€” if local: `await entry.handler(req)`; if remote: `await transport.call(node_id, req)`.
539
+ 4. **Health update** β€” `HealthTracker.record(entry, success, latency_ms)` updates rolling success-rate and latency EMA.
540
+
541
+ ### Score formula
542
+
543
+ ```
544
+ score = (1.0 if is_local else 0.5)
545
+ + success_rate * 0.3
546
+ - (in_flight / max_concurrent) * 0.2
547
+ + (1.0 if not quarantined else -999)
548
+ ```
549
+
550
+ A quarantined entry (repeated failures) scores `-999` and is skipped until the cooldown expires.
551
+
552
+ ### Params-based routing
553
+
554
+ When a capability descriptor is registered with **params** (e.g. `{"corpus": "medical", "requires_internet": False}`), the router also checks whether the caller's `body["params"]` are compatible:
555
+
556
+ ```python
557
+ def _corpus_matches(offered: dict, requested: dict) -> bool:
558
+ return requested.get("corpus", offered["corpus"]) == offered["corpus"]
559
+ ```
560
+
561
+ This lets multiple nodes serve the same capability name with different parameters, and callers select the one that matches their requirements.
562
+
563
+ ### Sticky sessions (M10 Chat)
564
+
565
+ Pass `session_id` to `bus.call(...)` to pin subsequent calls to the same node:
566
+
567
+ ```python
568
+ result = await bus.call("chat.history", (1, 0), body, session_id="s:abc123")
569
+ ```
570
+
571
+ Subsequent calls with the same `session_id` route to the same entry (sticky routing).
572
+
573
+ ### Routing a call to a specific node
574
+
575
+ Use the `InMemoryTransport` directly (in tests) or send an HTTP request to the transport server:
576
+
577
+ ```
578
+ POST http://<node-host>:7080/call
579
+ Content-Type: application/json
580
+
581
+ {
582
+ "capability": "llm.chat",
583
+ "version_req": [1, 0],
584
+ "body": {"input": {"messages": [{"role": "user", "content": "Hello"}]}}
585
+ }
586
+ ```
587
+
588
+ ### Offline/Emergency routing
589
+
590
+ When `Detector.apply_probe_results({"internet": False})` marks the node offline:
591
+ - All capabilities with `requires_internet=True` are **deregistered** from the bus
592
+ - Calls that were routed to internet-only providers now fail over to local providers
593
+ - This is automatic β€” callers see no difference
594
+
595
+ ---
596
+
597
+ ## 12. Creating a Special-Feature Node
598
+
599
+ A **special-feature node** is any node where you register a non-default set of capabilities.
600
+
601
+ ### OCR-only node (medical document reading)
602
+
603
+ ```python
604
+ # hearthnet/examples/ocr_node.py
605
+ from hearthnet.node import HearthNode
606
+ from hearthnet.services.ocr.service import OcrService # M17
607
+ from hearthnet.ui.app import build_ui
608
+
609
+ node = HearthNode("ocr-node-01", "OCR Specialist", "ed25519:your-community")
610
+ node.bus.register_service(OcrService(backend="tesseract"))
611
+ # Do NOT install LLM or RAG services if this node should only do OCR
612
+
613
+ ui = build_ui(bus=node.bus, display_name=node.display_name, node_id=node.node_id, community_id=node.community_id)
614
+ ui.build().launch(server_port=7865)
615
+ ```
616
+
617
+ Any other node in the community can now call `ocr.extract@1.0` and the bus
618
+ automatically routes it to this specialist node.
619
+
620
+ ### Medical-RAG node (EBKH evidence base)
621
+
622
+ ```python
623
+ from hearthnet.services.demo import RagService
624
+ from hearthnet.services.llm.service import LlmService
625
+
626
+ # Install LLM with a domain-specific system prompt
627
+ llm = LlmService(model="ollama:meditron-7b")
628
+ rag = RagService(corpus="medical-ebkh")
629
+
630
+ node.bus.register_service(llm)
631
+ node.bus.register_service(rag)
632
+
633
+ # Optionally seed the RAG corpus on startup
634
+ import asyncio
635
+ asyncio.run(node.rag.ingest("medical-ebkh", title="WHO First Aid", text="..."))
636
+ ```
637
+
638
+ ### Anchor node (high-availability, no UI)
639
+
640
+ An **anchor** node (`profile="anchor"`) is designed for always-on servers or Pis:
641
+
642
+ ```bash
643
+ python -m hearthnet.cli run --profile anchor --no-ui
644
+ ```
645
+
646
+ ```toml
647
+ [identity]
648
+ profile = "anchor"
649
+
650
+ [transport]
651
+ host = "0.0.0.0"
652
+ port = 7080
653
+
654
+ [ui]
655
+ enabled = false # anchor nodes typically don't serve a web UI
656
+ ```
657
+
658
+ Anchor nodes act as relay points (M15) and capability hubs. Other nodes discover them and offload compute tasks.
659
+
660
+ ### Multilingual translation node (M18)
661
+
662
+ ```python
663
+ from hearthnet.services.translation.service import TranslationService
664
+
665
+ node.bus.register_service(
666
+ TranslationService(backend="helsinki-nlp", languages=["de", "fr", "es", "ar"])
667
+ )
668
+ ```
669
+
670
+ Callers use `translation.translate@1.0` with `{"input": {"text": "...", "source": "en", "target": "de"}}`.
671
+
672
+ ### Civil Defense node (M31) β€” emergency broadcast
673
+
674
+ ```python
675
+ from hearthnet.services.civil_defense.service import CivilDefenseService
676
+
677
+ node.bus.register_service(
678
+ CivilDefenseService(
679
+ broadcast_endpoints=["239.255.42.42:42425"], # UDP multicast
680
+ priority_filter="critical",
681
+ )
682
+ )
683
+ ```
684
+
685
+ ### Combining capabilities (full-service node)
686
+
687
+ ```python
688
+ node.install_demo_services() # LLM, RAG, Marketplace, Chat
689
+
690
+ # Then add specialist services on top:
691
+ node.bus.register_service(OcrService())
692
+ node.bus.register_service(TranslationService())
693
+ node.bus.register_service(SttTtsService())
694
+ ```
695
+
696
+ The bus merges all capabilities. Peer nodes discover all of them via the manifest exchange.
697
+
698
+ ### Verified capabilities in the UI
699
+
700
+ The Settings tab β†’ "Connected Peers & Capabilities" β†’ Refresh shows the live list
701
+ of what each peer node offers. You can verify routing is correct before deploying.
702
+
docs/screenshots/01-alice-ask-empty.png ADDED
docs/screenshots/02-alice-ask-response.png ADDED
docs/screenshots/03-alice-chat.png ADDED
docs/screenshots/04-alice-marketplace.png ADDED
docs/screenshots/05-alice-files.png ADDED
docs/screenshots/06-alice-emergency.png ADDED
docs/screenshots/07-alice-settings.png ADDED
docs/screenshots/08-alice-settings-peers.png ADDED
docs/screenshots/09-bob-ask-tab.png ADDED
docs/screenshots/09b-bob-ask-response.png ADDED
docs/screenshots/10-bob-settings.png ADDED
docs/screenshots/10b-bob-settings-peers.png ADDED
docs/screenshots/alice-ask-fresh.png ADDED
docs/screenshots/alice-ask-tab-full.png ADDED
docs/screenshots/alice-ask-tab.png ADDED
docs/screenshots/alice-home.png ADDED
hearthnet/ui/app.py CHANGED
@@ -34,12 +34,21 @@ class UiApp:
34
  from hearthnet.ui.tabs.marketplace import build_marketplace_tab
35
  from hearthnet.ui.tabs.settings import build_settings_tab
36
 
37
- with gr.Blocks(title="HearthNet", theme=gr.themes.Soft()) as demo:
38
- gr.Markdown("# πŸ”₯ HearthNet β€” Community AI Mesh")
 
 
 
 
 
 
 
 
39
 
40
  with gr.Row():
41
  gr.HTML(value="<span style='color:green'>● ONLINE</span>")
42
- gr.Markdown(f"Node: `{self._meta.get('node_id', 'unknown')[:20]}`")
 
43
 
44
  with gr.Tabs():
45
  with gr.Tab("Ask"):
 
34
  from hearthnet.ui.tabs.marketplace import build_marketplace_tab
35
  from hearthnet.ui.tabs.settings import build_settings_tab
36
 
37
+ # Pull identity from bus when not explicitly provided in meta
38
+ if self._bus is not None:
39
+ self._meta.setdefault("node_id", getattr(self._bus, "node_id_full", "unknown"))
40
+ self._meta.setdefault("community_id", getattr(self._bus, "community_id", "unknown"))
41
+
42
+ node_id_display = self._meta.get("node_id", "unknown")
43
+ display_name = self._meta.get("display_name", node_id_display[:20])
44
+
45
+ with gr.Blocks(title=f"HearthNet β€” {display_name}", theme=gr.themes.Soft()) as demo:
46
+ gr.Markdown(f"# πŸ”₯ HearthNet β€” {display_name}")
47
 
48
  with gr.Row():
49
  gr.HTML(value="<span style='color:green'>● ONLINE</span>")
50
+ gr.Markdown(f"Node: `{node_id_display[:40]}`")
51
+ gr.Markdown(f"Community: `{self._meta.get('community_id', 'unknown')[:30]}`")
52
 
53
  with gr.Tabs():
54
  with gr.Tab("Ask"):
hearthnet/ui/tabs/ask.py CHANGED
@@ -40,11 +40,12 @@ def build_ask_tab(bus=None):
40
  if not message.strip():
41
  return history, "", gr.update(visible=False), []
42
 
 
43
  history = history or []
44
- history.append([message, None])
45
 
46
  if bus is None:
47
- history[-1][1] = "⚠️ Bus not connected. Running in demo mode."
48
  return history, "", gr.update(visible=False), []
49
 
50
  try:
@@ -75,15 +76,12 @@ def build_ask_tab(bus=None):
75
  except Exception:
76
  pass
77
 
78
- # LLM call
79
- messages = []
80
  if context:
81
- messages.append({"role": "system", "content": f"Context:\n{context}"})
82
- for user_msg, assistant_msg in history[:-1]:
83
- messages.append({"role": "user", "content": user_msg})
84
- if assistant_msg:
85
- messages.append({"role": "assistant", "content": assistant_msg})
86
- messages.append({"role": "user", "content": message})
87
 
88
  params = {}
89
  if model and model != "auto":
@@ -92,17 +90,17 @@ def build_ask_tab(bus=None):
92
  result = await bus.call(
93
  "llm.chat",
94
  (1, 0),
95
- {"params": params, "input": {"messages": messages}},
96
  )
97
  reply = (
98
  result.get("output", {}).get("message", {}).get("content", "No response")
99
  )
100
- history[-1][1] = reply
101
 
102
  return history, "", gr.update(visible=bool(sources), value=sources), sources
103
 
104
  except Exception as exc:
105
- history[-1][1] = f"Error: {exc}"
106
  return history, "", gr.update(visible=False), []
107
 
108
  send_btn.click(
 
40
  if not message.strip():
41
  return history, "", gr.update(visible=False), []
42
 
43
+ # Gradio 6: messages are dicts with role/content
44
  history = history or []
45
+ history.append({"role": "user", "content": message})
46
 
47
  if bus is None:
48
+ history.append({"role": "assistant", "content": "⚠️ Bus not connected. Running in demo mode."})
49
  return history, "", gr.update(visible=False), []
50
 
51
  try:
 
76
  except Exception:
77
  pass
78
 
79
+ # Build messages for LLM (use history)
80
+ llm_messages = []
81
  if context:
82
+ llm_messages.append({"role": "system", "content": f"Context:\n{context}"})
83
+ for h in history:
84
+ llm_messages.append({"role": h["role"], "content": h["content"]})
 
 
 
85
 
86
  params = {}
87
  if model and model != "auto":
 
90
  result = await bus.call(
91
  "llm.chat",
92
  (1, 0),
93
+ {"params": params, "input": {"messages": llm_messages}},
94
  )
95
  reply = (
96
  result.get("output", {}).get("message", {}).get("content", "No response")
97
  )
98
+ history.append({"role": "assistant", "content": reply})
99
 
100
  return history, "", gr.update(visible=bool(sources), value=sources), sources
101
 
102
  except Exception as exc:
103
+ history.append({"role": "assistant", "content": f"Error: {exc}"})
104
  return history, "", gr.update(visible=False), []
105
 
106
  send_btn.click(
hearthnet/ui/tabs/chat.py CHANGED
@@ -23,21 +23,25 @@ def build_chat_tab(bus=None):
23
 
24
  async def load_history(peer):
25
  if bus is None:
26
- return [["system", "Bus not connected"]]
27
  try:
28
  r = await bus.call(
29
  "chat.history", (1, 0), {"input": {"peer": peer or None}}
30
  )
31
  msgs = r.get("output", {}).get("messages", [])
32
- return [[m.get("from", "?"), m.get("body", "")] for m in msgs]
 
 
 
33
  except Exception as e:
34
- return [["error", str(e)]]
35
 
36
  async def send_msg(peer, msg, history):
37
  if not peer or not msg:
38
  return history, "", gr.update(visible=False)
 
39
  if bus is None:
40
- history = (history or []) + [[msg, "⚠️ Bus not connected"]]
41
  return history, "", gr.update(visible=False)
42
  try:
43
  r = await bus.call(
@@ -45,13 +49,14 @@ def build_chat_tab(bus=None):
45
  (1, 0),
46
  {"input": {"recipient": peer, "body": msg}},
47
  )
48
- history = (history or []) + [
49
- [msg, f"βœ“ sent ({r.get('output', {}).get('delivered', '?')})"]
 
 
50
  ]
51
  return history, "", gr.update(visible=True, value=r.get("output"))
52
  except Exception as e:
53
- return history, "", gr.update(visible=True, value={"error": str(e)})
54
-
55
  history_btn.click(load_history, inputs=peer_id, outputs=chat_out)
56
  send_btn.click(
57
  send_msg,
 
23
 
24
  async def load_history(peer):
25
  if bus is None:
26
+ return [{"role": "assistant", "content": "Bus not connected"}]
27
  try:
28
  r = await bus.call(
29
  "chat.history", (1, 0), {"input": {"peer": peer or None}}
30
  )
31
  msgs = r.get("output", {}).get("messages", [])
32
+ result = []
33
+ for m in msgs:
34
+ result.append({"role": "user", "content": f"[{m.get('from','?')}]: {m.get('body','')}" })
35
+ return result
36
  except Exception as e:
37
+ return [{"role": "assistant", "content": f"Error: {e}"}]
38
 
39
  async def send_msg(peer, msg, history):
40
  if not peer or not msg:
41
  return history, "", gr.update(visible=False)
42
+ history = history or []
43
  if bus is None:
44
+ history = history + [{"role": "user", "content": msg}, {"role": "assistant", "content": "⚠️ Bus not connected"}]
45
  return history, "", gr.update(visible=False)
46
  try:
47
  r = await bus.call(
 
49
  (1, 0),
50
  {"input": {"recipient": peer, "body": msg}},
51
  )
52
+ status = r.get("output", {}).get("delivered", "sent")
53
+ history = history + [
54
+ {"role": "user", "content": msg},
55
+ {"role": "assistant", "content": f"βœ“ delivered={status}"},
56
  ]
57
  return history, "", gr.update(visible=True, value=r.get("output"))
58
  except Exception as e:
59
+ history = history + [{"role": "user", "content": msg}, {"role": "assistant", "content": f"Error: {e}"}]
 
60
  history_btn.click(load_history, inputs=peer_id, outputs=chat_out)
61
  send_btn.click(
62
  send_msg,
hearthnet/ui/tabs/settings.py CHANGED
@@ -18,6 +18,11 @@ def build_settings_tab(config=None, meta: dict | None = None, bus=None):
18
 
19
  meta = meta or {}
20
 
 
 
 
 
 
21
  with gr.Column():
22
  gr.Markdown("### βš™οΈ Node & Settings")
23
 
@@ -44,24 +49,23 @@ def build_settings_tab(config=None, meta: dict | None = None, bus=None):
44
  if bus is None:
45
  return [{"node_id": "demo-node", "profile": "hearth", "capabilities": ["llm.chat"]}]
46
  try:
47
- snap = bus.topology_snapshot()
48
- result = []
49
- for p in snap.peers:
50
- result.append({
51
- "node_id": p.node_id,
52
- "display_name": p.display_name,
53
- "profile": p.profile,
54
- "source": p.source,
55
- "last_seen_s_ago": round(__import__('time').time() - p.last_seen, 1),
56
- })
57
- caps = []
58
- for e in snap.capabilities_remote:
59
- caps.append({
60
- "node_id": e.node_id[:20],
61
- "capability": f"{e.descriptor.name}@{e.descriptor.version[0]}.{e.descriptor.version[1]}",
62
- "health": f"{e.success_rate:.0%}",
63
- })
64
- return {"peers": result, "remote_capabilities": caps}
65
  except Exception as exc:
66
  return {"error": str(exc)}
67
 
 
18
 
19
  meta = meta or {}
20
 
21
+ # Enrich meta from live bus when available
22
+ if bus is not None:
23
+ meta.setdefault("node_id", getattr(bus, "node_id_full", "unknown"))
24
+ meta.setdefault("community_id", getattr(bus, "community_id", "unknown"))
25
+
26
  with gr.Column():
27
  gr.Markdown("### βš™οΈ Node & Settings")
28
 
 
49
  if bus is None:
50
  return [{"node_id": "demo-node", "profile": "hearth", "capabilities": ["llm.chat"]}]
51
  try:
52
+ # capabilities_remote are _entry_view dicts; get unique peer IDs
53
+ remote_entries = list(bus.registry.all_remote())
54
+ peer_caps: dict[str, list[str]] = {}
55
+ for e in remote_entries:
56
+ nid = e.node_id
57
+ peer_caps.setdefault(nid, []).append(
58
+ f"{e.descriptor.name}@{e.descriptor.version[0]}.{e.descriptor.version[1]}"
59
+ )
60
+ result = [
61
+ {"node_id": nid, "capabilities": caps, "capability_count": len(caps)}
62
+ for nid, caps in peer_caps.items()
63
+ ]
64
+ local_caps = [
65
+ f"{e.descriptor.name}@{e.descriptor.version[0]}.{e.descriptor.version[1]}"
66
+ for e in bus.registry.all_local()
67
+ ]
68
+ return {"this_node": bus.node_id_full, "peers": result, "local_capabilities": local_caps}
 
69
  except Exception as exc:
70
  return {"error": str(exc)}
71
 
scripts/demo_two_nodes.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Two-node HearthNet demo.
2
+
3
+ Launches two fully-wired HearthNet nodes in the same process using the
4
+ InMemoryNetwork transport. Both nodes:
5
+ - have demo services (LLM echo, RAG, Marketplace, Chat)
6
+ - discover each other (shared InMemoryTransport)
7
+ - start a Gradio UI on separate ports
8
+
9
+ Node A β†’ http://127.0.0.1:7861 (Alice)
10
+ Node B β†’ http://127.0.0.1:7862 (Bob)
11
+
12
+ Run:
13
+ python scripts/demo_two_nodes.py
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import threading
18
+ import time
19
+
20
+ from hearthnet.node import HearthNode, InMemoryNetwork
21
+ from hearthnet.ui.app import build_ui
22
+
23
+
24
+ def launch_node(
25
+ node: HearthNode,
26
+ port: int,
27
+ *,
28
+ share: bool = False,
29
+ ) -> None:
30
+ """Build and launch Gradio for a single node (blocking)."""
31
+ ui = build_ui(
32
+ bus=node.bus,
33
+ state_bus=node.state_bus,
34
+ display_name=node.display_name,
35
+ node_id=node.node_id,
36
+ community_id=node.community_id,
37
+ )
38
+ demo = ui.build()
39
+ print(f"[{node.display_name}] UI β†’ http://127.0.0.1:{port}/")
40
+ demo.launch(
41
+ server_name="0.0.0.0",
42
+ server_port=port,
43
+ share=share,
44
+ quiet=True,
45
+ )
46
+
47
+
48
+ def main() -> None:
49
+ net = InMemoryNetwork()
50
+
51
+ # Create two named nodes in the same community
52
+ alice = net.add_node("alice", "Alice", "ed25519:hearthnet-demo")
53
+ bob = net.add_node("bob", "Bob", "ed25519:hearthnet-demo")
54
+
55
+ # Install real (local) demo services on both
56
+ alice.install_demo_services(corpus="alice-knowledge")
57
+ bob.install_demo_services(corpus="bob-knowledge")
58
+
59
+ # Let them discover each other via in-memory transport
60
+ net.mesh_discover()
61
+
62
+ print("Peers registered:")
63
+ for n in [alice, bob]:
64
+ peers = [p.node_id for p in n.peers.all()]
65
+ caps = [e.descriptor.name for e in n.bus.registry.all_local()]
66
+ print(f" {n.node_id}: peers={peers}, local_caps={caps}")
67
+
68
+ # Launch both UIs β€” node B in a daemon thread, node A blocks main
69
+ t = threading.Thread(
70
+ target=launch_node, args=(bob, 7862), kwargs={"share": False}, daemon=True
71
+ )
72
+ t.start()
73
+ time.sleep(2) # give Bob time to bind
74
+
75
+ print("\nBoth nodes are running:")
76
+ print(" Alice (Node A): http://127.0.0.1:7861/")
77
+ print(" Bob (Node B): http://127.0.0.1:7862/")
78
+ print("\nIn the Chat tab on Alice, enter 'bob' as recipient to message Bob.")
79
+ print("In the Ask tab, type any question to see the LLM echo response.")
80
+
81
+ launch_node(alice, 7861) # blocks
82
+
83
+
84
+ if __name__ == "__main__":
85
+ main()
scripts/gen_screenshots.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Generate HearthNet UI screenshots.
2
+
3
+ Launches a two-node mesh, performs real interactions (LLM query, chat send,
4
+ peer list refresh, marketplace post, RAG ingest), then saves screenshots.
5
+
6
+ Usage: python scripts/gen_screenshots.py
7
+ Output: docs/screenshots/*.png
8
+ """
9
+ from __future__ import annotations
10
+
11
+ import socket
12
+ import threading
13
+ import time
14
+ import urllib.request
15
+ from pathlib import Path
16
+
17
+ OUT = Path("docs/screenshots")
18
+ OUT.mkdir(parents=True, exist_ok=True)
19
+
20
+
21
+ def _free_port() -> int:
22
+ s = socket.socket()
23
+ s.bind(("127.0.0.1", 0))
24
+ p = s.getsockname()[1]
25
+ s.close()
26
+ return p
27
+
28
+
29
+ def _wait_ready(port: int, timeout: float = 20.0) -> None:
30
+ deadline = time.time() + timeout
31
+ while time.time() < deadline:
32
+ try:
33
+ urllib.request.urlopen(f"http://127.0.0.1:{port}/", timeout=2)
34
+ return
35
+ except Exception:
36
+ time.sleep(0.4)
37
+ raise TimeoutError(f"port {port} not ready after {timeout}s")
38
+
39
+
40
+ def _launch_node(demo, port: int) -> None:
41
+ """Launch a pre-built Gradio Blocks on the given port."""
42
+ demo.launch(
43
+ server_name="127.0.0.1",
44
+ server_port=port,
45
+ prevent_thread_lock=True,
46
+ quiet=True,
47
+ )
48
+
49
+
50
+ def main() -> None:
51
+ from hearthnet.node import InMemoryNetwork
52
+
53
+ net = InMemoryNetwork()
54
+ alice = net.add_node("alice", "Alice", "ed25519:hearthnet-demo")
55
+ bob = net.add_node("bob", "Bob", "ed25519:hearthnet-demo")
56
+ alice.install_demo_services(corpus="alice-docs")
57
+ bob.install_demo_services(corpus="bob-docs")
58
+ net.mesh_discover()
59
+
60
+ port_a = _free_port()
61
+ port_b = _free_port()
62
+
63
+ from hearthnet.ui.app import build_ui
64
+
65
+ # Build UIs sequentially (Gradio's block context is not thread-safe)
66
+ def _build(node):
67
+ return build_ui(
68
+ bus=node.bus,
69
+ state_bus=node.state_bus,
70
+ display_name=node.display_name,
71
+ node_id=node.node_id,
72
+ community_id=node.community_id,
73
+ ).build()
74
+
75
+ demo_a = _build(alice)
76
+ demo_b = _build(bob)
77
+
78
+ threading.Thread(target=_launch_node, args=(demo_a, port_a), daemon=True).start()
79
+ threading.Thread(target=_launch_node, args=(demo_b, port_b), daemon=True).start()
80
+
81
+ _wait_ready(port_a)
82
+ _wait_ready(port_b)
83
+ time.sleep(1.5) # let JS hydrate
84
+
85
+ from playwright.sync_api import sync_playwright
86
+
87
+ with sync_playwright() as pw:
88
+ browser = pw.chromium.launch(headless=True)
89
+
90
+ def _goto(page, url="/"):
91
+ page.goto(url, wait_until="networkidle", timeout=30_000)
92
+
93
+ def _click_tab(page, name):
94
+ page.get_by_role("tab", name=name).click()
95
+ page.wait_for_load_state("networkidle", timeout=15_000)
96
+
97
+ # ── Alice ──────────────────────────────────────────────────────────
98
+ ctx_a = browser.new_context(
99
+ base_url=f"http://127.0.0.1:{port_a}",
100
+ viewport={"width": 1280, "height": 900},
101
+ )
102
+ page_a = ctx_a.new_page()
103
+ _goto(page_a)
104
+
105
+ # 1. Ask tab β€” send a message and capture response
106
+ page_a.screenshot(path=str(OUT / "01-alice-ask-empty.png"))
107
+ print(" 01-alice-ask-empty.png βœ“")
108
+
109
+ # Gradio renders textareas inside shadow DOM; use .first for the message box
110
+ textarea = page_a.locator("textarea").first
111
+ textarea.fill("What is HearthNet? Explain in two sentences.")
112
+ # Multi-line textarea: click Send button (Enter adds newline, not submit)
113
+ page_a.get_by_role("button", name="Send").first.click()
114
+ page_a.wait_for_timeout(4000)
115
+ page_a.screenshot(path=str(OUT / "02-alice-ask-response.png"))
116
+ print(" 02-alice-ask-response.png βœ“")
117
+
118
+ # 2. Chat tab β€” send a message to bob
119
+ _click_tab(page_a, "Chat")
120
+ # First textbox = recipient, second textbox = message
121
+ textboxes = page_a.get_by_role("textbox")
122
+ try:
123
+ textboxes.nth(0).fill("bob")
124
+ textboxes.nth(1).fill("Hey Bob, can you hear me?")
125
+ page_a.get_by_role("button", name="Send").click()
126
+ page_a.wait_for_timeout(1500)
127
+ except Exception as exc:
128
+ print(f" Chat fill failed: {exc}")
129
+ page_a.screenshot(path=str(OUT / "03-alice-chat.png"))
130
+ print(" 03-alice-chat.png βœ“")
131
+
132
+ # 3. Marketplace tab
133
+ _click_tab(page_a, "Marketplace")
134
+ page_a.screenshot(path=str(OUT / "04-alice-marketplace.png"))
135
+ print(" 04-alice-marketplace.png βœ“")
136
+
137
+ # 4. Files tab
138
+ _click_tab(page_a, "Files")
139
+ page_a.screenshot(path=str(OUT / "05-alice-files.png"))
140
+ print(" 05-alice-files.png βœ“")
141
+
142
+ # 5. Emergency tab
143
+ _click_tab(page_a, "Emergency")
144
+ page_a.screenshot(path=str(OUT / "06-alice-emergency.png"))
145
+ print(" 06-alice-emergency.png βœ“")
146
+
147
+ # 6. Settings tab β€” shows alice node ID and bob as peer
148
+ _click_tab(page_a, "Settings")
149
+ page_a.screenshot(path=str(OUT / "07-alice-settings.png"))
150
+ print(" 07-alice-settings.png βœ“")
151
+
152
+ # Click "Refresh Peers" to see bob in the list
153
+ try:
154
+ page_a.get_by_role("button", name="Refresh Peers").click()
155
+ page_a.wait_for_timeout(2000)
156
+ page_a.screenshot(path=str(OUT / "08-alice-settings-peers.png"))
157
+ print(" 08-alice-settings-peers.png βœ“")
158
+ except Exception as exc:
159
+ print(f" Peers refresh failed: {exc}")
160
+
161
+ ctx_a.close()
162
+
163
+ # ── Bob ────────────────────────────────────────────────────────────
164
+ ctx_b = browser.new_context(
165
+ base_url=f"http://127.0.0.1:{port_b}",
166
+ viewport={"width": 1280, "height": 900},
167
+ )
168
+ page_b = ctx_b.new_page()
169
+ _goto(page_b)
170
+ page_b.screenshot(path=str(OUT / "09-bob-ask-tab.png"))
171
+ print(" 09-bob-ask-tab.png βœ“")
172
+
173
+ # Bob Ask β€” ask a question
174
+ textarea_b = page_b.locator("textarea").first
175
+ textarea_b.fill("Hello from Bob! What can I do on HearthNet?")
176
+ page_b.get_by_role("button", name="Send").first.click()
177
+ page_b.wait_for_timeout(4000)
178
+ page_b.screenshot(path=str(OUT / "09b-bob-ask-response.png"))
179
+ print(" 09b-bob-ask-response.png βœ“")
180
+
181
+ # Bob settings β€” should show alice as peer
182
+ _click_tab(page_b, "Settings")
183
+ page_b.screenshot(path=str(OUT / "10-bob-settings.png"))
184
+ print(" 10-bob-settings.png βœ“")
185
+
186
+ # Refresh Bob's peer list β€” should show Alice
187
+ try:
188
+ page_b.get_by_role("button", name="Refresh Peers").click()
189
+ page_b.wait_for_timeout(2000)
190
+ page_b.screenshot(path=str(OUT / "10b-bob-settings-peers.png"))
191
+ print(" 10b-bob-settings-peers.png βœ“")
192
+ except Exception as exc:
193
+ print(f" Bob peers refresh failed: {exc}")
194
+
195
+ ctx_b.close()
196
+ browser.close()
197
+
198
+ print("\nScreenshots saved to docs/screenshots/:")
199
+ for f in sorted(OUT.glob("*.png")):
200
+ print(f" {f.name}")
201
+
202
+
203
+ if __name__ == "__main__":
204
+ main()