${avatarTemplate({
author: profile,
- clickAction:
- liveStatus?.state === "active" && !isCurrentUser
- ? "live"
- : "lightbox",
+ clickAction: liveStatus?.state === "active" ? "live" : "lightbox",
})}
${!isCurrentUser && !isLabeler && isAuthenticated && !isBlockedBy
? html` ${isFollowing
@@ -421,6 +453,9 @@ export function profileCardTemplate({
onClickBlock,
onClickAddToLists,
onClickReport,
+ onClickGoLive,
+ onClickEditLive,
+ liveStatus,
});
}}
>
diff --git a/src/js/utils.js b/src/js/utils.js
index 61537d45..a16f88aa 100644
--- a/src/js/utils.js
+++ b/src/js/utils.js
@@ -115,7 +115,7 @@ window.addEventListener("visibilitychange", () => {
}
});
-export function displayRelativeTime(timestamp) {
+export function formatRelativeTime(timestamp) {
// e.g. "2025-09-11T15:08:11.414Z" -> "7h"
const now = relativeTimeBase;
const then = new Date(timestamp);
@@ -231,6 +231,14 @@ export function formatFullDate(timestamp) {
});
}
+// E.g. 3:44 PM
+export function formatShortTime(timestamp) {
+ return new Date(timestamp).toLocaleTimeString(undefined, {
+ hour: "numeric",
+ minute: "2-digit",
+ });
+}
+
// E.g. September 29, 2025 at 3:44 PM
export function formatFullTimestamp(timestamp) {
const date = new Date(timestamp);
@@ -1200,3 +1208,35 @@ export function requireArg(method, name, value) {
throw new Error(`${method} requires a ${name}`);
}
}
+
+// E.g. "twitch.tv/foo" -> "https://twitch.tv/foo".
+// Returns null if the input clearly isn't an url
+export function normalizeUrl(input) {
+ const trimmed = (input ?? "").trim();
+ if (!trimmed) return null;
+ const withScheme = /^https?:\/\//i.test(trimmed)
+ ? trimmed
+ : `https://${trimmed}`;
+ let parsed;
+ try {
+ parsed = new URL(withScheme);
+ } catch {
+ return null;
+ }
+ const labels = parsed.hostname.split(".").filter(Boolean);
+ if (labels.length < 2) return null;
+ const tld = labels[labels.length - 1];
+ if (!/^[a-z]{2,}$/i.test(tld)) return null;
+ return parsed.href;
+}
+
+// e.g. "1 hour", "30 minutes", "1 hour 5 minutes"
+export function formatDuration(minutes) {
+ const total = Math.max(0, Math.round(minutes));
+ const hours = Math.floor(total / 60);
+ const mins = total % 60;
+ const parts = [];
+ if (hours > 0) parts.push(`${hours} ${hours === 1 ? "hour" : "hours"}`);
+ if (mins > 0) parts.push(`${mins} ${mins === 1 ? "minute" : "minutes"}`);
+ return parts.join(" ") || "0 minutes";
+}
diff --git a/src/js/views/chat.view.js b/src/js/views/chat.view.js
index 6b5645f4..7ab7cc4a 100644
--- a/src/js/views/chat.view.js
+++ b/src/js/views/chat.view.js
@@ -6,7 +6,7 @@ import {
} from "/js/router.js";
import { html, render } from "/js/lib/lit-html.js";
import { headerTemplate } from "/js/templates/header.template.js";
-import { displayRelativeTime } from "/js/utils.js";
+import { formatRelativeTime } from "/js/utils.js";
import {
getConvoPreviewText,
getDisplayName,
@@ -59,7 +59,7 @@ export default async function chatView({
);
const otherUser = groupDetails ? null : otherMembers[0];
const timeAgo = lastInteraction
- ? displayRelativeTime(getInteractionTimestamp(lastInteraction))
+ ? formatRelativeTime(getInteractionTimestamp(lastInteraction))
: "";
const isUnread = convo.unreadCount > 0;
return html`
diff --git a/src/js/views/chatDetail.view.js b/src/js/views/chatDetail.view.js
index 74ed6000..eec52014 100644
--- a/src/js/views/chatDetail.view.js
+++ b/src/js/views/chatDetail.view.js
@@ -38,6 +38,7 @@ import {
wait,
raf,
differenceInMinutes,
+ formatShortTime,
isMobileViewport,
canHover,
pinScrollPosition,
@@ -1032,14 +1033,6 @@ export default async function chatDetailView({
`;
}
- function formatTime(timestamp) {
- return new Date(timestamp).toLocaleTimeString([], {
- hour: "numeric",
- minute: "2-digit",
- hour12: true,
- });
- }
-
function systemMessageTemplate({ message, convo }) {
const memberDid = message.data?.member?.did;
const memberProfile = memberDid ? getMemberProfile(convo, memberDid) : null;
@@ -1116,7 +1109,7 @@ export default async function chatDetailView({
? "message-group-time-sent"
: "message-group-time-received"}"
>
- ${formatTime(group.lastSentAt)}
+ ${formatShortTime(group.lastSentAt)}
`;
@@ -1126,7 +1119,7 @@ export default async function chatDetailView({
const isToday = isSameDate(date, new Date());
return html`
@@ -336,7 +336,7 @@ export default async function notificationsView({
const { notifications } = notificationGroup;
const firstNotif = notifications[0];
const post = notificationGroup.subject;
- const timeAgo = displayRelativeTime(firstNotif.indexedAt);
+ const timeAgo = formatRelativeTime(firstNotif.indexedAt);
const isUnread = !firstNotif.isRead;
const profileLink = linkToProfile(post.author);
return notificationItemTemplate({
@@ -366,7 +366,7 @@ export default async function notificationsView({
function likeNotificationTemplate({ notificationGroup, isRepost = false }) {
const { notifications } = notificationGroup;
const firstNotif = notifications[0];
- const timeAgo = displayRelativeTime(firstNotif.indexedAt);
+ const timeAgo = formatRelativeTime(firstNotif.indexedAt);
const isUnread = !firstNotif.isRead;
// Get the liked post for preview
@@ -398,7 +398,7 @@ export default async function notificationsView({
function repostNotificationTemplate({ notificationGroup, isRepost = false }) {
const { notifications } = notificationGroup;
const firstNotif = notifications[0];
- const timeAgo = displayRelativeTime(firstNotif.indexedAt);
+ const timeAgo = formatRelativeTime(firstNotif.indexedAt);
const isUnread = !firstNotif.isRead;
// Get the reposted post for preview
@@ -451,7 +451,7 @@ export default async function notificationsView({
function feedgenLikeNotificationTemplate({ notificationGroup }) {
const { notifications } = notificationGroup;
const firstNotif = notifications[0];
- const timeAgo = displayRelativeTime(firstNotif.indexedAt);
+ const timeAgo = formatRelativeTime(firstNotif.indexedAt);
const isUnread = !firstNotif.isRead;
const subjectUri = notificationGroup.subject;
const { repo, rkey } = subjectUri ? parseUri(subjectUri) : {};
@@ -482,7 +482,7 @@ export default async function notificationsView({
function starterpackJoinedNotificationTemplate({ notificationGroup }) {
const { notifications } = notificationGroup;
const firstNotif = notifications[0];
- const timeAgo = displayRelativeTime(firstNotif.indexedAt);
+ const timeAgo = formatRelativeTime(firstNotif.indexedAt);
const isUnread = !firstNotif.isRead;
const subjectUri = notificationGroup.subject;
const { repo, rkey } = subjectUri ? parseUri(subjectUri) : {};
@@ -514,7 +514,7 @@ export default async function notificationsView({
function verifiedNotificationTemplate({ notificationGroup }) {
const { notifications } = notificationGroup;
const firstNotif = notifications[0];
- const timeAgo = displayRelativeTime(firstNotif.indexedAt);
+ const timeAgo = formatRelativeTime(firstNotif.indexedAt);
const isUnread = !firstNotif.isRead;
return html`
@@ -540,7 +540,7 @@ export default async function notificationsView({
function unverifiedNotificationTemplate({ notificationGroup }) {
const { notifications } = notificationGroup;
const firstNotif = notifications[0];
- const timeAgo = displayRelativeTime(firstNotif.indexedAt);
+ const timeAgo = formatRelativeTime(firstNotif.indexedAt);
const isUnread = !firstNotif.isRead;
const otherCount = notifications.length - 1;
@@ -568,7 +568,7 @@ export default async function notificationsView({
function contactMatchNotificationTemplate({ notificationGroup }) {
const { notifications } = notificationGroup;
const firstNotif = notifications[0];
- const timeAgo = displayRelativeTime(firstNotif.indexedAt);
+ const timeAgo = formatRelativeTime(firstNotif.indexedAt);
const isUnread = !firstNotif.isRead;
const displayName = getDisplayName(firstNotif.author);
const profileLink = linkToProfile(firstNotif.author);
diff --git a/src/js/views/profile.view.js b/src/js/views/profile.view.js
index f7db9f38..52172651 100644
--- a/src/js/views/profile.view.js
+++ b/src/js/views/profile.view.js
@@ -21,6 +21,8 @@ import { feedsFeedTemplate } from "/js/templates/feedsFeed.template.js";
import { listFeedTemplate } from "/js/templates/listFeed.template.js";
import "/js/components/edit-profile-dialog.js";
import "/js/components/add-to-lists-dialog.js";
+import "/js/components/go-live-dialog.js";
+import "/js/components/edit-live-dialog.js";
import { tryAgainButtonTemplate } from "/js/templates/tryAgainButton.template.js";
export default async function profileView({
@@ -70,6 +72,29 @@ export default async function profileView({
dialog.open();
}
+ function handleGoLive(profile) {
+ const liveStatus = dataLayer.derived.$actorLiveStatus.get(profile.did);
+ const dialog = document.createElement("go-live-dialog");
+ dialog.dataLayer = dataLayer;
+ // Prefill url from old status if present
+ if (liveStatus?.state === "inactive" && !liveStatus.isDisabled) {
+ dialog.initialUrl = liveStatus?.record?.embed?.external?.uri ?? "";
+ }
+ dialog.addEventListener("close", () => dialog.remove());
+ document.body.appendChild(dialog);
+ dialog.open();
+ }
+
+ function handleEditLive(profile) {
+ const liveStatus = dataLayer.derived.$actorLiveStatus.get(profile.did);
+ const dialog = document.createElement("edit-live-dialog");
+ dialog.dataLayer = dataLayer;
+ dialog.liveStatus = liveStatus;
+ dialog.addEventListener("close", () => dialog.remove());
+ document.body.appendChild(dialog);
+ dialog.open();
+ }
+
async function handleEditProfile(profile) {
const dialog = document.createElement("edit-profile-dialog");
dialog.addEventListener("profile-save", (event) =>
@@ -313,6 +338,8 @@ export default async function profileView({
profileInteractionHandler.handleReport(profile),
onClickAddToLists: (profile) => handleAddToLists(profile),
onClickEditProfile: () => handleEditProfile(profile),
+ onClickGoLive: () => handleGoLive(profile),
+ onClickEditLive: () => handleEditLive(profile),
liveStatus,
pluginService,
isFollowPending: dataLayer.derived.$isFollowPending.get(
@@ -444,7 +471,9 @@ export default async function profileView({
? dataLayer.derived.$labelerInfo.get(profile.did)
: null;
// If labeler, require labeler info to be loaded
- const isLoaded = profile && (isLabeler ? !!labelerInfo : true);
+ const isCurrentUserLoaded = !isAuthenticated ? true : !!currentUser;
+ const isLoaded =
+ profile && isCurrentUserLoaded && (isLabeler ? !!labelerInfo : true);
const activeTab = state.$activeTab.get();
render(
html`
@@ -549,17 +578,14 @@ export default async function profileView({
state.$activeTab.set("labeler-settings");
dataLayer.requests.loadLabelerInfo(profile.did);
}
+ const currentUserDid = isAuthenticated ? dataLayer.api.session.did : null;
+ const isCurrentUser = profile.did === currentUserDid;
if (!profile.viewer?.blocking && !profile.viewer?.blockedBy) {
- const isCurrentUser =
- profile.did === dataLayer.derived.$currentUser.get()?.did;
loadAuthorFeed({ reload: true });
preloadHiddenFeeds({ isCurrentUser, isLabeler });
}
// Load chat status
- if (
- isAuthenticated &&
- profile.did !== dataLayer.derived.$currentUser.get()?.did
- ) {
+ if (!isCurrentUser) {
dataLayer.requests.loadProfileChatStatus(profile.did);
}
}
diff --git a/tests/e2e/mockServer.js b/tests/e2e/mockServer.js
index a214e60b..0f2352a9 100644
--- a/tests/e2e/mockServer.js
+++ b/tests/e2e/mockServer.js
@@ -126,6 +126,13 @@ export class MockServer {
this.registerPushStatus = 200;
this.slingshotUnreachable = false;
this.pdsEndpoint = "http://localhost:8081";
+ // did -> { cid, value } for app.bsky.actor.status/self
+ this.statusRecords = new Map();
+ this.putStatusCalls = [];
+ this.deleteStatusCalls = [];
+ // Remaining InvalidSwap failures the next putStatusRecord calls will emit
+ this.invalidSwapRemaining = 0;
+ this.statusCounter = 0;
}
// Make slingshot fail to resolve identities, so the app falls back to
@@ -333,6 +340,20 @@ export class MockServer {
this.externalLinkCards.set(url, meta);
}
+ // Seeds a status record for the given did (default: current user).
+ setStatusRecord(
+ record,
+ { did = userProfile.did, cid = "bafyreiseedstatus" } = {},
+ ) {
+ this.statusRecords.set(did, { cid, value: record });
+ }
+
+ // Makes the next N putStatusRecord calls fail with InvalidSwap before
+ // succeeding. Consumed one-per-call.
+ simulateInvalidSwap({ times = 1 } = {}) {
+ this.invalidSwapRemaining = times;
+ }
+
addNotifications(notifications, { cursor } = {}) {
this.notifications.push(...notifications);
this.notificationCursor = cursor;
@@ -2426,6 +2447,27 @@ export class MockServer {
const collection = body?.collection;
const rkey = body?.rkey;
+ if (collection === "app.bsky.actor.status") {
+ const repo = body?.repo;
+ this.deleteStatusCalls.push(body);
+ if (!this.statusRecords.has(repo)) {
+ return route.fulfill({
+ status: 400,
+ contentType: "application/json",
+ body: JSON.stringify({
+ error: "RecordNotFound",
+ message: "Could not locate record",
+ }),
+ });
+ }
+ this.statusRecords.delete(repo);
+ return route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: "{}",
+ });
+ }
+
if (collection === "app.bsky.feed.like") {
const feedKey = `${userProfile.did}-likes`;
const likes = this.authorFeeds.get(feedKey) || [];
@@ -2826,6 +2868,29 @@ export class MockServer {
}),
});
}
+ if (collection === "app.bsky.actor.status" && rkey === "self") {
+ const repo = url.searchParams.get("repo");
+ const seeded = this.statusRecords.get(repo);
+ if (seeded) {
+ return route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ uri: `at://${repo}/${collection}/${rkey}`,
+ cid: seeded.cid,
+ value: seeded.value,
+ }),
+ });
+ }
+ return route.fulfill({
+ status: 400,
+ contentType: "application/json",
+ body: JSON.stringify({
+ error: "RecordNotFound",
+ message: `Could not locate record: at://${repo}/${collection}/${rkey}`,
+ }),
+ });
+ }
if (collection === "app.bsky.graph.list") {
const repo = url.searchParams.get("repo");
const listUri = `at://${repo}/${collection}/${rkey}`;
@@ -2935,6 +3000,33 @@ export class MockServer {
}),
});
}
+ if (collection === "app.bsky.actor.status") {
+ const repo = body?.repo;
+ const rkey = body?.rkey ?? "self";
+ this.putStatusCalls.push(body);
+ if (this.invalidSwapRemaining > 0) {
+ this.invalidSwapRemaining -= 1;
+ return route.fulfill({
+ status: 400,
+ contentType: "application/json",
+ body: JSON.stringify({
+ error: "InvalidSwap",
+ message: "Record swap CID does not match current CID",
+ }),
+ });
+ }
+ this.statusCounter += 1;
+ const cid = `bafyreistatus${this.statusCounter}`;
+ this.statusRecords.set(repo, { cid, value: body?.record });
+ return route.fulfill({
+ status: 200,
+ contentType: "application/json",
+ body: JSON.stringify({
+ uri: `at://${repo}/${collection}/${rkey}`,
+ cid,
+ }),
+ });
+ }
if (collection === "app.bsky.graph.list") {
const repo = body?.repo;
const rkey = body?.rkey;
diff --git a/tests/e2e/specs/flows/goLive.test.js b/tests/e2e/specs/flows/goLive.test.js
new file mode 100644
index 00000000..cec2938b
--- /dev/null
+++ b/tests/e2e/specs/flows/goLive.test.js
@@ -0,0 +1,159 @@
+import { test, expect } from "../../base.js";
+import { login } from "../../helpers.js";
+import { userProfile } from "../../testData.js";
+import { MockServer } from "../../mockServer.js";
+
+const STREAM_URL = "https://www.twitch.tv/streamer";
+
+async function openProfileMenu(page) {
+ const view = page.locator("#profile-view");
+ await expect(view.locator('[data-testid="profile-name"]')).toBeVisible({
+ timeout: 10000,
+ });
+ await view.locator(".ellipsis-button").click();
+ return page.locator(".profile-context-menu");
+}
+
+test.describe("Go Live flow", () => {
+ test("create → badge appears → edit → remove", async ({ page }) => {
+ const mockServer = new MockServer();
+ mockServer.addProfile({
+ ...userProfile,
+ followersCount: 5,
+ followsCount: 5,
+ postsCount: 3,
+ });
+ mockServer.setExternalLinkCard(STREAM_URL, {
+ title: "Cool Stream",
+ description: "Streaming live",
+ });
+ await mockServer.setup(page);
+ await login(page);
+ await page.goto(`/profile/${userProfile.did}`);
+
+ // 1. Menu shows "Go live" (off state) for the current user.
+ let menu = await openProfileMenu(page);
+ let goLiveItem = menu.locator(
+ '[data-testid="menu-action-profile-go-live"]',
+ );
+ await expect(goLiveItem).toHaveAttribute("data-teststate", "off");
+ await expect(goLiveItem).toContainText("Go live");
+ await goLiveItem.click();
+
+ // 2. Dialog opens; type URL; preview lands after debounce.
+ const dialog = page.locator('[data-testid="go-live-dialog"]');
+ await expect(dialog).toBeVisible();
+ const urlInput = dialog.locator('[data-testid="link-input"]');
+ await urlInput.fill(STREAM_URL);
+ await expect(dialog.locator('[data-testid="link-preview"]')).toBeVisible({
+ timeout: 5000,
+ });
+ await expect(dialog.locator('[data-testid="link-preview"]')).toContainText(
+ "Cool Stream",
+ );
+
+ // 3. Submit → toast → dialog closes → badge on the profile avatar.
+ await dialog.locator('[data-testid="go-live-submit"]').click();
+ await expect(dialog).not.toBeVisible();
+ await expect(page.locator('[data-testid="live-badge"]')).toBeVisible();
+ expect(mockServer.putStatusCalls).toHaveLength(1);
+ expect(mockServer.putStatusCalls[0].record.embed.external.uri).toBe(
+ STREAM_URL,
+ );
+ const originalCreatedAt = mockServer.putStatusCalls[0].record.createdAt;
+
+ // 4. Reopen menu → label flips to "Edit live status".
+ menu = await openProfileMenu(page);
+ goLiveItem = menu.locator('[data-testid="menu-action-profile-go-live"]');
+ await expect(goLiveItem).toHaveAttribute("data-teststate", "live");
+ await expect(goLiveItem).toContainText("Edit live status");
+ await goLiveItem.click();
+
+ // 5. Edit dialog opens with URL prefilled; change URL and Save.
+ const editDialog = page.locator('[data-testid="edit-live-dialog"]');
+ await expect(editDialog).toBeVisible();
+ const editInput = editDialog.locator('[data-testid="link-input"]');
+ await expect(editInput).toHaveValue(STREAM_URL);
+ const NEW_STREAM_URL = "https://www.twitch.tv/streamer-updated";
+ mockServer.setExternalLinkCard(NEW_STREAM_URL, {
+ title: "Updated Stream",
+ description: "",
+ });
+ await editInput.fill(NEW_STREAM_URL);
+ // Wait for debounce + preview
+ await expect(
+ editDialog.locator('[data-testid="link-preview"]'),
+ ).toContainText("Updated Stream", { timeout: 5000 });
+ await editDialog.locator('[data-testid="edit-live-save"]').click();
+ await expect(editDialog).not.toBeVisible();
+ expect(mockServer.putStatusCalls).toHaveLength(2);
+ // createdAt is threaded through unchanged
+ expect(mockServer.putStatusCalls[1].record.createdAt).toBe(
+ originalCreatedAt,
+ );
+ expect(mockServer.putStatusCalls[1].record.embed.external.uri).toBe(
+ NEW_STREAM_URL,
+ );
+
+ // 6. Reopen menu → still live → remove.
+ menu = await openProfileMenu(page);
+ await menu.locator('[data-testid="menu-action-profile-go-live"]').click();
+ await expect(
+ page.locator('[data-testid="edit-live-dialog"]'),
+ ).toBeVisible();
+ await page.locator('[data-testid="edit-live-remove"]').click();
+
+ // Confirm modal
+ await page.locator('[data-testid="modal-confirm-button"]').click();
+ await expect(
+ page.locator('[data-testid="edit-live-dialog"]'),
+ ).not.toBeVisible();
+ expect(mockServer.deleteStatusCalls).toHaveLength(1);
+
+ // 7. Badge gone, menu back to "Go live".
+ await expect(page.locator('[data-testid="live-badge"]')).toHaveCount(0);
+ menu = await openProfileMenu(page);
+ await expect(
+ menu.locator('[data-testid="menu-action-profile-go-live"]'),
+ ).toHaveAttribute("data-teststate", "off");
+ });
+
+ test("retries on InvalidSwap and still succeeds on a single submit", async ({
+ page,
+ }) => {
+ const mockServer = new MockServer();
+ mockServer.addProfile({ ...userProfile });
+ mockServer.setExternalLinkCard(STREAM_URL, {
+ title: "Cool Stream",
+ description: "",
+ });
+ // Prior status exists on the PDS, first putStatusRecord will race and
+ // fail once with InvalidSwap; the CAS loop then re-reads and succeeds.
+ mockServer.setStatusRecord(
+ {
+ $type: "app.bsky.actor.status",
+ status: "app.bsky.actor.status#live",
+ createdAt: "2025-01-01T00:00:00.000Z",
+ durationMinutes: 60,
+ },
+ { cid: "bafyreiseedstatus" },
+ );
+ mockServer.simulateInvalidSwap({ times: 1 });
+ await mockServer.setup(page);
+ await login(page);
+ await page.goto(`/profile/${userProfile.did}`);
+
+ const menu = await openProfileMenu(page);
+ await menu.locator('[data-testid="menu-action-profile-go-live"]').click();
+ const dialog = page.locator('[data-testid="go-live-dialog"]');
+ await expect(dialog).toBeVisible();
+ await dialog.locator('[data-testid="link-input"]').fill(STREAM_URL);
+ await expect(dialog.locator('[data-testid="link-preview"]')).toBeVisible({
+ timeout: 5000,
+ });
+ await dialog.locator('[data-testid="go-live-submit"]').click();
+ await expect(dialog).not.toBeVisible();
+ // Two put attempts: the InvalidSwap failure and the successful retry.
+ expect(mockServer.putStatusCalls).toHaveLength(2);
+ });
+});
diff --git a/tests/e2e/specs/views/profile.view.test.js b/tests/e2e/specs/views/profile.view.test.js
index 0fd7d223..bd37c256 100644
--- a/tests/e2e/specs/views/profile.view.test.js
+++ b/tests/e2e/specs/views/profile.view.test.js
@@ -887,9 +887,15 @@ test.describe("Profile view", () => {
await view.locator(".ellipsis-button").click();
const menu = page.locator(".profile-context-menu");
- await expect(menu.locator("context-menu-item")).toHaveCount(3, {
+ await expect(menu.locator("context-menu-item")).toHaveCount(5, {
timeout: 5000,
});
+ await expect(
+ menu.locator('[data-testid="menu-action-profile-go-live"]'),
+ ).toBeVisible();
+ await expect(
+ menu.locator('[data-testid="menu-action-profile-add-to-lists"]'),
+ ).toBeVisible();
await expect(
menu.locator('[data-testid="menu-action-profile-search-posts"]'),
).toBeVisible();
diff --git a/tests/unit/specs/components/app-icon.test.js b/tests/unit/specs/components/app-icon.test.js
index d62604ca..09f507bf 100644
--- a/tests/unit/specs/components/app-icon.test.js
+++ b/tests/unit/specs/components/app-icon.test.js
@@ -14,7 +14,7 @@ describe("app-icon", () => {
const use = element.querySelector("use");
assert(use !== null);
- assert.deepEqual(use.getAttribute("href"), "/img/icons.svg#bell");
+ assert.deepEqual(use.getAttribute("href"), "#bell");
});
it("renders nothing when icon is absent", () => {
@@ -27,15 +27,9 @@ describe("app-icon", () => {
const element = document.createElement("app-icon");
element.setAttribute("icon", "bus");
document.body.appendChild(element);
- assert.deepEqual(
- element.querySelector("use").getAttribute("href"),
- "/img/icons.svg#bus",
- );
+ assert.deepEqual(element.querySelector("use").getAttribute("href"), "#bus");
element.setAttribute("icon", "car");
- assert.deepEqual(
- element.querySelector("use").getAttribute("href"),
- "/img/icons.svg#car",
- );
+ assert.deepEqual(element.querySelector("use").getAttribute("href"), "#car");
});
});
diff --git a/tests/unit/specs/components/live-link-form.test.js b/tests/unit/specs/components/live-link-form.test.js
new file mode 100644
index 00000000..a34aaf3d
--- /dev/null
+++ b/tests/unit/specs/components/live-link-form.test.js
@@ -0,0 +1,30 @@
+import { describe, it, beforeEach, afterEach, mock } from "node:test";
+import assert from "node:assert/strict";
+import "/js/components/live-link-form.js";
+
+describe("live-link-form", () => {
+ beforeEach(() => {
+ document.body.innerHTML = "";
+ mock.timers.enable({ apis: ["setTimeout"] });
+ });
+
+ afterEach(() => {
+ document.body.innerHTML = "";
+ mock.timers.reset();
+ });
+
+ it("clears the debounce timer on disconnect so _loadLinkMeta never runs", () => {
+ const element = document.createElement("live-link-form");
+ document.body.appendChild(element);
+ const loadSpy = mock.method(element, "_loadLinkMeta", async () => {});
+ // Type a URL — arms the 500ms debounce
+ element._handleInput({
+ target: { value: "https://www.twitch.tv/streamer" },
+ });
+ assert.notEqual(element._debounceTimer, null);
+ // Remove from document before debounce fires
+ element.remove();
+ mock.timers.tick(1000);
+ assert.equal(loadSpy.mock.calls.length, 0);
+ });
+});
diff --git a/tests/unit/specs/components/profile-hover-card.test.js b/tests/unit/specs/components/profile-hover-card.test.js
index 6076ef6b..01a270d0 100644
--- a/tests/unit/specs/components/profile-hover-card.test.js
+++ b/tests/unit/specs/components/profile-hover-card.test.js
@@ -31,16 +31,21 @@ function makeSetup({
} = {}) {
const dataLayer = makeTestDataLayer();
if (detailedProfile) {
- dataLayer.dataStore.$detailedProfiles.set(
- detailedProfile.did,
- detailedProfile,
- );
+ // Route through setDetailedProfile so `status` is extracted into
+ // $profileStatuses like production ingestion does.
+ dataLayer.dataStore.setDetailedProfile(detailedProfile);
}
if (basicProfile) {
- dataLayer.dataStore.$profiles.set(basicProfile.did, basicProfile);
+ dataLayer.dataStore.setProfiles([basicProfile]);
}
if (currentUser) {
dataLayer.dataStore.$currentUser.set(currentUser);
+ if (currentUser.status !== undefined) {
+ dataLayer.dataStore.$profileStatuses.set(
+ currentUser.did,
+ currentUser.status,
+ );
+ }
}
const followCalls = [];
const interactionHandlers = {
diff --git a/tests/unit/specs/dataLayer/liveStatus.test.js b/tests/unit/specs/dataLayer/liveStatus.test.js
index bbae85c7..b79299fc 100644
--- a/tests/unit/specs/dataLayer/liveStatus.test.js
+++ b/tests/unit/specs/dataLayer/liveStatus.test.js
@@ -9,6 +9,9 @@ import { Signal } from "/js/signals.js";
import { HiddenFeedItemsStore } from "/js/dataLayer/hiddenFeedItemsStore.js";
import { DraftMediaStore } from "/js/drafts.js";
import { isAllowedLiveHost, isStatusValid } from "/js/dataHelpers.js";
+import { normalizeUrl, formatDuration } from "/js/utils.js";
+import { ApiError } from "/js/api.js";
+import { Mutations } from "/js/dataLayer/mutations.js";
import {
createLiveStatusView,
createPost,
@@ -292,7 +295,10 @@ describe("live status", () => {
it("re-arms for the new deadline when a rewrite extends the expiry", () => {
const { derived, dataStore } = makeDerived();
- addLiveProfile(dataStore, createLiveStatusView({ did }));
+ addLiveProfile(
+ dataStore,
+ createLiveStatusView({ did, expiresAt: futureExpiry() }),
+ );
assert.equal(derived.$actorLiveStatus.get(did).state, "active");
// A later write extends the expiry to 14:00; the next judgment re-arms
@@ -328,4 +334,261 @@ describe("live status", () => {
);
});
});
+
+ describe("normalizeUrl", () => {
+ it("prepends https:// to bare hosts and normalizes", () => {
+ assert.equal(normalizeUrl("twitch.tv/foo"), "https://twitch.tv/foo");
+ assert.equal(
+ normalizeUrl(" https://www.youtube.com/watch "),
+ "https://www.youtube.com/watch",
+ );
+ });
+ it("rejects strings without a valid TLD", () => {
+ assert.equal(normalizeUrl("nope"), null);
+ assert.equal(normalizeUrl("localhost/foo"), null);
+ assert.equal(normalizeUrl(""), null);
+ assert.equal(normalizeUrl(null), null);
+ });
+ });
+
+ describe("formatDuration", () => {
+ it("formats hours and minutes", () => {
+ assert.equal(formatDuration(5), "5 minutes");
+ assert.equal(formatDuration(60), "1 hour");
+ assert.equal(formatDuration(65), "1 hour 5 minutes");
+ assert.equal(formatDuration(120), "2 hours");
+ assert.equal(formatDuration(0), "0 minutes");
+ });
+ });
+
+ describe("mutations.setLiveStatus / clearLiveStatus", () => {
+ // Matches the placeholder linkMeta shape the dialog always passes,
+ // even on cardyb failure (title falls back to the URL).
+ function placeholderLinkMeta(url) {
+ return { url, title: url, description: "", image: null };
+ }
+
+ function makeApi(overrides = {}) {
+ const api = {
+ getStatusRecord: mock.fn(async () => {
+ const err = new ApiError({
+ status: 400,
+ statusText: "Bad Request",
+ data: { error: "RecordNotFound" },
+ headers: {},
+ url: "",
+ });
+ throw err;
+ }),
+ putStatusRecord: mock.fn(async (record) => ({
+ uri: "at://did:plc:live1/app.bsky.actor.status/self",
+ cid: "bafyputcid",
+ value: record,
+ })),
+ deleteStatusRecord: mock.fn(async () => ({})),
+ uploadBlob: mock.fn(async () => ({
+ mimeType: "image/jpeg",
+ ref: { $link: "bafthumbcid" },
+ size: 123,
+ })),
+ ...overrides,
+ };
+ return api;
+ }
+
+ function makeSetup(api = makeApi()) {
+ const dataStore = new DataStore(createSessionState(null));
+ dataStore.$currentUser.set({
+ did: "did:plc:live1",
+ handle: "live1.test",
+ });
+ const patchStore = new PatchStore();
+ const preferencesProvider = {
+ requirePreferences: () => Preferences.createLoggedOutPreferences(),
+ $preferences: new Signal.State(
+ Preferences.createLoggedOutPreferences(),
+ ),
+ };
+ const mutations = new Mutations(
+ api,
+ dataStore,
+ patchStore,
+ preferencesProvider,
+ { resolveHandle: async () => null },
+ new DraftMediaStore("test-media"),
+ );
+ return { mutations, dataStore, patchStore, api };
+ }
+
+ it("publishes a status, writes it to the current user, and clears patches", async () => {
+ const { mutations, dataStore, patchStore, api } = makeSetup();
+ await mutations.setLiveStatus({
+ durationMinutes: 60,
+ linkMeta: {
+ url: "https://www.twitch.tv/streamer",
+ title: "Cool Stream",
+ description: "",
+ image: null,
+ },
+ });
+ assert.equal(api.putStatusRecord.mock.calls.length, 1);
+ const [record, swapCid] = api.putStatusRecord.mock.calls[0].arguments;
+ assert.equal(record.status, "app.bsky.actor.status#live");
+ assert.equal(record.durationMinutes, 60);
+ assert.equal(record.embed.external.uri, "https://www.twitch.tv/streamer");
+ assert.equal(swapCid, null);
+ const status = dataStore.$profileStatuses.get("did:plc:live1");
+ assert.equal(status.status, "app.bsky.actor.status#live");
+ assert.equal(status.embed.external.uri, "https://www.twitch.tv/streamer");
+ assert.equal(status.cid, "bafyputcid");
+ // No profile-patch dance any more — $profileStatuses is written directly.
+ assert.equal(
+ patchStore.$profilePatches.get("did:plc:live1") ?? null,
+ null,
+ );
+ });
+
+ it("preserves createdAt on edit and threads durationMinutes through", async () => {
+ const { mutations, api } = makeSetup();
+ const createdAt = "2025-05-01T12:00:00.000Z";
+ await mutations.setLiveStatus({
+ durationMinutes: 30,
+ linkMeta: placeholderLinkMeta("https://www.twitch.tv/updated"),
+ createdAt,
+ });
+ const record = api.putStatusRecord.mock.calls[0].arguments[0];
+ assert.equal(record.createdAt, createdAt);
+ assert.equal(record.durationMinutes, 30);
+ });
+
+ it("retries on InvalidSwap and eventually succeeds", async () => {
+ let attempts = 0;
+ const api = makeApi({
+ putStatusRecord: mock.fn(async (record) => {
+ attempts += 1;
+ if (attempts < 3) {
+ throw new ApiError({
+ status: 400,
+ statusText: "Bad Request",
+ data: { error: "InvalidSwap" },
+ headers: {},
+ url: "",
+ });
+ }
+ return { uri: "at://x", cid: "cid3", value: record };
+ }),
+ });
+ const { mutations } = makeSetup(api);
+ await mutations.setLiveStatus({
+ durationMinutes: 60,
+ linkMeta: placeholderLinkMeta("https://www.twitch.tv/a"),
+ });
+ assert.equal(attempts, 3);
+ assert.equal(api.getStatusRecord.mock.calls.length, 3);
+ });
+
+ it("swallows thumb upload failures but still publishes", async () => {
+ const api = makeApi({
+ uploadBlob: mock.fn(async () => {
+ throw new Error("upload failed");
+ }),
+ });
+ const originalFetch = globalThis.fetch;
+ globalThis.fetch = async () => ({
+ blob: async () => new Blob(["x"], { type: "image/png" }),
+ });
+ try {
+ const { mutations } = makeSetup(api);
+ await mutations.setLiveStatus({
+ durationMinutes: 60,
+ linkMeta: {
+ url: "https://www.twitch.tv/a",
+ title: "t",
+ description: "",
+ image: "https://example.com/img.jpg",
+ },
+ });
+ assert.equal(api.putStatusRecord.mock.calls.length, 1);
+ const record = api.putStatusRecord.mock.calls[0].arguments[0];
+ assert.equal(record.embed.external.thumb, undefined);
+ } finally {
+ globalThis.fetch = originalFetch;
+ }
+ });
+
+ it("clearLiveStatus writes explicit null and tolerates RecordNotFound", async () => {
+ const { mutations, dataStore, api } = makeSetup();
+ // Seed with a status first
+ dataStore.$profileStatuses.set(
+ "did:plc:live1",
+ createLiveStatusView({ did: "did:plc:live1" }),
+ );
+ api.deleteStatusRecord = mock.fn(async () => {
+ throw new ApiError({
+ status: 400,
+ statusText: "Bad Request",
+ data: { error: "RecordNotFound" },
+ headers: {},
+ url: "",
+ });
+ });
+ await mutations.clearLiveStatus();
+ assert.equal(dataStore.$profileStatuses.get("did:plc:live1"), null);
+ });
+ });
+
+ describe("cross-device convergence", () => {
+ it("setProfiles clears a stale status when the fresh payload omits it", () => {
+ const { derived, dataStore } = makeDerived();
+ addLiveProfile(
+ dataStore,
+ createLiveStatusView({ did, expiresAt: futureExpiry() }),
+ );
+ assert.equal(derived.$actorLiveStatus.get(did).state, "active");
+ // Fresh appview payload with no `status` field
+ const refreshed = createProfile({
+ did,
+ handle: "liveuser.bsky.social",
+ displayName: "Live User",
+ });
+ dataStore.setProfiles([refreshed]);
+ assert.equal(derived.$actorLiveStatus.get(did).state, "none");
+ });
+
+ it("mergeProfile from a post author path preserves an existing status", () => {
+ const { derived, dataStore } = makeDerived();
+ addLiveProfile(
+ dataStore,
+ createLiveStatusView({ did, expiresAt: futureExpiry() }),
+ );
+ assert.equal(derived.$actorLiveStatus.get(did).state, "active");
+ dataStore.mergeProfile({
+ did,
+ handle: "liveuser.bsky.social",
+ displayName: "Live User (from post)",
+ });
+ assert.equal(derived.$actorLiveStatus.get(did).state, "active");
+ });
+
+ it("cancels the per-DID expiry timer when the status transitions to none", () => {
+ const { derived, dataStore } = makeDerived();
+ addLiveProfile(
+ dataStore,
+ createLiveStatusView({ did, expiresAt: futureExpiry() }),
+ );
+ // Reading the computed schedules the timer
+ assert.equal(derived.$actorLiveStatus.get(did).state, "active");
+ assert.equal(derived.liveStatusScheduler.size, 1);
+ // Status vanishes
+ dataStore.setProfiles([
+ createProfile({
+ did,
+ handle: "liveuser.bsky.social",
+ displayName: "Live User",
+ }),
+ ]);
+ assert.equal(derived.$actorLiveStatus.get(did).state, "none");
+ assert.equal(derived.liveStatusScheduler.size, 0);
+ });
+ });
});
--
knotmirror 0.0.1
From c36616cbeee326516593e055aa39e5549919afbd Mon Sep 17 00:00:00 2001
From: Grace Kind
Date: Wed, 2 Sep 2026 18:20:57 -0500
Subject: [PATCH 2/2] Save status for all profiles
---
src/js/dataLayer/dataStore.js | 2 ++
tests/unit/specs/dataLayer/liveStatus.test.js | 7 +++----
2 files changed, 5 insertions(+), 4 deletions(-)
diff --git a/src/js/dataLayer/dataStore.js b/src/js/dataLayer/dataStore.js
index 4c5884e0..0eaefe45 100644
--- a/src/js/dataLayer/dataStore.js
+++ b/src/js/dataLayer/dataStore.js
@@ -88,6 +88,7 @@ export class DataStore extends ReactiveStore {
const normalizedQuotedPost = embedViewRecordToPostView(quotedPost);
this.mergeProfile(normalizedQuotedPost.author);
+ this._saveStatusForProfile(normalizedQuotedPost.author);
if (!this.$posts.has(quotedPost.uri)) {
this.$embeddedPosts.set(quotedPost.uri, normalizedQuotedPost);
}
@@ -96,6 +97,7 @@ export class DataStore extends ReactiveStore {
for (const post of posts) {
this.mergeProfile(post.author);
+ this._saveStatusForProfile(post.author);
this.$posts.set(post.uri, post);
// Delete matching embedded post, since they're only used as previews
this.$embeddedPosts.delete(post.uri);
diff --git a/tests/unit/specs/dataLayer/liveStatus.test.js b/tests/unit/specs/dataLayer/liveStatus.test.js
index b79299fc..5154b222 100644
--- a/tests/unit/specs/dataLayer/liveStatus.test.js
+++ b/tests/unit/specs/dataLayer/liveStatus.test.js
@@ -229,15 +229,14 @@ describe("live status", () => {
it("attaches isLive to hydrated profiles and post authors", () => {
const { derived, dataStore } = makeDerived();
- addLiveProfile(
- dataStore,
- createLiveStatusView({ did, expiresAt: futureExpiry() }),
- );
+ const status = createLiveStatusView({ did, expiresAt: futureExpiry() });
+ addLiveProfile(dataStore, status);
const post = createPost({
uri: `at://${did}/app.bsky.feed.post/live1`,
text: "hello",
authorHandle: "liveuser.bsky.social",
authorDisplayName: "Live User",
+ authorStatus: status,
});
dataStore.setPosts([post]);
assert.equal(derived.$hydratedProfiles.get(did).isLive, true);