Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(chat): show a loopback sender as "You" on an organization transcript (#2180)
Maxfac4d5906c0c
diff --git a/storage/sender_identity.py b/storage/sender_identity.pyindex 99b229234..1e308753a 100644--- a/storage/sender_identity.py+++ b/storage/sender_identity.py@@ -88,8 +88,8 @@ def resolve_sender_labels(A subject can hold several authorization rows within an Instance (one pergranted scope); they describe the same person, so the most recently written- one wins and ties break on ``id`` -- the same subject must not label- differently between two reads of the same transcript.+ one that carries an email wins and ties break on ``id`` -- the same subject+ must not label differently between two reads of the same transcript."""wanted = {subject for subject in subjects if subject}if not wanted:@@ -114,16 +114,18 @@ def resolve_sender_labels(freshest: dict[str, Any] = {}for row in rows:+ # Only a row that yields a label competes: a scope grant written+ # without an email says nothing about who the person is, so it must+ # not shadow an older row of the same subject that does.+ label = sender_label_from_email(row["email"])+ if not label:+ continuesubject = row["subject"]key = (row["updated_at"] or row["created_at"] or 0, row["id"] or "")current = freshest.get(subject)if current is None or key > current[0]:- freshest[subject] = (key, row["email"])- return {- subject: label- for subject, (_key, email) in freshest.items()- if (label := sender_label_from_email(email))- }+ freshest[subject] = (key, label)+ return {subject: label for subject, (_key, label) in freshest.items()}def attach_sender_labels(diff --git a/tests/test_org_sender_identity.py b/tests/test_org_sender_identity.pyindex 30f11b844..c2dd7f8d7 100644--- a/tests/test_org_sender_identity.py+++ b/tests/test_org_sender_identity.py@@ -245,6 +245,31 @@ def test_another_instances_authorization_never_names_a_sender(tmp_path, monkeypaassert "former.example" not in repr(tail)+def test_a_newer_row_without_an_email_does_not_hide_the_sender(tmp_path, monkeypatch):+ engine, scope_id = _state(tmp_path, monkeypatch, instance_kind="organization")+ ids = _seed_transcript(engine, scope_id)+ # The same person granted a second scope later, with no email on that row.+ remote_access_authorization_service.upsert_scoped(+ reference=None,+ instance_id=INSTANCE_ID,+ subject="sub-amy",+ email="",+ scope_kind="show_page",+ scope_ref="page_1",+ authorization_state="current",+ claims={},+ last_checked_at=99,+ updated_at=99,+ )++ with engine.connect() as conn:+ tail = _window(conn, tail=True)++ # Freshness picks among rows that can name the person; a newer row that+ # cannot must not turn a known member back into "unknown".+ assert tail[ids["amy"]]["sender_label"] == "amy.chen"++def test_organization_transcript_survives_an_unreadable_identity_source(tmp_path, monkeypatch):engine, scope_id = _state(tmp_path, monkeypatch, instance_kind="organization")ids = _seed_transcript(engine, scope_id)diff --git a/tests/test_remote_access_vibe_cloud.py b/tests/test_remote_access_vibe_cloud.pyindex 29e2b1332..61d3c2cb8 100644--- a/tests/test_remote_access_vibe_cloud.py+++ b/tests/test_remote_access_vibe_cloud.py@@ -1789,6 +1789,39 @@ def test_session_projects_instance_kind_for_local_and_authenticated_remote(assert "instance_kind" not in unauthenticated.get_json()+def test_session_names_the_principal_this_browser_writes_chat_rows_as(+ monkeypatch,+ tmp_path,+) -> None:+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))+ config = _config()+ config.remote_access.vibe_cloud.instance_kind = "organization"+ config.ui.setup_host = "192.168.2.3"+ config.save()++ loopback = ui_server.app.test_client().get("/api/session", base_url="http://localhost")+ assert loopback.get_json()["author_id"] == "local"++ # A LAN setup-host browser is not remote either, but it is not the machine+ # owner: it writes no local author, so nothing it reads is its own.+ lan = ui_server.app.test_client().get(+ "/api/session",+ base_url="http://192.168.2.3",+ environ_base={"REMOTE_ADDR": "192.168.2.50"},+ )+ assert lan.get_json()["remote"] is False+ assert lan.get_json()["author_id"] is None++ remote = ui_server.app.test_client()+ remote.set_cookie(+ remote_access.SESSION_COOKIE_NAME,+ _session_cookie(config),+ domain="alex.avibe.bot",+ )+ authenticated = remote.get("/api/session", base_url="https://alex.avibe.bot")+ assert authenticated.get_json()["author_id"] == "remote:user-1"++def test_pair_reports_success_when_connector_start_fails(monkeypatch, tmp_path) -> None:monkeypatch.setenv("AVIBE_HOME", str(tmp_path))config = _config()diff --git a/ui/src/components/workbench/ChatOrgSenderIdentity.test.tsx b/ui/src/components/workbench/ChatOrgSenderIdentity.test.tsxindex ba2793b2f..681f65626 100644--- a/ui/src/components/workbench/ChatOrgSenderIdentity.test.tsx+++ b/ui/src/components/workbench/ChatOrgSenderIdentity.test.tsx@@ -16,7 +16,13 @@ import {type InstanceAuthorizationValue,} from '../../context/InstanceAuthorizationContext';import { ToastProvider } from '../../context/ToastProvider';-import { DENIED_INSTANCE_CAPABILITIES, type InstanceKind } from '../../lib/sessionInfo';+import { InstanceAuthorizationProvider } from '../../context/InstanceAuthorizationProvider';+import {+ DENIED_INSTANCE_CAPABILITIES,+ normalizeSessionInfo,+ type InstanceKind,+ type SessionInfo,+} from '../../lib/sessionInfo';import { senderInitial, senderTone } from '../../lib/senderIdentity';import { MessageRow } from './ChatPage';@@ -83,6 +89,49 @@ const humanMessage = (over: Partial<WorkbenchMessage> = {}): WorkbenchMessage =>const row = (message: WorkbenchMessage, instanceKind: InstanceKind | null) =>render(<MessageRow message={message} session={session} messageFontSize={13} />, instanceKind);+// The same row as a real reader sees it: the reader's principal comes from the+// session payload through the production provider, not from a hand-built value.+const rowAs = (message: WorkbenchMessage, reader: SessionInfo) =>+ renderToStaticMarkup(+ <I18nextProvider i18n={i18n}>+ <ToastProvider>+ <MemoryRouter>+ <InstanceAuthorizationProvider session={reader}>+ <MessageRow message={message} session={session} messageFontSize={13} />+ </InstanceAuthorizationProvider>+ </MemoryRouter>+ </ToastProvider>+ </I18nextProvider>,+ );++// Readers exactly as ``normalizeSessionInfo`` hands them over from /api/session.+const LOOPBACK_READER = normalizeSessionInfo({+ remote: false,+ instance_kind: 'organization',+ author_id: 'local',+});+// A LAN setup-host browser: not remote, but not the machine owner either.+const LAN_READER = normalizeSessionInfo({+ remote: false,+ instance_kind: 'organization',+ author_id: null,+});+const cloudReader = (sub: string): SessionInfo =>+ normalizeSessionInfo({+ remote: true,+ authenticated: true,+ email: `${sub}@acme.example`,+ sub,+ author_id: `remote:${sub}`,+ instance_kind: 'organization',+ instance_role: 'member',+ capabilities: DENIED_INSTANCE_CAPABILITIES,+ authorization_state: 'current',+ });+const YOU = `>${en.chat.senderYou}<`;+// The default avatar: a person glyph instead of an initial or a "?".+const DEFAULT_AVATAR = 'lucide-user-round';+describe('organization sender identity', () => {it('names the sender on an organization instance', () => {const markup = row(humanMessage(), 'organization');@@ -107,6 +156,42 @@ describe('organization sender identity', () => {expect(markup).not.toContain(TONE_FILL);});+ it('calls the reader\'s own row "You" at the loopback and through Cloud', () => {+ const local = humanMessage({ author_id: 'local', sender_label: null });+ const amy = humanMessage({ author_id: 'remote:sub-amy', sender_label: 'amy.chen' });++ for (const [message, reader] of [+ [local, LOOPBACK_READER],+ [amy, cloudReader('sub-amy')],+ ] as const) {+ const markup = rowAs(message, reader);+ expect(markup).toContain(YOU);+ expect(markup).toContain(DEFAULT_AVATAR);+ expect(markup).not.toContain('amy.chen');+ expect(markup).not.toContain(en.chat.senderUnknown);+ expect(markup).not.toContain('>?<');+ expect(markup).not.toContain(TONE_FILL);+ }+ });++ it('never calls someone else\'s row "You"', () => {+ const local = humanMessage({ author_id: 'local', sender_label: null });+ const amy = humanMessage({ author_id: 'remote:sub-amy', sender_label: 'amy.chen' });++ // A Cloud reader looking at the loopback owner's row, and at a colleague's.+ const bo = cloudReader('sub-bo');+ expect(rowAs(local, bo)).not.toContain(YOU);+ expect(rowAs(local, bo)).toContain(en.chat.senderUnknown);+ expect(rowAs(amy, bo)).not.toContain(YOU);+ expect(rowAs(amy, bo)).toContain('amy.chen');+ // A LAN browser is not remote, but the owner's loopback rows are not its own.+ expect(rowAs(local, LAN_READER)).not.toContain(YOU);+ expect(rowAs(local, LAN_READER)).toContain(en.chat.senderUnknown);+ // The loopback reader looking at a Cloud member's row.+ expect(rowAs(amy, LOOPBACK_READER)).toContain('amy.chen');+ expect(rowAs(amy, LOOPBACK_READER)).not.toContain(YOU);+ });+it('ignores a label the server should not have sent on a personal instance', () => {// Same message object in both renders: the ONLY variable is instance kind.const personal = row(humanMessage(), 'personal');diff --git a/ui/src/components/workbench/SenderHead.tsx b/ui/src/components/workbench/SenderHead.tsxindex b6a607876..795508fc8 100644--- a/ui/src/components/workbench/SenderHead.tsx+++ b/ui/src/components/workbench/SenderHead.tsx@@ -1,6 +1,8 @@import clsx from 'clsx';+import { UserRound } from 'lucide-react';import { useTranslation } from 'react-i18next';+import { useInstanceAuthorization } from '../../context/InstanceAuthorizationContext';import { formatLocalClockTime, formatLocalDateTime } from '../../lib/relativeTime';import { SENDER_TONE_CLASS, senderInitial, senderTone } from '../../lib/senderIdentity';@@ -20,15 +22,21 @@ export const SenderHead: React.FC<{createdAt: string;}> = ({ authorId, label, createdAt }) => {const { t } = useTranslation();+ const { readerPrincipal } = useInstanceAuthorization();+ // A row written by the reader's own principal is theirs: "You" over the+ // default avatar, whether they sit at the loopback or come in through Cloud.+ // Anyone else's ``local`` row still has no email behind it and reads as+ // "unknown" -- "You" would attribute it to the wrong person.+ const own = Boolean(readerPrincipal) && authorId === readerPrincipal;// No label means the server could not resolve this principal — an IM-relayed// human row, or a subject Cloud never stored an email for. Naming it anything// but "unknown" would attribute the message to someone.- const resolved = typeof label === 'string' && label.trim() ? label.trim() : null;+ const resolved = own ? null : typeof label === 'string' && label.trim() ? label.trim() : null;return (<div className="flex max-w-full items-center gap-2.5 px-1"><span className="truncate text-[13px] font-bold text-foreground">- {resolved ?? t('chat.senderUnknown')}+ {own ? t('chat.senderYou') : (resolved ?? t('chat.senderUnknown'))}</span>{/* Compact clock beside the name; the exact stamp stays one hover away. */}<span@@ -43,12 +51,12 @@ export const SenderHead: React.FC<{'flex size-6 shrink-0 items-center justify-center rounded-full text-[13px] font-bold',resolved? SENDER_TONE_CLASS[senderTone(authorId)]- : // An unresolved sender gets the neutral chip rather than a colour- // that would imply an identity the server could not confirm.+ : // The reader's own row and an unresolved sender both get the+ // neutral chip: neither has a server-confirmed label to colour.'bg-foreground/[0.06] text-muted',)}>- {resolved ? senderInitial(resolved) : '?'}+ {own ? <UserRound className="size-3.5" /> : resolved ? senderInitial(resolved) : '?'}</span></div>);diff --git a/ui/src/context/InstanceAuthorizationContext.ts b/ui/src/context/InstanceAuthorizationContext.tsindex 171bf26bb..f03ceb542 100644--- a/ui/src/context/InstanceAuthorizationContext.ts+++ b/ui/src/context/InstanceAuthorizationContext.ts@@ -9,6 +9,11 @@ export interface InstanceAuthorizationValue {instanceKind: InstanceKind | null;instanceRole: InstanceRole | null;capabilities: InstanceCapabilities;+ // The principal this reader's Chat rows are written as, straight from+ // ``/api/session`` -- ``local`` for a direct loopback browser, ``remote:<sub>``+ // for a Cloud session, absent for anything else (a LAN setup host, say).+ // Compared against a row's ``author_id`` to recognise the reader's own rows.+ readerPrincipal?: string | null;}export const InstanceAuthorizationContext = createContext<InstanceAuthorizationValue>({diff --git a/ui/src/context/InstanceAuthorizationProvider.tsx b/ui/src/context/InstanceAuthorizationProvider.tsxindex 6b49f1169..f72aed638 100644--- a/ui/src/context/InstanceAuthorizationProvider.tsx+++ b/ui/src/context/InstanceAuthorizationProvider.tsx@@ -24,6 +24,7 @@ export const InstanceAuthorizationProvider = ({instanceKind: session.instance_kind,instanceRole: session.instance_role ?? 'owner',capabilities: session.capabilities ?? OWNER_INSTANCE_CAPABILITIES,+ readerPrincipal: session.author_id ?? null,};}if (!session.authenticated || session.authorization_state !== 'current') {@@ -39,6 +40,7 @@ export const InstanceAuthorizationProvider = ({instanceKind: session.instance_kind,instanceRole: session.instance_role,capabilities: session.capabilities,+ readerPrincipal: session.author_id ?? null,};}, [session]);diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.jsonindex 178184570..00956bdfd 100644--- a/ui/src/i18n/en.json+++ b/ui/src/i18n/en.json@@ -4191,6 +4191,7 @@"olderLoadFailed": "Couldn't load earlier messages — tap to retry","organizationNotice": "This is an organization session — messages show who sent them.","senderUnknown": "Unknown sender",+ "senderYou": "You","forkedEmptyTitle": "Forked session ready","forkedEmptyBody": "This session has been forked from the source context. The visible transcript starts clean, and the source context is preserved so you can continue the conversation here.","forkedFromPrefix": "Forked from",diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.jsonindex 119616af8..20df5dffa 100644--- a/ui/src/i18n/zh.json+++ b/ui/src/i18n/zh.json@@ -4191,6 +4191,7 @@"olderLoadFailed": "加载更早的消息失败,点击重试","organizationNotice": "这是一个组织会话,消息会显示发送者。","senderUnknown": "未知发送者",+ "senderYou": "你","forkedEmptyTitle": "复刻会话已创建","forkedEmptyBody": "已从原会话上下文复刻,当前对话记录从空白开始,原会话上下文已保留,继续对话即可","forkedFromPrefix": "复刻自",diff --git a/ui/src/lib/sessionInfo.ts b/ui/src/lib/sessionInfo.tsindex 5c03e86f9..fd83365d9 100644--- a/ui/src/lib/sessionInfo.ts+++ b/ui/src/lib/sessionInfo.ts@@ -27,6 +27,7 @@ export type SessionInfo =instance_kind: InstanceKind | null;instance_role?: 'owner';capabilities?: InstanceCapabilities;+ author_id?: string | null;}| { remote: true; authenticated: false; authorization_refresh_required?: boolean }| {@@ -46,6 +47,7 @@ export type SessionInfo =instance_role: InstanceRole;capabilities: InstanceCapabilities;authorization_state: 'current';+ author_id?: string | null;};export const DENIED_INSTANCE_CAPABILITIES: InstanceCapabilities = {@@ -84,6 +86,10 @@ const normalizeCapabilities = (value: Record<string, unknown>): InstanceCapabiliconst normalizeInstanceKind = (value: unknown): InstanceKind | null =>value === 'personal' || value === 'organization' ? value : null;+// The principal the server writes this browser's Chat rows as, or nothing.+const authorIdField = (value: unknown): { author_id?: string } =>+ typeof value === 'string' && value.trim() ? { author_id: value.trim() } : {};+export const normalizeSessionInfo = (value: unknown): SessionInfo => {if (!isRecord(value)) return { remote: true, authenticated: false };@@ -93,6 +99,7 @@ export const normalizeSessionInfo = (value: unknown): SessionInfo => {instance_kind: normalizeInstanceKind(value.instance_kind),instance_role: 'owner',capabilities: OWNER_INSTANCE_CAPABILITIES,+ ...authorIdField(value.author_id),};}@@ -142,5 +149,6 @@ export const normalizeSessionInfo = (value: unknown): SessionInfo => {instance_role: instanceRole,capabilities,authorization_state: 'current',+ ...authorIdField(value.author_id),};};diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 5022a468b..d5643fd75 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -1373,6 +1373,16 @@ def _is_local_request(config: V2Config | None = None) -> bool:return _is_setup_host_request(config)+def _is_direct_loopback_connection() -> bool:+ """The request reached this process directly over loopback.++ No proxy forwarding, no Docker bridge allowance, no LAN setup host: only a+ browser on this machine talking to a loopback address qualifies.+ """++ return not _has_forwarded_metadata() and _is_loopback_peer() and _is_loopback_host(request.host)++def _is_direct_loopback_browser_request() -> bool:"""Strict same-origin browser admission for local author attribution.@@ -1381,7 +1391,7 @@ def _is_direct_loopback_browser_request() -> bool:directly connected over loopback and present a same-origin header."""- if _has_forwarded_metadata() or not _is_loopback_peer() or not _is_loopback_host(request.host):+ if not _is_direct_loopback_connection():return Falseorigin = _request_origin(request.headers.get("Origin")) or _request_origin(request.headers.get("Referer"))return bool(origin and _same_origin(origin, request.host_url.rstrip("/")))@@ -7259,6 +7269,13 @@ def remote_access_auth_callback():return response+def _remote_author_id(subject: Any) -> str | None:+ """The principal ``_trusted_browser_author_key`` writes a Cloud subject's rows as."""++ subject = str(subject or "").strip()+ return f"remote:{subject}" if subject else None++@app.route("/api/session", methods=["GET"])def api_session():from vibe import remote_access@@ -7278,6 +7295,11 @@ def api_session():"instance_kind": instance_kind,"instance_role": "owner","capabilities": context.capability_projection(),+ # The principal this browser's Chat rows are written as, so the+ # UI can recognise them as its own. Only a direct loopback+ # browser is ``local``; a LAN setup host is not remote either,+ # but it is not the machine owner and writes no local author.+ "author_id": "local" if _is_direct_loopback_connection() else None,})else:@@ -7298,6 +7320,7 @@ def api_session():"authenticated": True,"email": str(identity.get("email", "")),"sub": str(identity.get("sub", "")),+ "author_id": _remote_author_id(identity.get("sub")),"instance_kind": instance_kind,"authorization_state": "unavailable",}@@ -7309,6 +7332,7 @@ def api_session():"authenticated": True,"email": str(identity.get("email", "")),"sub": str(identity.get("sub", "")),+ "author_id": _remote_author_id(identity.get("sub")),"instance_kind": instance_kind,"authorization_state": "revoked",}@@ -7324,6 +7348,7 @@ def api_session():"authenticated": True,"email": str(payload.get("email", "")),"sub": str(payload.get("sub", "")),+ "author_id": _remote_author_id(payload.get("sub")),"instance_kind": instance_kind,"instance_role": context.instance_role,"capabilities": context.capability_projection(),