Skip to content

armgit / avibe

Public Imported from GitHub
0

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.

feat(chat): name the sender on an organization transcript (#2130)

Max0a79583a50de
diff --git a/core/show_session_events.py b/core/show_session_events.py
index 8f89be79b..c0dd9a99d 100644
--- a/core/show_session_events.py
+++ b/core/show_session_events.py
@@ -1219,14 +1219,20 @@ def _public_event_message(message: dict[str, Any] | None) -> dict[str, Any] | No
echo, the ``show.event`` and ``message.new`` streams, the CLI's own result
and the local bridge. The row itself keeps the full metadata for the
deferred consumers that re-check it.
+
+ ``sender_label`` is dropped for the same reason: it is Chat's Organization
+ sender identity, and a Show Page audience — a shared link included — sits
+ outside the Instance, so an anchored row keeps the shape it had before that
+ field existed.
"""
if not isinstance(message, dict):
return message
- metadata = message.get("metadata")
- if not isinstance(metadata, dict):
- return message
- return {**message, "metadata": message_deliveries.public_message_metadata(metadata)}
+ public = {key: value for key, value in message.items() if key != "sender_label"}
+ metadata = public.get("metadata")
+ if isinstance(metadata, dict):
+ public["metadata"] = message_deliveries.public_message_metadata(metadata)
+ return public
def _row_to_payload(row: dict[str, Any]) -> dict[str, Any]:
diff --git a/storage/messages_service.py b/storage/messages_service.py
index 01fdd5786..347fbeff2 100644
--- a/storage/messages_service.py
+++ b/storage/messages_service.py
@@ -33,6 +33,7 @@ from storage.models import (
vault_requests,
)
from storage.pagination import PageRequest, PageResult, page_result_from_limit_plus_one
+from storage.sender_identity import attach_sender_labels
from storage.sessions_service import session_agent_display_label
from vibe.authorization import AuthorizationContext, require_instance_role
from vibe.message_identity import HARNESS_TYPE, INPUT_TURN_AUTHOR_TYPES, NOTIFY_TYPE, VAULT_TYPE
@@ -336,6 +337,26 @@ def _attach_harness_provenance(
return payloads
+def _attach_transcript_identity(
+ conn: Connection,
+ payloads: list[dict[str, Any]],
+ *,
+ authorization_context: AuthorizationContext | Mapping[str, Any] | None = None,
+) -> list[dict[str, Any]]:
+ """Everything a transcript row needs read-side but does not store.
+
+ One entry point for both enrichments so a new transcript window inherits
+ them together instead of picking up whichever one its neighbour happened to
+ call.
+ """
+ return attach_sender_labels(
+ conn,
+ _attach_harness_provenance(
+ conn, payloads, authorization_context=authorization_context
+ ),
+ )
+
+
def transcript_order_value(table: Any = messages) -> Any:
"""SQLite ordering key for when a Message entered the transcript.
@@ -616,7 +637,13 @@ def get_message(
if session_id is not None:
query = query.where(messages.c.session_id == session_id)
row = conn.execute(query).mappings().first()
- return _row_to_payload(dict(row), conn=conn) if row else None
+ if not row:
+ return None
+ # The ``message.new`` publisher loads the live row through here, so the
+ # sender resolved on delivery is the one the following reload shows.
+ return attach_sender_labels(
+ conn, [_row_to_payload(dict(row), conn=conn)]
+ )[0]
def native_message_exists(
@@ -958,7 +985,7 @@ def list_session_messages(
has_newer = len(newer) > effective_limit
newer = newer[:effective_limit]
- merged = _attach_harness_provenance(
+ merged = _attach_transcript_identity(
conn,
older + anchor_rows + newer,
authorization_context=authorization_context,
@@ -975,7 +1002,7 @@ def list_session_messages(
query = query.order_by(order_value.desc(), messages.c.id.desc()).limit(
effective_limit + 1
)
- rows = _attach_harness_provenance(
+ rows = _attach_transcript_identity(
conn,
[
_row_to_payload(
@@ -1008,7 +1035,7 @@ def list_session_messages(
query = query.order_by(order_value.desc(), messages.c.id.desc()).limit(
effective_limit + 1
)
- rows = _attach_harness_provenance(
+ rows = _attach_transcript_identity(
conn,
[
_row_to_payload(
@@ -1042,7 +1069,7 @@ def list_session_messages(
query = query.order_by(order_value.asc(), messages.c.id.asc()).limit(
effective_limit + 1
)
- rows = _attach_harness_provenance(
+ rows = _attach_transcript_identity(
conn,
[
_row_to_payload(
diff --git a/storage/sender_identity.py b/storage/sender_identity.py
new file mode 100644
index 000000000..99b229234
--- /dev/null
+++ b/storage/sender_identity.py
@@ -0,0 +1,159 @@
+"""Name the human behind a Chat message on an Organization instance.
+
+A ``messages`` row records *which principal* wrote it -- ``author_id`` is
+``local`` for a loopback browser and ``remote:<OIDC sub>`` for a
+Cloud-authenticated one -- but no column holds anything a reader recognises. On
+a personal instance that is enough: every human row is the owner. On an
+organization instance several people share one transcript, so a bubble with no
+name cannot be attributed.
+
+The only human-readable identity this machine holds for a subject is the email
+Cloud stored in ``remote_access_authorizations`` -- the same source Show Pages
+read. Resolution happens here, read-side, and only the *label* (the email's
+local part) is written onto a payload: the address itself never leaves this
+module, so a transcript that is later shared or exported carries a display name
+rather than a mailbox.
+
+Attaching at payload-shaping time rather than at each HTTP surface is what
+makes a row keep its sender between the ``message.new`` event and the reload
+that follows: both go through ``storage.messages_service``.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any, Iterable
+
+from sqlalchemy import select
+from sqlalchemy.engine import Connection
+
+from storage.models import remote_access_authorizations
+
+logger = logging.getLogger(__name__)
+
+REMOTE_PRINCIPAL_PREFIX = "remote:"
+SENDER_LABEL_FIELD = "sender_label"
+
+
+def organization_instance_id() -> str | None:
+ """The paired Instance whose members a transcript here may be named after.
+
+ ``None`` on a personal instance, on an unpaired one, and whenever the config
+ cannot be read -- each of which means there is no organization directory to
+ resolve a sender against, not a failed transcript request.
+
+ Returning the id rather than a yes/no is what lets the lookup stay scoped:
+ an OIDC subject is unique within an Instance, not across them, and a stale
+ row from an earlier pairing is explicitly tolerated on disk.
+ """
+ try:
+ from core.services import settings as settings_service
+
+ cloud = settings_service.load_config().remote_access.vibe_cloud
+ except Exception:
+ logger.debug("Sender identity: instance identity unavailable", exc_info=True)
+ return None
+ if cloud.instance_kind != "organization":
+ return None
+ return (cloud.instance_id or "").strip() or None
+
+
+def sender_label_from_email(email: Any) -> str | None:
+ """The display label for a stored email: its local part.
+
+ An address with an empty local part falls back to the whole string so a
+ reader still gets something stable rather than a blank avatar.
+ """
+ if not isinstance(email, str):
+ return None
+ trimmed = email.strip()
+ if not trimmed:
+ return None
+ return trimmed.split("@", 1)[0].strip() or trimmed
+
+
+def resolve_sender_labels(
+ conn: Connection,
+ subjects: Iterable[str],
+ *,
+ instance_id: str,
+) -> dict[str, str]:
+ """Map OIDC subjects to display labels in one query.
+
+ Scoped to ``instance_id`` because that is what the table's identity key is
+ scoped to. Subjects are issued per Instance, so rows left behind by an
+ earlier pairing can carry the same subject for a different person; matching
+ on the subject alone would let one Instance's address name another's sender.
+ Required keyword, so a caller cannot reach the disclosure by forgetting it.
+
+ A subject can hold several authorization rows within an Instance (one per
+ granted 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.
+ """
+ wanted = {subject for subject in subjects if subject}
+ if not wanted:
+ return {}
+ try:
+ rows = list(
+ conn.execute(
+ select(
+ remote_access_authorizations.c.id,
+ remote_access_authorizations.c.subject,
+ remote_access_authorizations.c.email,
+ remote_access_authorizations.c.updated_at,
+ remote_access_authorizations.c.created_at,
+ )
+ .where(remote_access_authorizations.c.instance_id == instance_id)
+ .where(remote_access_authorizations.c.subject.in_(wanted))
+ ).mappings()
+ )
+ except Exception:
+ logger.debug("Sender identity: authorization lookup failed", exc_info=True)
+ return {}
+
+ freshest: dict[str, Any] = {}
+ for row in rows:
+ subject = 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))
+ }
+
+
+def attach_sender_labels(
+ conn: Connection,
+ payloads: list[dict[str, Any]],
+) -> list[dict[str, Any]]:
+ """Add ``sender_label`` to the remote-authored rows of one page.
+
+ Cheap by construction: a page with no ``remote:`` author -- every personal
+ instance, and every loopback or agent row on an organization one -- returns
+ before the config read and before the query. A row whose subject has no
+ stored email simply gets no field, and the UI renders it as an unknown
+ sender.
+ """
+ by_subject: dict[str, list[dict[str, Any]]] = {}
+ for payload in payloads:
+ author_id = payload.get("author_id")
+ if not isinstance(author_id, str) or not author_id.startswith(REMOTE_PRINCIPAL_PREFIX):
+ continue
+ subject = author_id[len(REMOTE_PRINCIPAL_PREFIX) :].strip()
+ if subject:
+ by_subject.setdefault(subject, []).append(payload)
+ if not by_subject:
+ return payloads
+ instance_id = organization_instance_id()
+ if not instance_id:
+ return payloads
+
+ resolved = resolve_sender_labels(conn, by_subject.keys(), instance_id=instance_id)
+ for subject, label in resolved.items():
+ for payload in by_subject[subject]:
+ payload[SENDER_LABEL_FIELD] = label
+ return payloads
diff --git a/tests/test_org_sender_identity.py b/tests/test_org_sender_identity.py
new file mode 100644
index 000000000..30f11b844
--- /dev/null
+++ b/tests/test_org_sender_identity.py
@@ -0,0 +1,286 @@
+"""Organization Chat rows name their sender; personal ones stay as they were.
+
+The label has to be identical however the row arrives -- the ``message.new``
+frame published on delivery, the tail the page hydrates with, the older page it
+scrolls back into, the window it jumps to around a search hit -- or a bubble
+would change sender between live and reload.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+from sqlalchemy import text
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from config.v2_settings import SettingsStore
+from storage import messages_service, remote_access_authorization_service, sender_identity
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.models import agent_sessions
+from storage.settings_service import upsert_scope
+from tests.ui_server_test_helpers import _save_config
+
+INSTANCE_ID = "inst_123"
+# A pairing this machine no longer serves. Its rows are explicitly tolerated on
+# disk when cleanup fails during re-pairing, and OIDC subjects are only unique
+# within an Instance, so they are exactly what must not name anyone here.
+FOREIGN_INSTANCE_ID = "inst_former"
+SESSION_ID = "sess_org_identity"
+AMY = "remote:sub-amy"
+STRANGER = "remote:sub-stranger"
+
+
+def _authorize(*, instance_id: str, subject: str, email: str, updated_at: int = 1) -> None:
+ remote_access_authorization_service.upsert_scoped(
+ reference=None,
+ instance_id=instance_id,
+ subject=subject,
+ email=email,
+ scope_kind="instance",
+ scope_ref=instance_id,
+ authorization_state="current",
+ claims={"email": email},
+ last_checked_at=updated_at,
+ updated_at=updated_at,
+ )
+
+
+def _state(tmp_path, monkeypatch, *, instance_kind: str):
+ """A configured instance with one session and one known Cloud member."""
+
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ _save_config(tmp_path, paired=True, instance_kind=instance_kind)
+ ensure_sqlite_state()
+ SettingsStore.reset_instance()
+
+ _authorize(instance_id=INSTANCE_ID, subject="sub-amy", email="[email protected]")
+
+ engine = create_sqlite_engine(tmp_path / "state" / "vibe.sqlite")
+ with engine.begin() as conn:
+ now = messages_service._utc_now_iso()
+ scope_id = upsert_scope(
+ conn, platform="avibe", scope_type="project", native_id="proj_org", now=now
+ )
+ conn.execute(
+ agent_sessions.insert().values(
+ id=SESSION_ID,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_variant="default",
+ session_anchor="anchor_" + SESSION_ID,
+ native_session_id="",
+ status="active",
+ metadata_json="{}",
+ created_at=now,
+ updated_at=now,
+ last_active_at=now,
+ )
+ )
+ return engine, scope_id
+
+
+def _seed_transcript(engine, scope_id: str) -> dict[str, str]:
+ """Four rows: two Cloud humans, the loopback owner, and the agent."""
+
+ ids: dict[str, str] = {}
+ with engine.begin() as conn:
+ for key, author, author_id in (
+ ("amy", "user", AMY),
+ ("stranger", "user", STRANGER),
+ ("owner", "user", "local"),
+ ("agent", "agent", None),
+ ):
+ ids[key] = messages_service.append(
+ conn,
+ scope_id=scope_id,
+ session_id=SESSION_ID,
+ platform="avibe",
+ author=author,
+ text=f"row from {key}",
+ author_id=author_id,
+ )["id"]
+ return ids
+
+
+def _claim_input(engine, scope_id: str, *, author_id: str) -> None:
+ """The state a just-sent message sits in before native acceptance.
+
+ Chat projects this Delivery as a transcript row, so it is a fifth window
+ onto the same transcript and has to name its sender like the other four.
+ """
+
+ from storage import message_deliveries
+
+ with engine.begin() as conn:
+ delivery = message_deliveries.insert_delivery(
+ conn,
+ delivery_id="msg_claimed_org",
+ session_id=SESSION_ID,
+ priority="p1",
+ state="reserved",
+ snapshot=message_deliveries.message_snapshot(
+ scope_id=scope_id,
+ session_id=SESSION_ID,
+ platform="avibe",
+ author="user",
+ source="user",
+ text="just sent",
+ author_id=author_id,
+ ),
+ dispatch_text="just sent",
+ )
+ message_deliveries.claim_start_batch(
+ conn,
+ turn_id=message_deliveries.new_turn_id(),
+ session_id=SESSION_ID,
+ backend="claude",
+ deliveries=[delivery],
+ dispatch_text="just sent",
+ )
+
+
+def _window(conn, **kwargs) -> dict[str, dict]:
+ result = messages_service.list_session_messages(
+ conn, session_id=SESSION_ID, limit=50, **kwargs
+ )
+ return {row["id"]: row for row in result["messages"]}
+
+
+def test_organization_transcript_labels_every_window_and_the_live_row(tmp_path, monkeypatch):
+ engine, scope_id = _state(tmp_path, monkeypatch, instance_kind="organization")
+ ids = _seed_transcript(engine, scope_id)
+
+ with engine.connect() as conn:
+ tail = _window(conn, tail=True)
+ older = _window(conn, before_id=ids["agent"])
+ around = _window(conn, around_id=ids["amy"])
+ live = messages_service.get_message(conn, ids["amy"])
+
+ for window in (tail, older, around):
+ assert window[ids["amy"]]["sender_label"] == "amy.chen"
+ # The live frame and every reload window agree, so a bubble keeps its
+ # sender when the page refetches.
+ assert live["sender_label"] == "amy.chen"
+
+ # A subject with no stored authorization stays unnamed rather than failing
+ # the page, and the loopback owner and the agent are untouched.
+ assert "sender_label" not in tail[ids["stranger"]]
+ assert "sender_label" not in tail[ids["owner"]]
+ assert "sender_label" not in tail[ids["agent"]]
+
+
+def test_a_just_sent_message_is_named_before_it_materializes(tmp_path, monkeypatch):
+ engine, scope_id = _state(tmp_path, monkeypatch, instance_kind="organization")
+ _claim_input(engine, scope_id, author_id=AMY)
+
+ from vibe.ui_server import _active_unmaterialized_input
+
+ with engine.connect() as conn:
+ projected = _active_unmaterialized_input(conn, SESSION_ID)
+
+ assert projected is not None
+ assert projected["projection"] == "claimed_delivery"
+ # Chat appends this row to a transcript whose durable rows are already
+ # enriched. Without its own label the sender would read "unknown" and then
+ # change once the Delivery materializes -- the one thing the field exists
+ # to prevent.
+ assert projected["sender_label"] == "amy.chen"
+
+
+def test_organization_payload_carries_the_label_not_the_address(tmp_path, monkeypatch):
+ engine, scope_id = _state(tmp_path, monkeypatch, instance_kind="organization")
+ _seed_transcript(engine, scope_id)
+
+ with engine.connect() as conn:
+ result = messages_service.list_session_messages(
+ conn, session_id=SESSION_ID, tail=True, limit=50
+ )
+
+ assert "acme.example" not in repr(result)
+ assert any(row.get("sender_label") == "amy.chen" for row in result["messages"])
+
+
+def test_personal_instance_transcript_is_unchanged(tmp_path, monkeypatch):
+ engine, scope_id = _state(tmp_path, monkeypatch, instance_kind="personal")
+ ids = _seed_transcript(engine, scope_id)
+
+ with engine.connect() as conn:
+ tail = _window(conn, tail=True)
+ live = messages_service.get_message(conn, ids["amy"])
+
+ assert all("sender_label" not in row for row in tail.values())
+ assert "sender_label" not in live
+
+
+def test_another_instances_authorization_never_names_a_sender(tmp_path, monkeypatch):
+ engine, scope_id = _state(tmp_path, monkeypatch, instance_kind="organization")
+ ids = _seed_transcript(engine, scope_id)
+ # The same subject re-issued to someone else by a former pairing, written
+ # more recently than the row that is actually ours...
+ _authorize(
+ instance_id=FOREIGN_INSTANCE_ID,
+ subject="sub-amy",
+ updated_at=99,
+ )
+ # ...and a subject only that former pairing ever knew.
+ _authorize(
+ instance_id=FOREIGN_INSTANCE_ID,
+ subject="sub-stranger",
+ updated_at=99,
+ )
+
+ with engine.connect() as conn:
+ tail = _window(conn, tail=True)
+
+ # Freshness breaks ties *within* our Instance; a newer foreign row is not a
+ # candidate at all, so the label stays the one this Instance authorized.
+ assert tail[ids["amy"]]["sender_label"] == "amy.chen"
+ assert "sender_label" not in tail[ids["stranger"]]
+ assert "former.example" not in repr(tail)
+
+
+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)
+ with engine.begin() as conn:
+ conn.execute(text("drop table remote_access_authorizations"))
+
+ with engine.connect() as conn:
+ tail = _window(conn, tail=True)
+
+ assert set(tail) == set(ids.values())
+ assert "sender_label" not in tail[ids["amy"]]
+
+
+def test_show_page_audiences_do_not_receive_the_sender_label():
+ from core import show_session_events
+
+ projected = show_session_events._public_event_message(
+ {"id": "msg_1", "text": "hi", "sender_label": "amy.chen", "metadata": {}}
+ )
+
+ # A Show Page audience -- a shared link included -- sits outside the
+ # Instance, so the anchored row keeps its pre-#2126 shape.
+ assert "sender_label" not in projected
+ assert projected["text"] == "hi"
+ assert show_session_events._public_event_message(None) is None
+
+
+ ("email", "expected"),
+ [
+ ("[email protected]", "amy.chen"),
+ (" [email protected] ", "amy"),
+ ("@acme.example", "@acme.example"),
+ ("", None),
+ (None, None),
+ ],
+)
+def test_sender_label_is_the_local_part(email, expected):
+ assert sender_identity.sender_label_from_email(email) == expected
diff --git a/ui/src/components/workbench/ChatOrgSenderIdentity.test.tsx b/ui/src/components/workbench/ChatOrgSenderIdentity.test.tsx
new file mode 100644
index 000000000..ba2793b2f
--- /dev/null
+++ b/ui/src/components/workbench/ChatOrgSenderIdentity.test.tsx
@@ -0,0 +1,157 @@
+// An Organization transcript is shared, so a human bubble has to say who wrote
+// it. A personal one has a single human and must keep rendering exactly as it
+// did. These render the real row rather than the whole page, so the only
+// variable between the two expectations is the instance kind.
+import { createInstance } from 'i18next';
+import type { ReactElement } from 'react';
+import { renderToStaticMarkup } from 'react-dom/server';
+import { I18nextProvider, initReactI18next } from 'react-i18next';
+import { MemoryRouter } from 'react-router-dom';
+import { describe, expect, it } from 'vitest';
+
+import en from '../../i18n/en.json';
+import type { WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
+import {
+ InstanceAuthorizationContext,
+ type InstanceAuthorizationValue,
+} from '../../context/InstanceAuthorizationContext';
+import { ToastProvider } from '../../context/ToastProvider';
+import { DENIED_INSTANCE_CAPABILITIES, type InstanceKind } from '../../lib/sessionInfo';
+import { senderInitial, senderTone } from '../../lib/senderIdentity';
+import { MessageRow } from './ChatPage';
+
+const i18n = createInstance();
+void i18n.use(initReactI18next).init({
+ lng: 'en',
+ fallbackLng: 'en',
+ resources: { en: { translation: en } },
+ interpolation: { escapeValue: false },
+});
+
+// The hover-revealed stamp under a bubble — the row's timestamp before the
+// sender head existed. Matched by class so the assertion does not depend on the
+// test machine's timezone.
+const HOVER_STAMP = 'group-hover/message:opacity-100';
+// The fill a resolved sender's avatar paints, checked in the markup so the
+// "resolved gets a tone, unresolved does not" contract is visible in the render
+// and not only in the helper's return value.
+const TONE_FILL = `bg-${senderTone('remote:sub-amy')}`;
+
+const instance = (instanceKind: InstanceKind | null): InstanceAuthorizationValue => ({
+ remote: instanceKind !== null,
+ instanceKind,
+ instanceRole: 'owner',
+ capabilities: DENIED_INSTANCE_CAPABILITIES,
+});
+
+const render = (ui: ReactElement, instanceKind: InstanceKind | null) =>
+ renderToStaticMarkup(
+ <I18nextProvider i18n={i18n}>
+ <ToastProvider>
+ <MemoryRouter>
+ <InstanceAuthorizationContext.Provider value={instance(instanceKind)}>
+ {ui}
+ </InstanceAuthorizationContext.Provider>
+ </MemoryRouter>
+ </ToastProvider>
+ </I18nextProvider>,
+ );
+
+const session = {
+ id: 'ses_01J8XK5M8T',
+ scope_id: 'scope-1',
+ status: 'active',
+ metadata: {},
+} as unknown as WorkbenchSession;
+
+const humanMessage = (over: Partial<WorkbenchMessage> = {}): WorkbenchMessage =>
+ ({
+ id: 'msg_human',
+ type: 'user',
+ author: 'user',
+ source: 'user',
+ author_id: 'remote:sub-amy',
+ author_name: null,
+ sender_label: 'amy.chen',
+ text: 'Can someone take the deploy?',
+ content: {},
+ metadata: {},
+ created_at: '2026-07-27T04:04:00Z',
+ ...over,
+ }) as unknown as WorkbenchMessage;
+
+const row = (message: WorkbenchMessage, instanceKind: InstanceKind | null) =>
+ render(<MessageRow message={message} session={session} messageFontSize={13} />, instanceKind);
+
+describe('organization sender identity', () => {
+ it('names the sender on an organization instance', () => {
+ const markup = row(humanMessage(), 'organization');
+
+ expect(markup).toContain('amy.chen');
+ // Initial over the deterministic tone fill, plus the compact clock.
+ expect(markup).toContain('>A<');
+ expect(markup).toContain(TONE_FILL);
+ expect(markup).toMatch(/>\d{2}:\d{2}</);
+ // The head carries the time, so the hover stamp underneath is gone rather
+ // than repeating it.
+ expect(markup).not.toContain(HOVER_STAMP);
+ expect(markup).toContain('Can someone take the deploy?');
+ });
+
+ it('falls back to a neutral unknown sender when the server resolved none', () => {
+ const markup = row(humanMessage({ sender_label: null }), 'organization');
+
+ expect(markup).toContain(en.chat.senderUnknown);
+ expect(markup).toContain('>?<');
+ // No tone fill: an unresolved row must not look like a confirmed identity.
+ expect(markup).not.toContain(TONE_FILL);
+ });
+
+ 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');
+ const unknownKind = row(humanMessage(), null);
+
+ expect(personal).toBe(unknownKind);
+ expect(personal).not.toContain('amy.chen');
+ expect(personal).not.toContain(en.chat.senderUnknown);
+ // The hover stamp is still the row's only timestamp, as before.
+ expect(personal).toContain(HOVER_STAMP);
+ expect(personal).toContain('Can someone take the deploy?');
+ });
+
+ it('leaves the agent row alone on an organization instance', () => {
+ const agent = {
+ id: 'msg_agent',
+ type: 'result',
+ author: 'agent',
+ source: null,
+ author_id: null,
+ author_name: 'claude',
+ text: 'On it.',
+ content: {},
+ metadata: {},
+ created_at: '2026-07-27T04:05:00Z',
+ } as unknown as WorkbenchMessage;
+
+ expect(row(agent, 'organization')).toBe(row(agent, 'personal'));
+ });
+});
+
+describe('sender avatar derivation', () => {
+ it('gives one principal the same tone every time', () => {
+ expect(senderTone('remote:sub-amy')).toBe(senderTone('remote:sub-amy'));
+ expect(['gold', 'violet']).toContain(senderTone('remote:sub-amy'));
+ // A missing id still resolves rather than throwing.
+ expect(['gold', 'violet']).toContain(senderTone(null));
+ });
+
+ it('takes the first whole character of the label', () => {
+ expect(senderInitial('amy.chen')).toBe('A');
+ expect(senderInitial(' bo')).toBe('B');
+ expect(senderInitial('雨辰')).toBe('雨');
+ // A surrogate pair stays one character instead of splitting.
+ expect(senderInitial('😀ana')).toBe('😀');
+ expect(senderInitial(' ')).toBe('?');
+ });
+});
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index ddcad1a41..be57e86f0 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -63,6 +63,7 @@ import { AnnotationMessage } from './AnnotationMessage';
import { FailureRetry } from './FailureRetry';
import { AGENT_BUBBLE, SYSTEM_BUBBLE, USER_BUBBLE } from './chatBubble';
import { RoleAvatar } from './RoleAvatar';
+import { SenderHead } from './SenderHead';
import { useFileDrop } from '../../lib/useFileDrop';
import { quoteText } from '../../lib/quoteText';
import {
@@ -3974,6 +3975,7 @@ export const Transcript: React.FC<TranscriptProps> = ({
footer,
}) => {
const { t } = useTranslation();
+ const { instanceKind } = useInstanceAuthorization();
const recovery = useModelHubRecovery(modelRecovery, working);
const navigate = useNavigate();
const { openApp } = useWindowManager();
@@ -4031,6 +4033,16 @@ export const Transcript: React.FC<TranscriptProps> = ({
isForkedSession && forkSourceSessionId ? (
<ForkSourceBanner sourceSessionId={forkSourceSessionId} sourceTitle={forkSourceSessionTitle} />
) : null;
+ // One line at the head of a shared transcript saying why the bubbles below
+ // now carry names (design.pen nlrCu). Organization instances only — on a
+ // personal one there is nothing to explain.
+ const organizationNotice =
+ instanceKind === 'organization' ? (
+ <div className="flex h-10 shrink-0 items-center gap-2 rounded-lg border border-mint/20 bg-mint-soft px-3.5 text-[12px] font-medium text-mint-ink">
+ <Info className="size-4 shrink-0" />
+ <span className="truncate">{t('chat.organizationNotice')}</span>
+ </div>
+ ) : null;
const scrollRef = useRef<HTMLDivElement | null>(null);
const contentRef = useRef<HTMLDivElement | null>(null);
// Set just before a programmatic deep-link jump scroll and cleared once it
@@ -4444,6 +4456,7 @@ export const Transcript: React.FC<TranscriptProps> = ({
className="min-h-0 flex-1 overflow-y-auto px-4 py-5 [overflow-anchor:none] md:px-8"
>
<div ref={contentRef} className="mx-auto flex w-full max-w-[1080px] flex-col gap-3">
+ {organizationNotice}
{forkSourceBanner}
{/* One slot at the head of the history for every way paging can end, so
each outcome resolves in place instead of the top twitching: still
@@ -4661,6 +4674,10 @@ export const MessageRow = memo(function MessageRow({
}: MessageRowProps) {
const { t } = useTranslation();
const navigate = useNavigate();
+ // Read here rather than threaded down as a prop: context reaches through the
+ // row's memo, so a personal↔organization change repaints the transcript
+ // without the page having to re-create every row's props.
+ const { instanceKind } = useInstanceAuthorization();
// Harness rows are collapsed by default; this tracks the per-row expand state.
const [expanded, setExpanded] = useState(false);
@@ -4850,14 +4867,27 @@ export const MessageRow = memo(function MessageRow({
// ----- User: right-aligned neutral bubble (kept distinct from agent mint) ---
if (isUser) {
+ // On an Organization instance the bubble gets a head naming who wrote it
+ // (design.pen nlrCu) — which also carries the time, so the hover stamp
+ // underneath would just repeat it. A personal instance keeps the row
+ // exactly as it was: one owner, nothing to attribute.
+ const senderHead =
+ instanceKind === 'organization' ? (
+ <SenderHead
+ authorId={message.author_id}
+ label={message.sender_label}
+ createdAt={message.created_at}
+ />
+ ) : null;
return (
<div data-message-id={message.id} className={rowClass('justify-end')}>
<div className="group/message flex max-w-[min(92%,860px)] flex-col items-end gap-1">
+ {senderHead}
<div className={USER_BUBBLE} style={messageFontStyle}>
{bodyNode}
{attachmentsNode}
</div>
- {time}
+ {senderHead ? null : time}
</div>
</div>
);
diff --git a/ui/src/components/workbench/SenderHead.tsx b/ui/src/components/workbench/SenderHead.tsx
new file mode 100644
index 000000000..b6a607876
--- /dev/null
+++ b/ui/src/components/workbench/SenderHead.tsx
@@ -0,0 +1,55 @@
+import clsx from 'clsx';
+import { useTranslation } from 'react-i18next';
+
+import { formatLocalClockTime, formatLocalDateTime } from '../../lib/relativeTime';
+import { SENDER_TONE_CLASS, senderInitial, senderTone } from '../../lib/senderIdentity';
+
+// The name/time/avatar line above a human bubble on an Organization instance
+// (design.pen nlrCu). Several people share that transcript, so a bubble with no
+// name cannot be attributed; on a personal instance every human row is the
+// owner, and this head is never rendered there.
+//
+// Ordered to read outward from the bubble it heads — name, time, then the
+// avatar against the transcript edge — matching the right-aligned row.
+//
+// Lives beside RoleAvatar rather than inside ChatPage so a row component can
+// use it without importing the whole page back.
+export const SenderHead: React.FC<{
+ authorId: string | null;
+ label: string | null | undefined;
+ createdAt: string;
+}> = ({ authorId, label, createdAt }) => {
+ const { t } = useTranslation();
+ // 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;
+
+ 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')}
+ </span>
+ {/* Compact clock beside the name; the exact stamp stays one hover away. */}
+ <span
+ className="shrink-0 text-[12px] font-medium text-muted"
+ title={formatLocalDateTime(createdAt)}
+ >
+ {formatLocalClockTime(createdAt)}
+ </span>
+ <span
+ aria-hidden
+ className={clsx(
+ '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.
+ 'bg-foreground/[0.06] text-muted',
+ )}
+ >
+ {resolved ? senderInitial(resolved) : '?'}
+ </span>
+ </div>
+ );
+};
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index 447918331..3d4770ba7 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -1305,6 +1305,10 @@ export type WorkbenchMessage = {
source: 'user' | 'agent' | 'harness' | string | null;
author_id: string | null;
author_name: string | null;
+ // Read-side display name for a human sender on an Organization instance,
+ // resolved from author_id. Absent on a personal instance and whenever the
+ // sender cannot be resolved; never carries the underlying email address.
+ sender_label?: string | null;
// Read-side provenance for an agent-callback ("自动触发") harness message (A9a):
// the session that triggered the run, resolved from the run's source_actor.
// Present only on agent_run harness messages; enables the source-session chip
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index bc4c77f19..638f26828 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -4158,6 +4158,8 @@
"loadingOlder": "Loading earlier messages",
"noEarlierMessages": "No earlier messages",
"olderLoadFailed": "Couldn't load earlier messages — tap to retry",
+ "organizationNotice": "This is an organization session — messages show who sent them.",
+ "senderUnknown": "Unknown sender",
"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.json
index 9a73d799f..a4ad06a06 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -4158,6 +4158,8 @@
"loadingOlder": "正在加载更早的消息",
"noEarlierMessages": "没有更早的消息了",
"olderLoadFailed": "加载更早的消息失败,点击重试",
+ "organizationNotice": "这是一个组织会话,消息会显示发送者。",
+ "senderUnknown": "未知发送者",
"forkedEmptyTitle": "复刻会话已创建",
"forkedEmptyBody": "已从原会话上下文复刻,当前对话记录从空白开始,原会话上下文已保留,继续对话即可",
"forkedFromPrefix": "复刻自",
diff --git a/ui/src/lib/relativeTime.ts b/ui/src/lib/relativeTime.ts
index 1c7bac944..0f50583d4 100644
--- a/ui/src/lib/relativeTime.ts
+++ b/ui/src/lib/relativeTime.ts
@@ -37,3 +37,14 @@ export function formatLocalDateTime(iso: string | null | undefined): string {
`${p(d.getHours())}:${p(d.getMinutes())}:${p(d.getSeconds())}`
);
}
+
+// Local wall-clock ``HH:mm`` — the compact stamp a message head shows beside a
+// sender name, where the full ``formatLocalDateTime`` value would crowd the
+// line. Same parsing and same empty/unparseable behaviour.
+export function formatLocalClockTime(iso: string | null | undefined): string {
+ if (!iso) return '—';
+ const d = new Date(iso);
+ if (Number.isNaN(d.getTime())) return iso;
+ const p = (n: number) => String(n).padStart(2, '0');
+ return `${p(d.getHours())}:${p(d.getMinutes())}`;
+}
diff --git a/ui/src/lib/senderIdentity.ts b/ui/src/lib/senderIdentity.ts
new file mode 100644
index 000000000..bcaa4efc8
--- /dev/null
+++ b/ui/src/lib/senderIdentity.ts
@@ -0,0 +1,38 @@
+// How a human sender is drawn in Chat, derived from what the server resolved.
+//
+// On an Organization instance the server attaches ``sender_label`` to a human
+// row (storage/sender_identity.py). Everything visual comes from here so the
+// same person always gets the same avatar -- in the live frame, in the tail, in
+// an older page, on another reader's machine. The tone is a pure function of
+// ``author_id``, never of render order or of the row's position in a window.
+
+export type SenderTone = 'gold' | 'violet';
+
+// The two solid-fill accents the design draws for senders (design.pen nlrCu).
+// Mint is the agent's own avatar and stays reserved for it.
+const SENDER_TONES: readonly SenderTone[] = ['gold', 'violet'];
+
+export const SENDER_TONE_CLASS: Record<SenderTone, string> = {
+ gold: 'bg-gold text-gold-foreground',
+ violet: 'bg-violet text-violet-foreground',
+};
+
+/** Pick a sender's avatar tone from their principal id. */
+export function senderTone(authorId: string | null | undefined): SenderTone {
+ // FNV-1a over the id: same answer across reloads, processes and machines,
+ // which nothing seeded from render order or Math.random could promise.
+ let hash = 0x811c9dc5;
+ for (const ch of String(authorId ?? '')) {
+ hash ^= ch.codePointAt(0) ?? 0;
+ hash = Math.imul(hash, 0x01000193) >>> 0;
+ }
+ return SENDER_TONES[hash % SENDER_TONES.length];
+}
+
+/** The single character an avatar shows for a sender label. */
+export function senderInitial(label: string): string {
+ // By code point, so a name opening with an emoji or an astral character
+ // yields that whole character instead of half a surrogate pair.
+ const [first] = Array.from(label.trim());
+ return first ? first.toUpperCase() : '?';
+}
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index 4b4fc1229..4e1c5b092 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -9266,6 +9266,7 @@ def _active_unmaterialized_input(conn, session_id: str) -> dict[str, Any] | None
"""Project the active claimed Delivery as a temporary transcript row."""
from storage import message_deliveries
+ from storage.sender_identity import attach_sender_labels
turn = message_deliveries.active_turn(conn, session_id)
if turn is None:
@@ -9282,7 +9283,12 @@ def _active_unmaterialized_input(conn, session_id: str) -> dict[str, Any] | None
delivered_at=turn.get("started_at") or turn.get("created_at"),
read_at=None,
)
- return payload
+ # This row joins a transcript whose durable rows were already enriched by
+ # ``messages_service``, so it has to carry the same identity fields or the
+ # sender would appear only once the Delivery materializes. Attached after
+ # the public projection, which rewrites metadata rather than allow-listing
+ # fields.
+ return attach_sender_labels(conn, [payload])[0]
def _append_active_input(