Skip to content

Take control over your live stream video by running it yourself. Streaming + chat out of the box.

fix(ap): fix metadata not being used for featured streams + fix live/offline handling

Gabe Kangas162211030834
diff --git a/models/federatedserver_test.go b/models/federatedserver_test.go
new file mode 100644
index 0000000000..4241b09c36
--- /dev/null
+++ b/models/federatedserver_test.go
@@ -0,0 +1,89 @@
+package models
+
+import (
+ "encoding/json"
+ "testing"
+ "time"
+)
+
+// TestFederatedServerJSONContract pins the JSON field names the API emits for
+// a federated server. The web consumes these names directly (see
+// web/hooks/useFederatedServers.tsx and web/tests/useFederatedServers.test.tsx),
+// so a rename here without a matching web change silently breaks the
+// featured-streams admin table and public listing. This test fails loudly if
+// the contract drifts -- including reverting to the legacy url/logo/thumbnail/
+// lastChecked names that previously broke the feature.
+func TestFederatedServerJSONContract(t *testing.T) {
+ name := "goodnight"
+ displayName := "Goodnight TV"
+ logoURL := "https://goodnight.example.com/logo.png"
+ streamTitle := "Late night coding"
+ streamDescription := "Chill coding vibes"
+ thumbnailURL := "https://goodnight.example.com/thumb.jpg"
+ summary := "Goodnight TV"
+ username := "goodnight"
+ now := time.Date(2026, 6, 16, 21, 55, 0, 0, time.UTC)
+
+ server := FederatedServer{
+ ID: 7,
+ IRI: "https://goodnight.example.com",
+ Name: &name,
+ DisplayName: &displayName,
+ Summary: &summary,
+ Username: &username,
+ LogoURL: &logoURL,
+ IsOnline: true,
+ StreamTitle: &streamTitle,
+ StreamDescription: &streamDescription,
+ Tags: []string{"coding", "chill"},
+ ThumbnailURL: &thumbnailURL,
+ LastSeenOnline: &now,
+ LastStatusUpdate: &now,
+ AddedAt: now,
+ FollowedAt: &now,
+ Pending: false,
+ FollowStatus: "accepted",
+ }
+
+ data, err := json.Marshal(server)
+ if err != nil {
+ t.Fatalf("failed to marshal FederatedServer: %v", err)
+ }
+
+ var fields map[string]json.RawMessage
+ if err := json.Unmarshal(data, &fields); err != nil {
+ t.Fatalf("failed to unmarshal FederatedServer JSON: %v", err)
+ }
+
+ // The web reads each of these keys by name.
+ required := []string{
+ "id",
+ "iri",
+ "name",
+ "displayName",
+ "logoUrl",
+ "isOnline",
+ "streamTitle",
+ "streamDescription",
+ "tags",
+ "thumbnailUrl",
+ "lastStatusUpdate",
+ "addedAt",
+ "followStatus",
+ }
+ for _, key := range required {
+ if _, ok := fields[key]; !ok {
+ t.Errorf("FederatedServer JSON is missing required field %q; the web depends on it", key)
+ }
+ }
+
+ // These are the legacy names the web mistakenly used before the contract
+ // was unified. They must never reappear -- their presence would mean the
+ // two sides have diverged again.
+ forbidden := []string{"url", "logo", "thumbnail", "lastChecked"}
+ for _, key := range forbidden {
+ if _, ok := fields[key]; ok {
+ t.Errorf("FederatedServer JSON contains unexpected legacy field %q", key)
+ }
+ }
+}
diff --git a/services/activitypub/activitypub.go b/services/activitypub/activitypub.go
index e74c0703d9..019f725946 100644
--- a/services/activitypub/activitypub.go
+++ b/services/activitypub/activitypub.go
@@ -206,6 +206,22 @@ func (s *Service) StopStreamPingTicker() {
s.outbox.StopStreamPingTicker()
}
+// SendStreamPing immediately emits a single Offer activity to followers. It is
+// called at go-live so peer Owncast servers update their featured-stream
+// directories right away instead of waiting up to a full ping interval for the
+// periodic ticker to fire.
+func (s *Service) SendStreamPing() error {
+ return s.outbox.SendStreamPing()
+}
+
+// SendStreamGoingOffline emits a Leave activity to followers when the stream
+// ends so peer Owncast servers drop this server from the live section of their
+// featured-stream directories immediately, rather than waiting for the
+// staleness sweep.
+func (s *Service) SendStreamGoingOffline() error {
+ return s.outbox.SendStreamGoingOffline()
+}
+
// outboundWorkerPoolSize sizes the outbound delivery pool from the
// current follower count: base workers + 1 per 100 followers, clamped.
// Prevents excessive resource usage on instances with many followers.
diff --git a/services/activitypub/inbox/leave.go b/services/activitypub/inbox/leave.go
index 26cebcba4d..30c361745f 100644
--- a/services/activitypub/inbox/leave.go
+++ b/services/activitypub/inbox/leave.go
@@ -2,10 +2,12 @@ package inbox
import (
"context"
+ "fmt"
"github.com/go-fed/activity/streams/vocab"
log "github.com/sirupsen/logrus"
+ "github.com/owncast/owncast/persistence/federatedserversrepository"
"github.com/owncast/owncast/services/activitypub/apmodels"
)
@@ -51,13 +53,38 @@ func (s *Service) handleLeaveInboxRequest(c context.Context, activity vocab.Acti
return nil
}
-// updateFederatedServerStatus updates the status and metadata for a federated server.
+// updateFederatedServerStatus marks the federated server identified by the
+// given actor IRI as offline. The Leave activity is how a peer announces its
+// stream has ended, so it is the mirror of the Offer (go-live) handler: it
+// flips the directory entry offline immediately rather than waiting for the
+// staleness sweep. Metadata is accepted for symmetry with the Offer handler
+// but an offline transition carries no stream fields to store.
func updateFederatedServerStatus(actorIRI string, metadata *apmodels.OwncastMetadata) error {
- // Log the status update. Metadata is accepted for symmetry with
- // Offer/Leave handling; the federated_servers row carries this
- // information via UpdateServerStatus when the next live ping comes
- // in, so we just acknowledge the offline transition here.
_ = metadata
- log.Infof("Updated federated server %s to offline status", actorIRI)
+
+ // Federated server records are keyed by the base server URL
+ // (scheme://host); the Leave's actor is the full actor IRI.
+ serverURL := serverURLFromActorIRI(actorIRI)
+ if serverURL == "" {
+ log.Debugf("Could not derive server URL from actor IRI %s, ignoring Leave", actorIRI)
+ return nil
+ }
+
+ repo := federatedserversrepository.Get()
+ if repo == nil {
+ // No repository wired up (e.g. in unit tests); nothing to update.
+ return nil
+ }
+
+ // Only act on servers we are actively following, matching the Offer path.
+ if !shouldProcessOfferFromServer(repo, serverURL) {
+ return nil
+ }
+
+ if err := repo.UpdateServerStatus(serverURL, false, nil); err != nil {
+ return fmt.Errorf("failed to mark federated server %s offline: %w", serverURL, err)
+ }
+
+ log.Debugf("Marked federated server %s offline from Leave activity", serverURL)
return nil
}
diff --git a/services/activitypub/outbox/ping.go b/services/activitypub/outbox/ping.go
index d28e1c13d6..c35e330557 100644
--- a/services/activitypub/outbox/ping.go
+++ b/services/activitypub/outbox/ping.go
@@ -4,6 +4,7 @@ import (
"net/url"
"github.com/go-fed/activity/streams"
+ "github.com/go-fed/activity/streams/vocab"
"github.com/pkg/errors"
log "github.com/sirupsen/logrus"
"github.com/teris-io/shortid"
@@ -11,23 +12,30 @@ import (
"github.com/owncast/owncast/services/activitypub/apmodels"
)
-// SendStreamPing sends an Offer activity to all followers indicating
-// the stream is still live. Used by the featured-streams flow so
-// remote Owncast servers can keep their mini-directory of live
-// streams fresh without polling.
-func (s *Service) SendStreamPing() error {
- if !s.configRepository.GetFederationEnabled() {
- return nil
- }
+// streamStatusActivity is satisfied by the ActivityStreams activity types used
+// to advertise stream status to followers: an Offer when going live and a
+// Leave when going offline. It captures just the setters the shared builder
+// needs so both can travel one code path.
+type streamStatusActivity interface {
+ vocab.Type
+ GetUnknownProperties() map[string]interface{}
+ SetActivityStreamsActor(vocab.ActivityStreamsActorProperty)
+ SetActivityStreamsObject(vocab.ActivityStreamsObjectProperty)
+ SetActivityStreamsTo(vocab.ActivityStreamsToProperty)
+ SetActivityStreamsCc(vocab.ActivityStreamsCcProperty)
+}
+// sendStreamStatusToFollowers stamps the given activity with this server's
+// identity, attaches its Owncast stream metadata (live or offline), addresses
+// it to all followers, and delivers it. logLabel is used only for log and
+// error messages. It is the shared implementation behind SendStreamPing
+// (Offer/live) and SendStreamGoingOffline (Leave/offline).
+func (s *Service) sendStreamStatusToFollowers(activity streamStatusActivity, isLive bool, logLabel string) error {
id := shortid.MustGenerate()
activityID := s.builder.MakeLocalIRIForResource(id)
localActor := s.builder.MakeLocalIRIForAccount(s.configRepository.GetDefaultFederationUsername())
serverURL := s.configRepository.GetServerURL()
- // Create the Offer activity.
- activity := streams.NewActivityStreamsOffer()
-
idProperty := streams.NewJSONLDIdProperty()
idProperty.Set(activityID)
activity.SetJSONLDId(idProperty)
@@ -36,20 +44,19 @@ func (s *Service) SendStreamPing() error {
actorProperty.AppendIRI(localActor)
activity.SetActivityStreamsActor(actorProperty)
- // The object of the Offer is our server URL (we're offering the
- // live stream).
+ // The object is our server URL: we're offering (or leaving) the live
+ // directory.
objectProperty := streams.NewActivityStreamsObjectProperty()
serverIRI, err := url.Parse(serverURL)
if err != nil {
- return errors.Wrap(err, "unable to parse server URL for Offer activity")
+ return errors.Wrapf(err, "unable to parse server URL for %s", logLabel)
}
objectProperty.AppendIRI(serverIRI)
activity.SetActivityStreamsObject(objectProperty)
// Attach Owncast metadata so receivers can populate their
- // federated_servers table from the ping alone.
- unknownProps := activity.GetUnknownProperties()
- apmodels.SetOwncastMetadata(unknownProps, s.configRepository, true)
+ // federated_servers table from this activity alone.
+ apmodels.SetOwncastMetadata(activity.GetUnknownProperties(), s.configRepository, isLive)
to, cc := s.getAddressingToFollowers()
activity.SetActivityStreamsTo(to)
@@ -57,8 +64,8 @@ func (s *Service) SendStreamPing() error {
b, err := apmodels.Serialize(activity)
if err != nil {
- log.Errorln("unable to serialize stream ping Offer activity", err)
- return errors.Wrap(err, "unable to serialize stream ping Offer activity")
+ log.Errorln("unable to serialize "+logLabel, err)
+ return errors.Wrapf(err, "unable to serialize %s", logLabel)
}
if err := s.SendToFollowers(b); err != nil {
@@ -69,6 +76,31 @@ func (s *Service) SendStreamPing() error {
return err
}
- log.Debugln("Sent stream ping Offer activity to all followers")
+ log.Debugln("Sent " + logLabel + " to all followers")
return nil
}
+
+// SendStreamPing sends an Offer activity to all followers indicating the
+// stream is live. Used by the featured-streams flow (at go-live and on a
+// timer) so remote Owncast servers can keep their mini-directory of live
+// streams fresh without polling.
+func (s *Service) SendStreamPing() error {
+ if !s.configRepository.GetFederationEnabled() {
+ return nil
+ }
+
+ return s.sendStreamStatusToFollowers(streams.NewActivityStreamsOffer(), true, "stream ping Offer activity")
+}
+
+// SendStreamGoingOffline sends a Leave activity to all followers indicating
+// the stream has ended. This is the offline counterpart to SendStreamPing:
+// it lets peer Owncast servers drop this server from the live section of
+// their featured-streams directory immediately, rather than waiting for the
+// staleness sweep to time the entry out.
+func (s *Service) SendStreamGoingOffline() error {
+ if !s.configRepository.GetFederationEnabled() {
+ return nil
+ }
+
+ return s.sendStreamStatusToFollowers(streams.NewActivityStreamsLeave(), false, "stream-offline Leave activity")
+}
diff --git a/services/stream/stream.go b/services/stream/stream.go
index 8baa537b0a..56f6c2713f 100644
--- a/services/stream/stream.go
+++ b/services/stream/stream.go
@@ -175,9 +175,14 @@ func (s *Service) setStreamAsConnected(rtmpOut *io.PipeReader) {
// Send delayed notification messages.
s.onlineTimerCancelFunc = s.startLiveStreamNotificationsTimer()
- // Start the periodic Offer ping that lets peer Owncast servers
- // refresh their featured-streams listing.
+ // Let peer Owncast servers refresh their featured-streams listing.
+ // Send one Offer immediately so a go-live propagates to followers
+ // without waiting for the first periodic tick, then start the ticker
+ // to keep the listing fresh for the duration of the stream.
if s.configRepository.GetFederationEnabled() {
+ if err := s.activitypub.SendStreamPing(); err != nil {
+ log.Errorf("unable to send immediate go-live stream ping: %v", err)
+ }
s.activitypub.StartStreamPingTicker()
}
}
@@ -197,8 +202,16 @@ func (s *Service) SetStreamAsDisconnected() {
s.broadcaster = nil
// Stop the federated stream-ping ticker so we don't keep advertising
- // that we are live after the stream has ended.
+ // that we are live after the stream has ended, then tell followers we've
+ // gone offline so they drop us from the live section of their
+ // featured-streams directory immediately instead of waiting for the
+ // staleness sweep.
s.activitypub.StopStreamPingTicker()
+ if s.configRepository.GetFederationEnabled() {
+ if err := s.activitypub.SendStreamGoingOffline(); err != nil {
+ log.Errorf("unable to send stream-offline Leave activity: %v", err)
+ }
+ }
offlineFilename := "offline-v2.ts"
diff --git a/test/automated/activitypub/Dockerfile b/test/automated/activitypub/Dockerfile
index 11d4d3acca..a4901dd38c 100644
--- a/test/automated/activitypub/Dockerfile
+++ b/test/automated/activitypub/Dockerfile
@@ -4,6 +4,7 @@ RUN apt-get update && apt-get install -y \
gcc make \
curl libcurl4-openssl-dev libssl-dev \
jq sqlite3 ffmpeg \
+ fonts-dejavu-core \
libnss3-tools \
lsof procps \
&& rm -rf /var/lib/apt/lists/*
diff --git a/test/automated/activitypub/test-featured-streams.sh b/test/automated/activitypub/test-featured-streams.sh
index 1be7ccff6a..c6c5bb4209 100755
--- a/test/automated/activitypub/test-featured-streams.sh
+++ b/test/automated/activitypub/test-featured-streams.sh
@@ -19,13 +19,26 @@
# 4. Verify the follow transitions to "accepted" once Instance 2 returns its
# ActivityPub Accept (regression guard: the Accept must be matched to the
# stored record).
-# 5. Verify the listing is readable on the PUBLIC (unauthenticated) endpoint.
-# 6. Verify the reverse direction (Instance 2 adds Instance 1) also works.
+# 5. Verify the accepted record is actually populated with the remote server's
+# name, display name and logo (regression guard: a green "accepted" with a
+# blank, image-less row is the broken state users hit).
+# 6. Verify the listing exposes the documented field names the web consumes
+# (regression guard: the API and web previously drifted onto different
+# field names and the feature shipped broken but green).
+# 7. Verify the listing is readable on the PUBLIC (unauthenticated) endpoint.
+# 8. Verify the reverse direction (Instance 2 adds Instance 1) also works.
+# 9. Stream a real test video into Instance 2 and verify its entry in
+# Instance 1's directory flips to live with the stream title, then stop the
+# stream and verify it flips back to offline promptly (the core of the
+# feature, both directions). Streams automatically under CI; prompts when
+# run interactively.
#
# Requirements:
# - Go, C compiler (for building Owncast)
# - Caddy, mkcert
# - curl, jq
+# - ffmpeg and a Sans font (for the live-status test stream; the Docker image
+# installs both, see run.sh)
set -e
@@ -53,6 +66,8 @@ SNAC_PORT="${SNAC_PORT:-9080}"
ADMIN_USER="admin"
ADMIN_PASS="abc123"
+# Default stream key for a fresh Owncast instance (config/defaults.go).
+STREAM_KEY="${STREAM_KEY:-abc123}"
CI="${CI:-false}"
# URLs (HTTPS via proxy)
@@ -66,6 +81,7 @@ PROXY_PID=""
OC1_PID=""
OC2_PID=""
OC_LAST_PID=""
+TEST_STREAM_PID=""
# Colors
RED='\033[0;31m'
@@ -79,9 +95,19 @@ log_warn() { echo -e "${YELLOW}[WARN]${NC} $1"; }
log_error() { echo -e "${RED}[ERROR]${NC} $1"; }
log_test() { echo -e "${CYAN}[TEST]${NC} $1"; }
+# shellcheck disable=SC2329 # invoked via trap, not called directly
cleanup() {
log_info "Cleaning up..."
+ # Stop any test stream first so ffmpeg releases the RTMP connection before
+ # the Owncast instances are torn down. Kill the ffmpeg child directly too,
+ # since the ocTestStream wrapper does not forward signals to it.
+ pkill -f "rtmp://127.0.0.1:${OWNCAST2_RTMP_PORT}/live/" 2>/dev/null || true
+ if [[ -n "${TEST_STREAM_PID}" ]] && kill -0 "${TEST_STREAM_PID}" 2>/dev/null; then
+ kill "${TEST_STREAM_PID}" 2>/dev/null || true
+ wait "${TEST_STREAM_PID}" 2>/dev/null || true
+ fi
+
for pid_var in PROXY_PID OC2_PID OC1_PID; do
local pid="${!pid_var}"
if [[ -n "${pid}" ]] && kill -0 "${pid}" 2>/dev/null; then
@@ -210,7 +236,8 @@ start_owncast_instance() {
"${OWNCAST_BIN}" \
-database "${db}" \
-webserverport "${web_port}" \
- -rtmpport "${rtmp_port}"
+ -rtmpport "${rtmp_port}" \
+ -enableVerboseLogging
) > "${log}" 2>&1 &
OC_LAST_PID=$!
log_info "Owncast '${label}' PID ${OC_LAST_PID} (log: ${log})"
@@ -314,6 +341,21 @@ server_follow_status() {
echo "$1" | jq -r --arg iri "$2" '.servers[]? | select(.iri == $iri) | .followStatus' 2>/dev/null
}
+# server_object JSON IRI -> prints the compact server object (or empty)
+server_object() {
+ echo "$1" | jq -c --arg iri "$2" '.servers[]? | select(.iri == $iri)' 2>/dev/null
+}
+
+# server_field JSON IRI FIELD -> prints the value of FIELD (or empty).
+# Note: we deliberately avoid `// empty` here because jq treats a literal
+# false as "absent", which would turn isOnline=false into an empty string and
+# make an offline server indistinguishable from a missing field. Map only
+# null/missing to empty, preserving false/true and string values.
+server_field() {
+ echo "$1" | jq -r --arg iri "$2" --arg field "$3" \
+ '.servers[]? | select(.iri == $iri) | .[$field] | if . == null then empty else . end' 2>/dev/null
+}
+
# wait_for_follow_status WEB_PORT IRI EXPECTED_STATUS TIMEOUT_SECONDS
wait_for_follow_status() {
local web_port=$1
@@ -385,32 +427,113 @@ test_follow_is_accepted() {
return 1
}
+test_metadata_is_populated() {
+ log_test "TEST 3: Remote server metadata (name/logo) is populated after accept"
+
+ # Once the Accept comes back, the follower resolves the remote actor and
+ # stores its username, display name and logo. If this step is skipped the
+ # directory entry is a blank row with no name and no image -- exactly the
+ # broken state users reported. A green "follow accepted" is not enough;
+ # the row has to actually carry the data the UI renders.
+ local json name displayName logoUrl
+ json=$(get_featured_servers "${OWNCAST_PORT}" admin)
+
+ name=$(server_field "${json}" "${OWNCAST2_URL}" name)
+ displayName=$(server_field "${json}" "${OWNCAST2_URL}" displayName)
+ logoUrl=$(server_field "${json}" "${OWNCAST2_URL}" logoUrl)
+
+ local failed=0
+ if [[ -z "${name}" ]]; then
+ log_error "TEST 3 FAILED: 'name' is empty; the Accept handler did not store the remote username"
+ failed=1
+ fi
+ if [[ -z "${displayName}" ]]; then
+ log_error "TEST 3 FAILED: 'displayName' is empty; the remote server's display name was not stored"
+ failed=1
+ fi
+ if [[ -z "${logoUrl}" ]]; then
+ log_error "TEST 3 FAILED: 'logoUrl' is empty; the featured stream would render with no image"
+ failed=1
+ fi
+
+ if [[ ${failed} -ne 0 ]]; then
+ log_error "Server record: $(server_object "${json}" "${OWNCAST2_URL}")"
+ return 1
+ fi
+
+ log_test "TEST 3 PASSED: name='${name}', displayName='${displayName}', logoUrl='${logoUrl}'"
+ return 0
+}
+
+test_listing_field_contract() {
+ log_test "TEST 4: Directory listing exposes the documented field contract"
+
+ # The web reads these field names verbatim (web/hooks/useFederatedServers.tsx).
+ # The whole feature shipped broken once because the API and the web had
+ # drifted onto different names, so guard the contract here: the documented
+ # names must be present and the legacy names must never come back.
+ local json server
+ json=$(get_featured_servers "${OWNCAST_PORT}" public)
+ server=$(server_object "${json}" "${OWNCAST2_URL}")
+
+ if [[ -z "${server}" ]]; then
+ log_error "TEST 4 FAILED: ${OWNCAST2_URL} not present in public listing"
+ log_error "Listing: ${json}"
+ return 1
+ fi
+
+ local failed=0 field
+ local required=(iri name displayName logoUrl isOnline addedAt followStatus)
+ for field in "${required[@]}"; do
+ if ! echo "${server}" | jq -e "has(\"${field}\")" > /dev/null 2>&1; then
+ log_error "TEST 4 FAILED: response is missing documented field '${field}'"
+ failed=1
+ fi
+ done
+
+ local forbidden=(url logo thumbnail lastChecked)
+ for field in "${forbidden[@]}"; do
+ if echo "${server}" | jq -e "has(\"${field}\")" > /dev/null 2>&1; then
+ log_error "TEST 4 FAILED: response contains legacy field '${field}' the web no longer reads"
+ failed=1
+ fi
+ done
+
+ if [[ ${failed} -ne 0 ]]; then
+ log_error "Server object: ${server}"
+ return 1
+ fi
+
+ log_test "TEST 4 PASSED: listing exposes the documented field contract"
+ return 0
+}
+
test_public_listing_is_readable() {
- log_test "TEST 3: Directory listing is readable without admin auth"
+ log_test "TEST 5: Directory listing is readable without admin auth"
# The public watch page fetches this endpoint on load; it must not be
# gated behind admin basic auth.
local code
code=$(curl -s -o /dev/null -w "%{http_code}" "http://localhost:${OWNCAST_PORT}/api/federation/servers")
if [[ "${code}" != "200" ]]; then
- log_error "TEST 3 FAILED: public listing returned HTTP ${code}, expected 200"
+ log_error "TEST 5 FAILED: public listing returned HTTP ${code}, expected 200"
return 1
fi
local json
json=$(get_featured_servers "${OWNCAST_PORT}" public)
if ! server_has_iri "${json}" "${OWNCAST2_URL}"; then
- log_error "TEST 3 FAILED: ${OWNCAST2_URL} not present in public listing"
+ log_error "TEST 5 FAILED: ${OWNCAST2_URL} not present in public listing"
log_error "Listing: ${json}"
return 1
fi
- log_test "TEST 3 PASSED: public listing returns the featured server"
+ log_test "TEST 5 PASSED: public listing returns the featured server"
return 0
}
test_reverse_direction() {
- log_test "TEST 4: Reverse direction (instance 2 adds instance 1)"
+ log_test "TEST 6: Reverse direction (instance 2 adds instance 1)"
local response success message
response=$(add_featured_server "${OWNCAST2_PORT}" "${OWNCAST_URL}")
@@ -419,23 +542,153 @@ test_reverse_direction() {
success=$(echo "${response}" | jq -r '.success // false' 2>/dev/null)
if [[ "${success}" != "true" ]]; then
message=$(echo "${response}" | jq -r '.message // ""' 2>/dev/null)
- log_error "TEST 4 FAILED: add request was not accepted: ${message}"
+ log_error "TEST 6 FAILED: add request was not accepted: ${message}"
return 1
fi
if wait_for_follow_status "${OWNCAST2_PORT}" "${OWNCAST_URL}" "accepted" 40; then
- log_test "TEST 4 PASSED: instance 2 followed and accepted instance 1"
+ log_test "TEST 6 PASSED: instance 2 followed and accepted instance 1"
return 0
fi
local json status
json=$(get_featured_servers "${OWNCAST2_PORT}" admin)
status=$(server_follow_status "${json}" "${OWNCAST_URL}")
- log_error "TEST 4 FAILED: follow status is '${status}', expected 'accepted'"
+ log_error "TEST 6 FAILED: follow status is '${status}', expected 'accepted'"
log_error "Listing: ${json}"
return 1
}
+# stop_test_stream stops the running test stream, if any.
+#
+# ocTestStream.sh runs ffmpeg in the foreground without forwarding signals or
+# trapping EXIT (for the internal test-pattern path), so killing the wrapper
+# alone orphans ffmpeg and the RTMP stream keeps running -- which would leave
+# the source server live and no Leave would ever be sent. Kill the ffmpeg
+# pushing to instance 2's RTMP endpoint directly as well.
+stop_test_stream() {
+ pkill -f "rtmp://127.0.0.1:${OWNCAST2_RTMP_PORT}/live/" 2>/dev/null || true
+ if [[ -n "${TEST_STREAM_PID}" ]] && kill -0 "${TEST_STREAM_PID}" 2>/dev/null; then
+ kill "${TEST_STREAM_PID}" 2>/dev/null || true
+ wait "${TEST_STREAM_PID}" 2>/dev/null || true
+ fi
+ TEST_STREAM_PID=""
+}
+
+test_live_status_flip() {
+ log_test "TEST 7: Featured stream flips to live when the remote goes online"
+
+ # This is the heart of the feature: a featured server must show as live,
+ # with its stream metadata, while it is actually streaming. Instance 1
+ # already follows instance 2 (TEST 2), so when instance 2 goes live it
+ # sends an immediate Offer ping that should flip instance 2's row in
+ # instance 1's directory to online.
+ #
+ # In CI we stream automatically; run interactively and we ask first so a
+ # developer can decline (or watch it happen).
+ if [[ "${CI}" != "true" ]]; then
+ echo ""
+ read -p "Start a test stream on instance 2 to verify live-status propagation? [Y/n] " -n 1 -r
+ echo ""
+ if [[ "${REPLY}" =~ ^[Nn]$ ]]; then
+ log_warn "TEST 7 SKIPPED: declined to start a test stream"
+ return 0
+ fi
+ fi
+
+ if [[ ! -x "${REPO_ROOT}/test/ocTestStream.sh" ]]; then
+ log_error "TEST 7 FAILED: ${REPO_ROOT}/test/ocTestStream.sh not found or not executable"
+ return 1
+ fi
+
+ # Give instance 2 a known stream title so we can assert it propagates with
+ # the live status, rather than just trusting the boolean flag.
+ local expected_title="Featured Streams Live Test"
+ local auth
+ auth=$(get_admin_auth)
+ curl -s -X POST "http://localhost:${OWNCAST2_PORT}/api/admin/config/streamtitle" \
+ -H "Authorization: Basic ${auth}" -H "Content-Type: application/json" \
+ -d "{\"value\": \"${expected_title}\"}" > /dev/null
+
+ log_info "Starting test stream into instance 2 (rtmp port ${OWNCAST2_RTMP_PORT})..."
+ "${REPO_ROOT}/test/ocTestStream.sh" "rtmp://127.0.0.1:${OWNCAST2_RTMP_PORT}/live/${STREAM_KEY}" \
+ > "${TEMP_DIR}/teststream.log" 2>&1 &
+ TEST_STREAM_PID=$!
+
+ # Wait for instance 1 to observe instance 2 as online. The Offer fires on
+ # RTMP connect, but allow generous time for ffmpeg startup and delivery.
+ local timeout=90 waited=0 online="" json
+ while [[ ${waited} -lt ${timeout} ]]; do
+ if ! kill -0 "${TEST_STREAM_PID}" 2>/dev/null; then
+ log_error "TEST 7 FAILED: test stream process exited early. ffmpeg log:"
+ cat "${TEMP_DIR}/teststream.log"
+ TEST_STREAM_PID=""
+ return 1
+ fi
+ json=$(get_featured_servers "${OWNCAST_PORT}" admin)
+ online=$(server_field "${json}" "${OWNCAST2_URL}" isOnline)
+ if [[ "${online}" == "true" ]]; then
+ break
+ fi
+ sleep 3
+ waited=$((waited + 3))
+ done
+
+ if [[ "${online}" != "true" ]]; then
+ log_error "TEST 7 FAILED: instance 2 never showed as online on instance 1 within ${timeout}s"
+ log_error "Server record: $(server_object "${json}" "${OWNCAST2_URL}")"
+ stop_test_stream
+ return 1
+ fi
+
+ # The Offer carries stream metadata; the title we set must have propagated.
+ local title
+ title=$(server_field "$(get_featured_servers "${OWNCAST_PORT}" admin)" "${OWNCAST2_URL}" streamTitle)
+ if [[ "${title}" != "${expected_title}" ]]; then
+ log_error "TEST 7 FAILED: streamTitle is '${title}', expected '${expected_title}'"
+ stop_test_stream
+ return 1
+ fi
+
+ log_info "Instance 2 is live on instance 1 with title '${title}'; stopping the stream..."
+ stop_test_stream
+
+ # Ending the stream makes instance 2 send a Leave activity; instance 1 must
+ # flip the entry back to offline promptly, well before the 20-minute
+ # staleness sweep would otherwise time it out. The latency floor here is
+ # how long instance 2 takes to detect the RTMP disconnect and transition
+ # itself offline, so allow generous headroom and report the measured time.
+ local offline_timeout=180 offline_waited=0
+ online="true"
+ while [[ ${offline_waited} -lt ${offline_timeout} ]]; do
+ json=$(get_featured_servers "${OWNCAST_PORT}" admin)
+ online=$(server_field "${json}" "${OWNCAST2_URL}" isOnline)
+ if [[ "${online}" == "false" ]]; then
+ break
+ fi
+ sleep 3
+ offline_waited=$((offline_waited + 3))
+ done
+
+ if [[ "${online}" != "false" ]]; then
+ log_error "TEST 7 FAILED: instance 2 still shows online on instance 1 ${offline_timeout}s after the stream stopped"
+ log_error "Server record: $(server_object "${json}" "${OWNCAST2_URL}")"
+
+ # Diagnostics: did instance 2 itself go offline, and did the Leave flow?
+ local oc2_self
+ oc2_self=$(curl -s "http://localhost:${OWNCAST2_PORT}/api/status" 2>/dev/null | jq -c '{online}' 2>/dev/null)
+ log_error "Instance 2 self-reported status: ${oc2_self:-<none>}"
+ log_error "--- instance 2 log (disconnect / leave / ping) ---"
+ grep -iE "disconnect|leave|offer|ping|offline|transcoder complet|federat" "${TEMP_DIR}/owncast2.log" 2>/dev/null | tail -25 >&2 || true
+ log_error "--- instance 1 log (inbox / leave) ---"
+ grep -iE "leave|offer|offline|federated server|inbox" "${TEMP_DIR}/owncast1.log" 2>/dev/null | tail -25 >&2 || true
+ return 1
+ fi
+
+ log_test "TEST 7 PASSED: went live with title '${title}', then back offline ~${offline_waited}s after the stream ended"
+ return 0
+}
+
# ==========================
# Results
# ==========================
@@ -514,10 +767,16 @@ main() {
echo ""
if test_follow_is_accepted; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
echo ""
+ if test_metadata_is_populated; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
+ echo ""
+ if test_listing_field_contract; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
+ echo ""
if test_public_listing_is_readable; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
echo ""
if test_reverse_direction; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
echo ""
+ if test_live_status_flip; then passed=$((passed + 1)); else failed=$((failed + 1)); fi
+ echo ""
print_results "${passed}" "${failed}"
diff --git a/web/components/admin/FederatedServers/FederatedServersTable.tsx b/web/components/admin/FederatedServers/FederatedServersTable.tsx
index 7d95e4afbf..d7137147a4 100644
--- a/web/components/admin/FederatedServers/FederatedServersTable.tsx
+++ b/web/components/admin/FederatedServers/FederatedServersTable.tsx
@@ -13,29 +13,35 @@ import { Localization } from '../../../types/localization';
import styles from './FederatedServersTable.module.scss';
export interface FederatedServerData {
- id: string;
- url: string;
- name: string;
+ id: number;
+ iri: string;
+ name?: string;
+ displayName?: string;
isOnline: boolean;
- lastChecked?: string;
+ lastStatusUpdate?: string;
addedAt: string;
}
export interface FederatedServersTableProps {
servers: FederatedServerData[];
loading?: boolean;
- onRemove: (id: string) => Promise<void>;
+ onRemove: (id: number) => Promise<void>;
}
+// Prefer the human-friendly display name, fall back to the federation
+// username so the column is never blank for an accepted server.
+const serverLabel = (server: FederatedServerData): string =>
+ server.displayName || server.name || '';
+
export const FederatedServersTable: FC<FederatedServersTableProps> = ({
servers,
loading = false,
onRemove,
}) => {
const { t } = useTranslation();
- const [removingId, setRemovingId] = useState<string | null>(null);
+ const [removingId, setRemovingId] = useState<number | null>(null);
- const handleRemove = async (id: string) => {
+ const handleRemove = async (id: number) => {
setRemovingId(id);
try {
await onRemove(id);
@@ -57,11 +63,11 @@ export const FederatedServersTable: FC<FederatedServersTableProps> = ({
),
dataIndex: 'name',
key: 'name',
- render: (text: string, record: FederatedServerData) => (
+ render: (_: string, record: FederatedServerData) => (
<Space>
- <span>{text}</span>
+ <span>{serverLabel(record)}</span>
<a
- href={record.url}
+ href={record.iri}
target="_blank"
rel="noopener noreferrer"
onClick={e => e.stopPropagation()}
@@ -75,8 +81,8 @@ export const FederatedServersTable: FC<FederatedServersTableProps> = ({
title: (
<Translation translationKey={Localization.Admin.FeaturedStreams.url} defaultText="URL" />
),
- dataIndex: 'url',
- key: 'url',
+ dataIndex: 'iri',
+ key: 'iri',
ellipsis: true,
},
{
@@ -114,8 +120,8 @@ export const FederatedServersTable: FC<FederatedServersTableProps> = ({
defaultText="Last Checked"
/>
),
- dataIndex: 'lastChecked',
- key: 'lastChecked',
+ dataIndex: 'lastStatusUpdate',
+ key: 'lastStatusUpdate',
render: (text: string) =>
text || (
<Translation
@@ -148,7 +154,7 @@ export const FederatedServersTable: FC<FederatedServersTableProps> = ({
<Translation
translationKey={Localization.Admin.FeaturedStreams.unfeatureConfirm}
defaultText="Unfeature {{name}}?"
- vars={{ name: record.name }}
+ vars={{ name: serverLabel(record) }}
/>
}
onConfirm={() => handleRemove(record.id)}
diff --git a/web/components/ui/StreamsTab/StreamsTab.stories.tsx b/web/components/ui/StreamsTab/StreamsTab.stories.tsx
index facfb48628..3720565508 100644
--- a/web/components/ui/StreamsTab/StreamsTab.stories.tsx
+++ b/web/components/ui/StreamsTab/StreamsTab.stories.tsx
@@ -19,64 +19,64 @@ const Template: StoryFn<StreamsTabProps> = args => <StreamsTab {...args} />;
const mockServers: FederatedServer[] = [
{
- id: '1',
+ id: 1,
name: 'Tech Talk Central',
- url: 'https://techtalk.example.com',
- logo: 'https://picsum.photos/seed/10/64/64',
+ iri: 'https://techtalk.example.com',
+ logoUrl: 'https://picsum.photos/seed/10/64/64',
isOnline: true,
streamTitle: 'Building Microservices with Go',
streamDescription: 'Learn how to build scalable microservices using Go and Docker.',
tags: ['technology', 'golang', 'microservices'],
- thumbnail: 'https://picsum.photos/seed/11/640/360',
+ thumbnailUrl: 'https://picsum.photos/seed/11/640/360',
},
{
- id: '2',
+ id: 2,
name: 'Gaming Paradise',
- url: 'https://gaming.example.com',
- logo: 'https://picsum.photos/seed/12/64/64',
+ iri: 'https://gaming.example.com',
+ logoUrl: 'https://picsum.photos/seed/12/64/64',
isOnline: true,
streamTitle: 'Speedrun Marathon Day 3',
streamDescription: 'Day 3 of our annual speedrun marathon featuring classic games.',
tags: ['gaming', 'speedrun', 'retro'],
- thumbnail: 'https://picsum.photos/seed/13/640/360',
+ thumbnailUrl: 'https://picsum.photos/seed/13/640/360',
},
{
- id: '3',
+ id: 3,
name: 'Music Studio Live',
- url: 'https://music.example.com',
- logo: 'https://picsum.photos/seed/14/64/64',
+ iri: 'https://music.example.com',
+ logoUrl: 'https://picsum.photos/seed/14/64/64',
isOnline: false,
tags: ['music', 'live', 'jazz'],
},
{
- id: '4',
+ id: 4,
name: 'Art & Design Hub',
- url: 'https://art.example.com',
- logo: 'https://picsum.photos/seed/15/64/64',
+ iri: 'https://art.example.com',
+ logoUrl: 'https://picsum.photos/seed/15/64/64',
isOnline: true,
streamTitle: 'Digital Painting Workshop',
streamDescription: 'Learn digital painting techniques using Procreate and Photoshop.',
tags: ['art', 'design', 'tutorial'],
- thumbnail: 'https://picsum.photos/seed/16/640/360',
+ thumbnailUrl: 'https://picsum.photos/seed/16/640/360',
},
{
- id: '5',
+ id: 5,
name: 'Cooking Corner',
- url: 'https://cooking.example.com',
- logo: 'https://picsum.photos/seed/17/64/64',
+ iri: 'https://cooking.example.com',
+ logoUrl: 'https://picsum.photos/seed/17/64/64',
isOnline: false,
tags: ['cooking', 'recipes'],
},
{
- id: '6',
+ id: 6,
name: 'Fitness & Wellness',
- url: 'https://fitness.example.com',
- logo: 'https://picsum.photos/seed/18/64/64',
+ iri: 'https://fitness.example.com',
+ logoUrl: 'https://picsum.photos/seed/18/64/64',
isOnline: true,
streamTitle: 'Morning Yoga Session',
streamDescription: 'Start your day with a relaxing 30-minute yoga flow.',
tags: ['fitness', 'yoga', 'wellness'],
- thumbnail: 'https://picsum.photos/seed/19/640/360',
+ thumbnailUrl: 'https://picsum.photos/seed/19/640/360',
},
];
@@ -97,7 +97,7 @@ AllOffline.args = {
isOnline: false,
streamTitle: undefined,
streamDescription: undefined,
- thumbnail: undefined,
+ thumbnailUrl: undefined,
})),
};
@@ -127,7 +127,7 @@ ManyServers.args = {
...mockServers,
...mockServers.map((server, index) => ({
...server,
- id: `duplicate-${index}`,
+ id: 1000 + index,
name: `${server.name} (2)`,
})),
],
diff --git a/web/components/ui/StreamsTab/StreamsTab.tsx b/web/components/ui/StreamsTab/StreamsTab.tsx
index 244b5c6966..719e6e7d91 100644
--- a/web/components/ui/StreamsTab/StreamsTab.tsx
+++ b/web/components/ui/StreamsTab/StreamsTab.tsx
@@ -6,17 +6,24 @@ import { Localization } from '../../../types/localization';
import styles from './StreamsTab.module.scss';
export interface FederatedServer {
- id: string;
- name: string;
- url: string;
- logo?: string;
+ id: number;
+ iri: string;
+ name?: string;
+ displayName?: string;
+ logoUrl?: string;
isOnline: boolean;
streamTitle?: string;
streamDescription?: string;
tags?: string[];
- thumbnail?: string;
+ thumbnailUrl?: string;
}
+// The human-facing label for a server: prefer the display name, fall back
+// to the federation username, then an empty string so we never render
+// "undefined".
+const serverDisplayName = (server: FederatedServer): string =>
+ server.displayName || server.name || '';
+
export interface StreamsTabProps {
servers?: FederatedServer[];
loading?: boolean;
@@ -85,7 +92,7 @@ export const StreamsTab: FC<StreamsTabProps> = ({ servers = [], loading = false,
if (a.isOnline !== b.isOnline) {
return a.isOnline ? -1 : 1;
}
- return a.name.localeCompare(b.name);
+ return serverDisplayName(a).localeCompare(serverDisplayName(b));
});
return (
@@ -94,13 +101,13 @@ export const StreamsTab: FC<StreamsTabProps> = ({ servers = [], loading = false,
{sortedServers.map(server => (
<Col key={server.id} xs={24} sm={12} md={8} lg={6} xl={6} xxl={4}>
<StreamCard
- serverName={server.name}
- serverUrl={server.url}
- serverLogo={server.logo}
+ serverName={serverDisplayName(server)}
+ serverUrl={server.iri}
+ serverLogo={server.logoUrl}
streamTitle={server.streamTitle}
streamDescription={server.streamDescription}
tags={server.tags}
- thumbnail={server.thumbnail}
+ thumbnail={server.thumbnailUrl}
isOnline={server.isOnline}
/>
</Col>
diff --git a/web/hooks/useFederatedServers.tsx b/web/hooks/useFederatedServers.tsx
index a385c72e9f..4659cd3341 100644
--- a/web/hooks/useFederatedServers.tsx
+++ b/web/hooks/useFederatedServers.tsx
@@ -3,17 +3,22 @@ import { message } from 'antd';
import { useTranslation } from 'next-export-i18n';
import { Localization } from '../types/localization';
+// FederatedServerResponse matches the OpenAPI FederatedServer model the
+// backend serializes verbatim. The web consumes these names directly so
+// there is a single, shared vocabulary for federated-server data rather
+// than a backend set and a separate frontend set.
export interface FederatedServerResponse {
- id: string;
- url: string;
- name: string;
- logo?: string;
+ id: number;
+ iri: string;
+ name?: string;
+ displayName?: string;
+ logoUrl?: string;
isOnline: boolean;
streamTitle?: string;
streamDescription?: string;
tags?: string[];
- thumbnail?: string;
- lastChecked?: string;
+ thumbnailUrl?: string;
+ lastStatusUpdate?: string;
addedAt: string;
}
@@ -23,7 +28,7 @@ export interface UseFederatedServersResult {
error: string | null;
refetch: () => void;
addServer: (url: string) => Promise<void>;
- removeServer: (id: string) => Promise<void>;
+ removeServer: (id: number) => Promise<void>;
}
interface APIErrorResponse {
@@ -100,7 +105,7 @@ export function useFederatedServers(isAdmin: boolean = false): UseFederatedServe
message.success(t(Localization.Admin.FeaturedStreams.streamFeaturedSuccess));
};
- const removeServer = async (id: string): Promise<void> => {
+ const removeServer = async (id: number): Promise<void> => {
const response = await fetch(`${API_REMOVE_FEDERATED_SERVER}/${id}`, {
method: 'DELETE',
credentials: 'include',
diff --git a/web/tests/FederatedServersTable.test.tsx b/web/tests/FederatedServersTable.test.tsx
index 39f5b4e932..c3ad07b5a1 100644
--- a/web/tests/FederatedServersTable.test.tsx
+++ b/web/tests/FederatedServersTable.test.tsx
@@ -29,16 +29,16 @@ jest.mock('antd', () => ({
describe('FederatedServersTable', () => {
const mockServers: FederatedServerData[] = [
{
- id: '1',
- url: 'https://server1.example.com',
+ id: 1,
+ iri: 'https://server1.example.com',
name: 'Server 1',
isOnline: true,
- lastChecked: '2024-01-01 12:00',
+ lastStatusUpdate: '2024-01-01 12:00',
addedAt: '2023-12-01',
},
{
- id: '2',
- url: 'https://server2.example.com',
+ id: 2,
+ iri: 'https://server2.example.com',
name: 'Server 2',
isOnline: false,
addedAt: '2023-12-02',
@@ -100,7 +100,7 @@ describe('FederatedServersTable', () => {
fireEvent.click(confirmButton);
await waitFor(() => {
- expect(mockOnRemove).toHaveBeenCalledWith('1');
+ expect(mockOnRemove).toHaveBeenCalledWith(1);
});
});
diff --git a/web/tests/StreamsTab.test.tsx b/web/tests/StreamsTab.test.tsx
index 18cf6d387d..2d66797a41 100644
--- a/web/tests/StreamsTab.test.tsx
+++ b/web/tests/StreamsTab.test.tsx
@@ -11,18 +11,18 @@ jest.mock('../components/ui/Translation/Translation', () => ({
describe('StreamsTab', () => {
const mockServers: FederatedServer[] = [
{
- id: '1',
+ id: 1,
name: 'Server 1',
- url: 'https://server1.example.com',
+ iri: 'https://server1.example.com',
isOnline: true,
streamTitle: 'Live Stream',
streamDescription: 'Description',
tags: ['gaming'],
},
{
- id: '2',
+ id: 2,
name: 'Server 2',
- url: 'https://server2.example.com',
+ iri: 'https://server2.example.com',
isOnline: false,
},
];
@@ -58,27 +58,27 @@ describe('StreamsTab', () => {
it('sorts servers with online servers first', () => {
const servers: FederatedServer[] = [
{
- id: '1',
+ id: 1,
name: 'Offline A',
- url: 'https://a.example.com',
+ iri: 'https://a.example.com',
isOnline: false,
},
{
- id: '2',
+ id: 2,
name: 'Online B',
- url: 'https://b.example.com',
+ iri: 'https://b.example.com',
isOnline: true,
},
{
- id: '3',
+ id: 3,
name: 'Offline C',
- url: 'https://c.example.com',
+ iri: 'https://c.example.com',
isOnline: false,
},
{
- id: '4',
+ id: 4,
name: 'Online A',
- url: 'https://d.example.com',
+ iri: 'https://d.example.com',
isOnline: true,
},
];
diff --git a/web/tests/useFederatedServers.test.tsx b/web/tests/useFederatedServers.test.tsx
new file mode 100644
index 0000000000..04120a963d
--- /dev/null
+++ b/web/tests/useFederatedServers.test.tsx
@@ -0,0 +1,137 @@
+import React from 'react';
+import { render, screen, waitFor } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import { useFederatedServers } from '../hooks/useFederatedServers';
+import { StreamsTab } from '../components/ui/StreamsTab/StreamsTab';
+import { FederatedServersTable } from '../components/admin/FederatedServers/FederatedServersTable';
+
+// next-export-i18n's useTranslation reads from the router; the components and
+// the hook both call it.
+jest.mock('next/router', () => ({
+ useRouter: () => ({
+ query: {},
+ pathname: '/',
+ asPath: '/',
+ push: jest.fn(),
+ replace: jest.fn(),
+ }),
+}));
+
+jest.mock('antd', () => ({
+ ...jest.requireActual('antd'),
+ message: { success: jest.fn(), error: jest.fn() },
+}));
+
+// Render the Translation component as its default text so assertions can match
+// on stable, language-independent strings.
+jest.mock('../components/ui/Translation/Translation', () => ({
+ Translation: ({ defaultText }: { defaultText: string }) => <span>{defaultText}</span>,
+}));
+
+// This payload deliberately uses the EXACT field names the Go backend
+// serializes for the OpenAPI FederatedServer model. The whole point of this
+// test is to fail if the web ever reads a different set of names than the API
+// actually returns -- which is precisely the bug that previously shipped (the
+// web read url/logo/thumbnail/lastChecked while the API sent
+// iri/logoUrl/thumbnailUrl/lastStatusUpdate).
+const API_SERVER = {
+ id: 7,
+ iri: 'https://goodnight.example.com',
+ name: 'goodnight', // federation username
+ displayName: 'Goodnight TV', // human-friendly name
+ logoUrl: 'https://goodnight.example.com/logo.png',
+ isOnline: true,
+ streamTitle: 'Late night coding',
+ streamDescription: 'Chill coding vibes',
+ tags: ['coding', 'chill'],
+ thumbnailUrl: 'https://goodnight.example.com/thumb.jpg',
+ lastSeenOnline: '2026-06-16T21:50:00Z',
+ lastStatusUpdate: '2026-06-16T21:55:00Z',
+ addedAt: '2026-06-16T21:48:50Z',
+ followedAt: '2026-06-16T21:48:50Z',
+ pending: false,
+ username: 'goodnight',
+ summary: 'Goodnight TV',
+ followStatus: 'accepted',
+};
+
+function mockFetchServers(server: object = API_SERVER) {
+ global.fetch = jest.fn().mockResolvedValue({
+ ok: true,
+ statusText: 'OK',
+ json: async () => ({ servers: [server] }),
+ }) as unknown as typeof fetch;
+}
+
+// Harnesses wire the real hook to the real components so the test exercises
+// the full path: API JSON shape -> useFederatedServers -> rendered component.
+const PublicHarness = () => {
+ const { servers, loading, error } = useFederatedServers();
+ return <StreamsTab servers={servers} loading={loading} error={error || undefined} />;
+};
+
+const AdminHarness = () => {
+ const { servers, loading, removeServer } = useFederatedServers(true);
+ return <FederatedServersTable servers={servers} loading={loading} onRemove={removeServer} />;
+};
+
+describe('useFederatedServers contract', () => {
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ it('requests the public federation listing endpoint', async () => {
+ mockFetchServers();
+ render(<PublicHarness />);
+ await waitFor(() => expect(global.fetch).toHaveBeenCalledWith('/api/federation/servers'));
+ });
+
+ describe('public StreamsTab rendering', () => {
+ it('renders the friendly display name, logo, thumbnail and live status from the API fields', async () => {
+ mockFetchServers();
+ const { container } = render(<PublicHarness />);
+
+ // displayName is preferred over the federation username.
+ expect(await screen.findByText('Goodnight TV')).toBeInTheDocument();
+ expect(screen.queryByText('goodnight')).not.toBeInTheDocument();
+
+ // logoUrl + thumbnailUrl must reach the rendered <img> elements.
+ expect(container.querySelector(`img[src="${API_SERVER.logoUrl}"]`)).toBeInTheDocument();
+ expect(container.querySelector(`img[src="${API_SERVER.thumbnailUrl}"]`)).toBeInTheDocument();
+
+ // isOnline drives the LIVE badge and reveals the stream title.
+ expect(screen.getByText('LIVE')).toBeInTheDocument();
+ expect(screen.getByText('Late night coding')).toBeInTheDocument();
+ });
+
+ it('falls back to the username when there is no display name', async () => {
+ mockFetchServers({ ...API_SERVER, displayName: undefined });
+ render(<PublicHarness />);
+ expect(await screen.findByText('goodnight')).toBeInTheDocument();
+ });
+ });
+
+ describe('admin FederatedServersTable rendering', () => {
+ it('renders the name, the iri as the URL, the external link and the status', async () => {
+ mockFetchServers();
+ const { container } = render(<AdminHarness />);
+
+ expect(await screen.findByText('Goodnight TV')).toBeInTheDocument();
+
+ // The iri populates both the URL column text and the external link href.
+ expect(screen.getByText(API_SERVER.iri)).toBeInTheDocument();
+ const link = container.querySelector('a[target="_blank"]');
+ expect(link).toHaveAttribute('href', API_SERVER.iri);
+
+ // isOnline -> "Online"; lastStatusUpdate -> the Last Checked column.
+ expect(screen.getByText('Online')).toBeInTheDocument();
+ expect(screen.getByText(API_SERVER.lastStatusUpdate)).toBeInTheDocument();
+ });
+
+ it('shows "Never" for last checked when the server has no status update', async () => {
+ mockFetchServers({ ...API_SERVER, isOnline: false, lastStatusUpdate: undefined });
+ render(<AdminHarness />);
+ expect(await screen.findByText('Never')).toBeInTheDocument();
+ });
+ });
+});