feat(linear): show member profile avatars with safe fallbacks
This commit is contained in:
1 parent
b410ead0c7
commit
8cf2521e9e
6 files changed
+95
-9
No files matched your search
@@ -6,7 +6,7 @@ import asyncio
|
||||
import mimetypes
|
||||
import time
|
||||
from pathlib import Path
|
||||
from typing import Any, TypedDict, cast
|
||||
from typing import Any, NotRequired, TypedDict, cast
|
||||
|
||||
import httpx
|
||||
|
||||
@@ -26,6 +26,7 @@ class LinearMember(TypedDict):
|
||||
id: str
|
||||
name: str
|
||||
teams: list[str]
|
||||
avatar_url: NotRequired[str | None]
|
||||
|
||||
|
||||
class LinearApiError(RuntimeError):
|
||||
@@ -141,7 +142,7 @@ class LinearClient:
|
||||
"""query NanobotTeamMembers($team: String!, $after: String, $filter: UserFilter) {
|
||||
team(id: $team) {
|
||||
members(first: 50, after: $after, filter: $filter) {
|
||||
nodes { id name active app }
|
||||
nodes { id name active app avatarUrl }
|
||||
pageInfo { hasNextPage endCursor }
|
||||
}
|
||||
}
|
||||
@@ -159,6 +160,8 @@ class LinearClient:
|
||||
if user_id is not None and member_id != user_id:
|
||||
raise LinearApiError("Linear returned an unexpected member identity")
|
||||
member = members.setdefault(member_id, {"id": member_id, "name": name, "teams": []})
|
||||
avatar_url = node.get("avatarUrl")
|
||||
member["avatar_url"] = avatar_url if isinstance(avatar_url, str) else None
|
||||
if team_name not in member["teams"]:
|
||||
member["teams"].append(team_name)
|
||||
return sorted(members.values(), key=lambda member: (member["name"].casefold(), member["id"]))
|
||||
|
||||
@@ -74,7 +74,9 @@ async def test_directory_paginates_teams_and_members_filters_apps_and_deduplicat
|
||||
if "NanobotMemberTeams" in body["query"]:
|
||||
teams = connection([{"id": "t1", "name": "One"}], "team-next") if not variables["after"] else connection([{"id": "t2", "name": "Two"}])
|
||||
return httpx.Response(200, json={"data": {"teams": teams}})
|
||||
human = {"id": "u1", "name": "Yongru", "active": True, "app": False}
|
||||
assert "avatarUrl" in body["query"]
|
||||
human = {"id": "u1", "name": "Yongru", "active": True, "app": False,
|
||||
"avatarUrl": "https://public.linear.app/u1/avatar"}
|
||||
if variables["team"] == "t1" and not variables["after"]:
|
||||
members = connection([human, {**human, "id": "bot", "app": True}], "member-next")
|
||||
elif variables["after"]:
|
||||
@@ -85,7 +87,10 @@ async def test_directory_paginates_teams_and_members_filters_apps_and_deduplicat
|
||||
|
||||
async with httpx.AsyncClient(transport=httpx.MockTransport(handler)) as http:
|
||||
client = LinearClient(_config(), state, http)
|
||||
assert await client.list_members("org-1") == [{"id": "u1", "name": "Yongru", "teams": ["One", "Two"]}]
|
||||
assert await client.list_members("org-1") == [{
|
||||
"id": "u1", "name": "Yongru", "teams": ["One", "Two"],
|
||||
"avatar_url": "https://public.linear.app/u1/avatar",
|
||||
}]
|
||||
assert len(calls) == 5
|
||||
|
||||
|
||||
@@ -97,12 +102,29 @@ async def test_filtered_lookup_sends_user_filter(tmp_path: Path) -> None:
|
||||
{"team": {"members": connection([{"id": "u1", "name": "Yongru", "active": True, "app": False}])}},
|
||||
])
|
||||
try:
|
||||
assert len(await client.list_members("org-1", user_id="u1")) == 1
|
||||
members = await client.list_members("org-1", user_id="u1")
|
||||
assert len(members) == 1
|
||||
assert members[0]["avatar_url"] is None
|
||||
assert client.graphql.call_args.args[2]["filter"] == {"id": {"eq": "u1"}}
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("avatar", [None, 42, {"url": "unexpected"}])
|
||||
async def test_directory_ignores_missing_or_invalid_avatars(tmp_path: Path, avatar: Any) -> None:
|
||||
client = LinearClient(_config(), LinearStateStore(tmp_path / "state.sqlite3"))
|
||||
client.graphql = AsyncMock(side_effect=[
|
||||
{"teams": connection([{"id": "t1", "name": "Team"}])},
|
||||
{"team": {"members": connection([
|
||||
{"id": "u1", "name": "Yongru", "active": True, "app": False, "avatarUrl": avatar},
|
||||
])}},
|
||||
])
|
||||
try:
|
||||
assert (await client.list_members("org-1"))[0]["avatar_url"] is None
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("response", [
|
||||
{"teams": {"nodes": []}},
|
||||
{"teams": {"nodes": [], "pageInfo": {"hasNextPage": True, "endCursor": None}}},
|
||||
@@ -137,7 +159,8 @@ async def test_member_management_reads_effective_access_and_saves_without_pairin
|
||||
state = LinearStateStore(tmp_path / "state.sqlite3")
|
||||
state.save_installation(_installation())
|
||||
fake = AsyncMock()
|
||||
fake.list_members.return_value = [{"id": "user-1", "name": "Yongru", "teams": ["Team"]}]
|
||||
fake.list_members.return_value = [{"id": "user-1", "name": "Yongru", "teams": ["Team"],
|
||||
"avatar_url": "https://public.linear.app/user-1/avatar"}]
|
||||
monkeypatch.setattr(linear_connect, "_load_linear_config", lambda: config)
|
||||
monkeypatch.setattr(linear_connect, "LinearStateStore", lambda: state)
|
||||
monkeypatch.setattr(linear_connect, "LinearClient", lambda *_args: fake)
|
||||
@@ -148,6 +171,7 @@ async def test_member_management_reads_effective_access_and_saves_without_pairin
|
||||
result = await store.handle("start", {**params, "operation": ["member_access"], "user_id": ["user-1"], "allowed": [value]})
|
||||
assert result["status"] == "member_access_saved"
|
||||
assert result["members"][0]["allowed"] is (value == "true")
|
||||
assert result["members"][0]["avatar_url"] == "https://public.linear.app/user-1/avatar"
|
||||
assert not member_allowed(config, state, "org-1", "user-1")
|
||||
fake.close.assert_awaited()
|
||||
|
||||
|
||||
@@ -14,6 +14,28 @@ import { useClient } from "@/providers/ClientProvider";
|
||||
|
||||
import { linearMemberAccessStore } from "./member-access-store";
|
||||
|
||||
function LinearMemberAvatar({ name, url }: { name: string; url?: string | null }) {
|
||||
const [failedUrl, setFailedUrl] = useState<string | null>(null);
|
||||
let source: string | null = null;
|
||||
try {
|
||||
const parsed = new URL(url ?? "");
|
||||
// Keep image requests on Linear's CDNs rather than arbitrary profile URLs.
|
||||
// Unknown sources fall back to initials.
|
||||
if (parsed.protocol === "https:" && !parsed.username && !parsed.password
|
||||
&& (!parsed.port || parsed.port === "443")
|
||||
&& ["public.linear.app", "uploads.linear.app"].includes(parsed.hostname)) {
|
||||
source = parsed.href;
|
||||
}
|
||||
} catch { /* Missing or malformed avatars use the same fallback. */ }
|
||||
return <span aria-hidden className="relative flex h-8 w-8 shrink-0 items-center justify-center overflow-hidden rounded-full bg-muted text-xs font-medium text-muted-foreground">
|
||||
{name.slice(0, 2).toLocaleUpperCase()}
|
||||
{source && source !== failedUrl ? <img src={source} alt="" width={32} height={32}
|
||||
loading="lazy" decoding="async" referrerPolicy="no-referrer"
|
||||
className="absolute inset-0 h-full w-full object-cover"
|
||||
onError={() => setFailedUrl(source)} /> : null}
|
||||
</span>;
|
||||
}
|
||||
|
||||
export function LinearMemberAccess({ organizationId, configScope = "", disabled = false }: {
|
||||
organizationId: string;
|
||||
configScope?: string;
|
||||
@@ -102,9 +124,7 @@ export function LinearMemberAccess({ organizationId, configScope = "", disabled
|
||||
const statusId = `${panelId}-${member.id}-status`;
|
||||
return <li key={member.id}>
|
||||
<SettingsRow title={<div className="flex min-w-0 items-center gap-3">
|
||||
<span aria-hidden className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-muted text-xs font-medium text-muted-foreground">
|
||||
{member.name.slice(0, 2).toLocaleUpperCase()}
|
||||
</span>
|
||||
<LinearMemberAvatar name={member.name} url={member.avatar_url} />
|
||||
<div className="min-w-0">
|
||||
<p className="truncate" title={member.id}>{member.name}</p>
|
||||
<div className="flex flex-wrap items-center gap-x-2 text-[12px] font-normal text-muted-foreground">
|
||||
|
||||
@@ -20,6 +20,7 @@ export interface LinearMember {
|
||||
id: string;
|
||||
name: string;
|
||||
teams: string[];
|
||||
avatar_url?: string | null;
|
||||
allowed: boolean;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user