Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Show Slack avatars for project members (#2321)

Regan Bell20a62382add6
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.ts
index 03942627e..faa181ce4 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -149,6 +149,7 @@ import {
} from "./model-options";
import {
attachmentGallery,
+ avatarTpl,
browserRenderableImage,
chipBadge,
copyText,
@@ -355,6 +356,21 @@ export function createChatSurface(
const speaker = (message as { speaker?: string }).speaker;
return typeof speaker === "string" && speaker.trim() ? speaker.trim() : undefined;
}
+
+ function speakerMember(message: AgentMessage): { principalId: string; avatarUrl?: string } | undefined {
+ const speakerId = (message as { speakerId?: string }).speakerId;
+ if (!speakerId) return undefined;
+ const project = contextsState.list.find((c) => c.scopeId === chatState.scopeId)?.project;
+ return project?.members.find((m) => m.principalId === speakerId);
+ }
+
+ function speakerLabelTpl(speaker: string | undefined, message: AgentMessage): TemplateResult | typeof nothing {
+ if (!speaker) return nothing;
+ const member = speakerMember(message);
+ return html`<div class="speaker-label">
+ ${avatarTpl({ key: member?.principalId ?? speaker, name: speaker, avatarUrl: member?.avatarUrl })}${speaker}
+ </div>`;
+ }
let transcriptRefreshGeneration = 0;
const forkOriginController = createForkOriginController({
state: chatState,
@@ -1706,7 +1722,8 @@ export function createChatSurface(
if (!cacheable) return chatMessage(message, index, isStreaming);
const forkable = Boolean(chatState.threadRef && chatState.sessionId && chatState.agent);
const forking = pendingFork !== null;
- const speakerLabel = speakerLabelFor(message);
+ const speaker = speakerLabelFor(message);
+ const speakerLabel = speaker && `${speaker}\n${speakerMember(message)?.avatarUrl ?? ""}`;
const edited = Boolean((message as { edited?: boolean }).edited);
const deleted = Boolean((message as { deleted?: boolean }).deleted);
const day = new Date().toDateString();
@@ -1790,7 +1807,7 @@ export function createChatSurface(
text: `${messageText(message)}${edited || deleted ? ` (${deleted ? "deleted" : "edited"})` : ""}`,
index,
entrySeqs: messageEntrySeqs(message).join(" "),
- before: html`${speaker ? html`<div class="speaker-label">${speaker}</div>` : nothing}${attachmentGallery(attachments, (attachment) => browserRenderableImage(attachment.mimeType), userAttachmentBadge)}`,
+ before: html`${speakerLabelTpl(speaker, message)}${attachmentGallery(attachments, (attachment) => browserRenderableImage(attachment.mimeType), userAttachmentBadge)}`,
after: sendFailure
? html`<div class="send-failure">
<span>${sendFailure}</span
@@ -1807,7 +1824,7 @@ export function createChatSurface(
data-index=${index}
data-entry-seqs=${messageEntrySeqs(message).join(" ")}
>
- ${speaker ? html`<div class="speaker-label">${speaker}</div>` : nothing}
+ ${speakerLabelTpl(speaker, message)}
${attachmentGallery(attachments, (attachment) => browserRenderableImage(attachment.mimeType), userAttachmentBadge)}
<div
class="message-bubble user-bubble ${deleted ? "deleted-bubble" : ""}"
diff --git a/plugins/web-ui/src/contexts.ts b/plugins/web-ui/src/contexts.ts
index 8a03cd435..27977fdca 100644
--- a/plugins/web-ui/src/contexts.ts
+++ b/plugins/web-ui/src/contexts.ts
@@ -26,7 +26,7 @@ import {
} from "./core-bridge";
import { UI_BASE } from "./deep-link";
import { errMessage } from "../../chassis/src/errors";
-import { actionSnippet, fieldSelect, formatBytes, initials, menuSelect, relTime } from "./ui";
+import { actionSnippet, avatarTpl, fieldSelect, formatBytes, menuSelect, relTime } from "./ui";
import { icon } from "./icons";
import { appState, replacePanePreservingFocus, switchView, syncUrlFromState } from "./shell";
import { startNewChat } from "./sessions";
@@ -697,10 +697,11 @@ function projectMembersSection(context: CoreContext): TemplateResult {
<div class="project-member-list">
${projectPeople(context).map((principalId) => {
const label = memberLabel(context, principalId);
- const viaChannel = Boolean(project.members.find((member) => member.principalId === principalId)?.viaChannel);
+ const member = project.members.find((m) => m.principalId === principalId);
+ const viaChannel = Boolean(member?.viaChannel);
return html`
<div class="project-member-row">
- <span class="project-member-avatar" aria-hidden="true">${initials(label)}</span>
+ ${avatarTpl({ key: principalId, name: label, avatarUrl: member?.avatarUrl })}
<span class="project-member-name" dir="auto">${label}</span>
${principalId === project.ownerId ? html`<span class="badge">Owner</span>` : nothing}
${
diff --git a/plugins/web-ui/src/core-bridge.ts b/plugins/web-ui/src/core-bridge.ts
index bb3581c1e..5fe54f393 100644
--- a/plugins/web-ui/src/core-bridge.ts
+++ b/plugins/web-ui/src/core-bridge.ts
@@ -255,7 +255,7 @@ export interface CoreProject {
memberIds: string[];
channelMemberIds?: string[];
scopeId: string;
- members: Array<{ principalId: string; displayName: string; viaChannel?: boolean }>;
+ members: Array<{ principalId: string; displayName: string; avatarUrl?: string; viaChannel?: boolean }>;
slackChannel?: { channelId: string; channelName: string; linkedBy?: string; linkedAt?: number };
createdAt?: number;
updatedAt?: number;
@@ -1714,6 +1714,7 @@ interface HistoryUserMessage {
attachments?: HistoryAttachment[];
steered?: boolean;
speaker?: string;
+ speakerId?: string;
ts?: string;
edited?: boolean;
deleted?: boolean;
@@ -1873,6 +1874,7 @@ export function userEntryMessage(
runId?: string;
steered?: boolean;
name?: string;
+ speakerId?: string;
ts?: string;
attachments?: Array<{ name?: string; mimetype?: string; sizeBytes?: number; artifactId?: string }>;
} | null;
@@ -1889,6 +1891,7 @@ export function userEntryMessage(
timestamp: entry.createdAt,
...(mail ? { subagentMail: mail } : {}),
...(payload?.steered ? { steered: true } : {}),
+ ...(typeof payload?.speakerId === "string" && payload.speakerId ? { speakerId: payload.speakerId } : {}),
...(typeof payload?.name === "string" && payload.name.trim() ? { speaker: payload.name.trim() } : {}),
...(typeof payload?.ts === "string" && payload.ts ? { ts: payload.ts } : {}),
...(attachments.length
diff --git a/plugins/web-ui/src/deploy-permissions.ts b/plugins/web-ui/src/deploy-permissions.ts
index 3f482a97f..83202be2e 100644
--- a/plugins/web-ui/src/deploy-permissions.ts
+++ b/plugins/web-ui/src/deploy-permissions.ts
@@ -2,7 +2,7 @@ import { html, render, nothing } from "lit";
import { live } from "lit/directives/live.js";
import { Building2, Globe, Lock, Search, X } from "lucide";
import { api } from "./core-bridge";
-import { closeFormMenus, initials, menuSelect } from "./ui";
+import { avatarTpl, closeFormMenus, menuSelect } from "./ui";
import { icon } from "./icons";
import { scopeChip } from "./contexts";
import { friendlyPrincipal } from "./deploy-view";
@@ -204,8 +204,11 @@ export async function openDeploymentPermissions(id: string, title: string, owner
selected
? html`<div class="permission-invite">
<div class="permission-person">
- <span class="project-member-avatar">${initials(selected.displayName)}</span
- ><span class="permission-person-label"
+ ${avatarTpl({
+ key: selected.principalId,
+ name: selected.displayName,
+ avatarUrl: selected.avatarUrl,
+ })}<span class="permission-person-label"
>${selected.displayName}<small>${selected.principalId}</small></span
>
</div>
@@ -313,12 +316,11 @@ export async function openDeploymentPermissions(id: string, title: string, owner
<div class="permission-section-label">People with access</div>
<div class="project-member-list">
<div class="permission-row">
- <span class="project-member-avatar" aria-hidden="true">${initials(owner.replace("personal:", ""))}</span
- ><span class="permission-person-label"
+ ${avatarTpl({ key: owner, name: owner.replace("personal:", "") })}<span class="permission-person-label"
>${owner.startsWith("personal:") ? friendlyPrincipal(owner.slice(9)) : scopeChip(owner)}</span
><span class="permission-owner">Owner</span>
</div>
- ${grantees.filter((grant) => generalAccess() !== "org" || !isOrgGrant(grant)).map((grant) => html`<div class="permission-row"><span class="project-member-avatar" aria-hidden="true">${initials(isOrgGrant(grant) ? orgName() : grant.scope.replace("personal:", ""))}</span><span class="permission-person-label">${isOrgGrant(grant) ? orgName() : (names.get(grant.scope) ?? (grant.scope.startsWith("personal:") ? grant.scope.slice(9) : scopeChip(grant.scope)))}${names.has(grant.scope) ? html`<small>${grant.scope.replace("personal:", "")}</small>` : nothing}</span>${permissionMenu(grant.permission === "write" ? "manage" : "view", `Access for ${grant.scope}`, (value) => void change(grant.scope, value), true)}</div>`)}
+ ${grantees.filter((grant) => generalAccess() !== "org" || !isOrgGrant(grant)).map((grant) => html`<div class="permission-row">${avatarTpl({ key: grant.scope, name: isOrgGrant(grant) ? orgName() : grant.scope.replace("personal:", "") })}<span class="permission-person-label">${isOrgGrant(grant) ? orgName() : (names.get(grant.scope) ?? (grant.scope.startsWith("personal:") ? grant.scope.slice(9) : scopeChip(grant.scope)))}${names.has(grant.scope) ? html`<small>${grant.scope.replace("personal:", "")}</small>` : nothing}</span>${permissionMenu(grant.permission === "write" ? "manage" : "view", `Access for ${grant.scope}`, (value) => void change(grant.scope, value), true)}</div>`)}
</div>
<div class="permission-section-label permission-general-label">General access</div>
<div class="project-member-list">
diff --git a/plugins/web-ui/src/inbox.ts b/plugins/web-ui/src/inbox.ts
index 889770322..b95bd8db6 100644
--- a/plugins/web-ui/src/inbox.ts
+++ b/plugins/web-ui/src/inbox.ts
@@ -15,7 +15,6 @@ import {
sentMailTpl,
} from "./sent-mail";
import { html, nothing, render, type TemplateResult } from "lit";
-import { keyed } from "lit/directives/keyed.js";
import { live } from "lit/directives/live.js";
import { ref } from "lit/directives/ref.js";
import {
@@ -49,7 +48,7 @@ import { listBackLink } from "./list-page";
import { registerPaneKind } from "./pane-kinds";
import { exitSplitIfActive, notifyPanesChanged } from "./split";
import { tip } from "./tooltip";
-import { brandName, fieldSelect, menuSelect, initials, relTime, sheenLabel, slackMark, workingWave } from "./ui";
+import { brandName, fieldSelect, menuSelect, avatarTpl, relTime, sheenLabel, slackMark, workingWave } from "./ui";
import { icon } from "./icons";
import { assistantSidebar, assistantMessage } from "./assistant-sidebar";
import { inboxChat } from "./inbox-chat";
@@ -1165,41 +1164,6 @@ function participantsOf(item: InboxItem): Participant[] {
return [...found.values()];
}
-function avatarHue(key: string): number {
- let hash = 0;
- for (let i = 0; i < key.length; i++) hash = (hash * 31 + key.charCodeAt(i)) % 360;
- return hash;
-}
-
-function avatarTpl(person: Participant): TemplateResult {
- const photo = person.avatarUrl?.startsWith("https://") ? person.avatarUrl : undefined;
- return html`<span
- class="inbox-avatar"
- style=${`--avatar-hue:${avatarHue(person.key)}`}
- ${tip(person.name)}
- aria-hidden="true"
- >
- ${initials(person.name)}
- ${
- photo
- ? keyed(
- photo,
- html`<img
- src=${photo}
- alt=""
- loading="lazy"
- decoding="async"
- referrerpolicy="no-referrer"
- @error=${(event: Event) => {
- (event.currentTarget as HTMLImageElement).hidden = true;
- }}
- />`,
- )
- : nothing
- }
- </span>`;
-}
-
const AVATARS_SHOWN = 4;
export function participantsTpl(item: InboxItem): TemplateResult | typeof nothing {
diff --git a/plugins/web-ui/src/people-results.ts b/plugins/web-ui/src/people-results.ts
index b6bc351ce..71cca41f9 100644
--- a/plugins/web-ui/src/people-results.ts
+++ b/plugins/web-ui/src/people-results.ts
@@ -1,12 +1,13 @@
import { html, type TemplateResult } from "lit";
import { Plus } from "lucide";
-import { initials } from "./ui";
+import { avatarTpl } from "./ui";
import { icon } from "./icons";
export interface DirectoryMatch {
principalId: string;
displayName: string;
type: string;
+ avatarUrl?: string;
}
export function peopleResults(
@@ -18,7 +19,7 @@ export function peopleResults(
${matches.map(
(person) =>
html` <button class="project-member-result" type="button" ?disabled=${busy} @click=${() => select(person)}>
- <span class="project-member-avatar" aria-hidden="true">${initials(person.displayName)}</span>
+ ${avatarTpl({ key: person.principalId, name: person.displayName, avatarUrl: person.avatarUrl })}
<span class="project-member-name" dir="auto">${person.displayName}</span>${icon(Plus, 15)}
</button>`,
)}
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index d568e437d..fe231d687 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -1768,6 +1768,9 @@ a.chat-row-open {
}
.speaker-label {
+ display: flex;
+ align-items: center;
+ gap: 6px;
font-size: 11px;
font-weight: 600;
color: var(--muted-foreground);
@@ -6004,6 +6007,20 @@ a.connector-widget:focus-visible {
font-size: 10px;
font-weight: 650;
}
+.speaker-label > .inbox-avatar {
+ width: 18px;
+ height: 18px;
+ border-radius: 50%;
+}
+.project-member-row > .inbox-avatar,
+.project-member-result > .inbox-avatar,
+.permission-person > .inbox-avatar,
+.permission-row > .inbox-avatar {
+ width: 28px;
+ height: 28px;
+ border-radius: 50%;
+ font-size: 10px;
+}
.project-member-name {
min-width: 0;
flex: 1;
diff --git a/plugins/web-ui/src/ui.ts b/plugins/web-ui/src/ui.ts
index 3dd9488b5..227a40248 100644
--- a/plugins/web-ui/src/ui.ts
+++ b/plugins/web-ui/src/ui.ts
@@ -1,5 +1,6 @@
import { previewFile } from "./file-open.ts";
import { html, nothing, type TemplateResult } from "lit";
+import { keyed } from "lit/directives/keyed.js";
import { live } from "lit/directives/live.js";
import { tip } from "./tooltip.ts";
import { Check, ChevronDown, Download, type IconNode } from "lucide";
@@ -239,6 +240,41 @@ export function initials(s: string): string {
return (two || "?").toUpperCase();
}
+function avatarHue(key: string): number {
+ let hash = 0;
+ for (let i = 0; i < key.length; i++) hash = (hash * 31 + key.charCodeAt(i)) % 360;
+ return hash;
+}
+
+export function avatarTpl(person: { key: string; name: string; avatarUrl?: string }): TemplateResult {
+ const photo = person.avatarUrl?.startsWith("https://") ? person.avatarUrl : undefined;
+ return html`<span
+ class="inbox-avatar"
+ style=${`--avatar-hue:${avatarHue(person.key)}`}
+ ${tip(person.name)}
+ aria-hidden="true"
+ >
+ ${initials(person.name)}
+ ${
+ photo
+ ? keyed(
+ photo,
+ html`<img
+ src=${photo}
+ alt=""
+ loading="lazy"
+ decoding="async"
+ referrerpolicy="no-referrer"
+ @error=${(event: Event) => {
+ (event.currentTarget as HTMLImageElement).hidden = true;
+ }}
+ />`,
+ )
+ : nothing
+ }
+ </span>`;
+}
+
export function relTime(ms: number): string {
const s = Math.max(0, Math.floor((Date.now() - ms) / 1000));
if (s < 60) return "just now";
diff --git a/plugins/web-ui/test/activity-folding.test.ts b/plugins/web-ui/test/activity-folding.test.ts
index f6e4e2183..144f933a6 100644
--- a/plugins/web-ui/test/activity-folding.test.ts
+++ b/plugins/web-ui/test/activity-folding.test.ts
@@ -106,7 +106,7 @@ test("steering separates tool folds with a visible unlabelled user message", asy
user.speaker = "Another person";
user.edited = true;
conv.drawActiveChat();
- assert.equal(document.querySelector(".inline-steer .speaker-label")?.textContent, "Another person");
+ assert.match(document.querySelector(".inline-steer .speaker-label")?.textContent ?? "", /AP\s+Another person/);
assert.equal(document.querySelector(".inline-steer .revision-badge")?.textContent, "(edited)");
user.deleted = true;
conv.drawActiveChat();
diff --git a/plugins/web-ui/test/deep-link-boot-fixture.ts b/plugins/web-ui/test/deep-link-boot-fixture.ts
index 45fee7f37..93fb6d098 100644
--- a/plugins/web-ui/test/deep-link-boot-fixture.ts
+++ b/plugins/web-ui/test/deep-link-boot-fixture.ts
@@ -145,7 +145,7 @@ export async function harness(opts: HarnessOptions): Promise<Harness> {
if (path.startsWith("/api/runtime-config")) {
if (opts.holdRuntimeConfig) await runtimeHeld;
return Response.json({
- scopeId: "personal:tester",
+ scopeId: new URL(path, "http://localhost").searchParams.get("scopeId") ?? "personal:tester",
approvedHarnesses: [],
modelsByHarness: {},
modelCatalog: {},
diff --git a/plugins/web-ui/test/history.test.ts b/plugins/web-ui/test/history.test.ts
index bdff8706a..9bd65c0e2 100644
--- a/plugins/web-ui/test/history.test.ts
+++ b/plugins/web-ui/test/history.test.ts
@@ -531,16 +531,22 @@ test("a durable turn_failure entry renders like the live inline error (survives
assert.equal(err.errorMessage, "API integrators: you can reduce refusals…");
});
-test("user entries carry the stored speaker name and slack ts onto the rebuilt message", () => {
+test("user entries carry the stored speaker identity, name and slack ts onto the rebuilt message", () => {
const entries: SessionEntry[] = [
- { type: "user", payload: { text: "hi", name: "Alice Example", ts: "100.1" }, createdAt: 100 },
+ {
+ type: "user",
+ payload: { text: "hi", name: "Alice Example", speakerId: "person-a", ts: "100.1" },
+ createdAt: 100,
+ },
{ type: "user", payload: { text: "anonymous web message" }, createdAt: 110 },
];
const msgs = entriesToMessages(entries, MODEL);
- const [slack, web] = msgs as Array<{ speaker?: string; ts?: string }>;
+ const [slack, web] = msgs as Array<{ speaker?: string; speakerId?: string; ts?: string }>;
assert.equal(slack?.speaker, "Alice Example");
+ assert.equal(slack?.speakerId, "person-a");
assert.equal(slack?.ts, "100.1");
assert.equal(web?.speaker, undefined);
+ assert.equal(web?.speakerId, undefined);
assert.equal(web?.ts, undefined);
});
diff --git a/plugins/web-ui/test/project-speaker-avatars.test.ts b/plugins/web-ui/test/project-speaker-avatars.test.ts
new file mode 100644
index 000000000..0531515e8
--- /dev/null
+++ b/plugins/web-ui/test/project-speaker-avatars.test.ts
@@ -0,0 +1,71 @@
+import assert from "node:assert/strict";
+import { test } from "node:test";
+import { harness, SESSION } from "./deep-link-boot-fixture.ts";
+
+test("project speaker photos follow authenticated identity, not duplicate or reassigned names", async () => {
+ const session = {
+ ...SESSION,
+ type: "group" as const,
+ createdAt: 1000,
+ scopeId: "group:project",
+ threadRef: "web:project:chat",
+ };
+ const speakers = [
+ { name: "Alex", speakerId: "person-a" },
+ { name: "Alex", speakerId: "person-b" },
+ { name: "Old Name", speakerId: "person-c" },
+ { name: "Alex" },
+ { name: "Old Name" },
+ { name: "Departed", speakerId: "missing-person" },
+ ];
+ const h = await harness({
+ path: `/s/${session.id}`,
+ session,
+ listSessions: [session],
+ contexts: [
+ {
+ scopeId: session.scopeId,
+ kind: "group",
+ name: "Project",
+ sessionCount: 1,
+ lastActivityAt: 1000,
+ project: {
+ id: "project",
+ name: "Project",
+ ownerId: "person-a",
+ memberIds: ["person-a", "person-b", "person-c", "person-d", "person-e"],
+ scopeId: session.scopeId,
+ members: [
+ { principalId: "person-a", displayName: "Alex", avatarUrl: "https://example.com/a.png" },
+ { principalId: "person-b", displayName: "Alex", avatarUrl: "https://example.com/b.png" },
+ { principalId: "person-c", displayName: "New Name", avatarUrl: "https://example.com/c.png" },
+ { principalId: "person-d", displayName: "Old Name", avatarUrl: "https://example.com/d.png" },
+ { principalId: "person-e", displayName: "Departed", avatarUrl: "https://example.com/e.png" },
+ ],
+ },
+ },
+ ],
+ entries: speakers.map((speaker, seq) => ({
+ seq,
+ type: "user",
+ createdAt: 1000 + seq,
+ payload: { text: `Message ${seq}`, ...speaker },
+ })),
+ });
+ try {
+ h.releaseSessions();
+ await h.boot();
+ await h.sessionsReady();
+ const labels = [...document.querySelectorAll(".message-stack .speaker-label")];
+ assert.equal(labels.length, speakers.length);
+ assert.deepEqual(
+ labels.map((label) => label.querySelector("img")?.getAttribute("src") ?? null),
+ ["https://example.com/a.png", "https://example.com/b.png", "https://example.com/c.png", null, null, null],
+ );
+ assert.match(labels[2]!.textContent!, /Old Name/);
+ assert.match(labels[3]!.textContent!, /AL\s+Alex/);
+ assert.match(labels[4]!.textContent!, /ON\s+Old Name/);
+ } finally {
+ await h.close();
+ }
+});
diff --git a/src/api/app-helpers.ts b/src/api/app-helpers.ts
index 11016fd48..6bfc873be 100644
--- a/src/api/app-helpers.ts
+++ b/src/api/app-helpers.ts
@@ -263,6 +263,7 @@ export function createAppHelpers(deps: AppDeps, app: App) {
return {
principalId,
displayName: member?.displayName?.trim() || principalId,
+ ...(member?.avatarUrl ? { avatarUrl: member.avatarUrl } : {}),
...(manual.has(principalId) ? {} : { viaChannel: true }),
};
}),
diff --git a/src/api/app-types.ts b/src/api/app-types.ts
index d55f397b6..a611fa1df 100644
--- a/src/api/app-types.ts
+++ b/src/api/app-types.ts
@@ -204,7 +204,7 @@ export type VisibleCron = Cron & { scopeName?: string };
export type ProjectView = Project & {
scopeId: ScopeId;
- members: Array<{ principalId: string; displayName: string; viaChannel?: boolean }>;
+ members: Array<{ principalId: string; displayName: string; avatarUrl?: string; viaChannel?: boolean }>;
};
type ProjectViewMutation =
diff --git a/src/api/routes/directory.ts b/src/api/routes/directory.ts
index 29a421201..a870a6a8f 100644
--- a/src/api/routes/directory.ts
+++ b/src/api/routes/directory.ts
@@ -1,4 +1,4 @@
-import { isPrincipalType, PRINCIPAL_TYPES, type PrincipalType } from "../../types.ts";
+import { isPrincipalType, PRINCIPAL_TYPES } from "../../types.ts";
import type { DirectoryMember } from "../../directory/directory-store.ts";
import { canonicalPerson } from "../../directory/person.ts";
import { sendJson } from "../http.ts";
@@ -84,7 +84,7 @@ async function pushDirectory(ctx: ApiCtx): Promise<void> {
if (Array.isArray(b.members)) {
const members = b.members
.filter(
- (m): m is { principalId: string; displayName: string; type: PrincipalType; slackId?: string } =>
+ (m): m is DirectoryMember =>
isObj(m) && typeof m.principalId === "string" && typeof m.displayName === "string" && isPrincipalType(m.type),
)
.map((m) => ({
@@ -92,6 +92,7 @@ async function pushDirectory(ctx: ApiCtx): Promise<void> {
displayName: m.displayName,
type: m.type,
...(typeof m.slackId === "string" && m.slackId ? { slackId: m.slackId } : {}),
+ ...(typeof m.avatarUrl === "string" && m.avatarUrl.startsWith("https://") ? { avatarUrl: m.avatarUrl } : {}),
}));
await app.upsertDirectory(members, numOrUndef(b.membersSyncedAt));
memberCount = members.length;
diff --git a/src/api/slack-core-client.ts b/src/api/slack-core-client.ts
index 9ca492a80..60382770d 100644
--- a/src/api/slack-core-client.ts
+++ b/src/api/slack-core-client.ts
@@ -63,7 +63,7 @@ interface StoredApprovalView extends Omit<PendingApproval, "reason"> {
}
interface DirectoryPush {
- members?: Array<{ principalId: string; displayName: string; type: "internal"; slackId?: string }>;
+ members?: Array<{ principalId: string; displayName: string; type: "internal"; slackId?: string; avatarUrl?: string }>;
channels?: Array<{ channelId: string; name: string; isPrivate?: boolean; isExternal?: boolean }>;
channelMembers?: Array<{ channelId: string; principalId: string }>;
channelRosterIds?: string[];
diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.ts
index a72e5c71f..74bd24e7c 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -3024,6 +3024,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
!syntheticPrompt && input.text.trim()
? {
text: input.text,
+ ...(humanTurn ? { speakerId: actor.id } : {}),
...((messageTs ?? entryTs) ? { ts: messageTs ?? entryTs } : {}),
...(actor.displayName?.trim() ? { name: actor.displayName.trim() } : {}),
...(input.displayText?.trim() ? { display: input.displayText } : {}),
@@ -3222,6 +3223,9 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {
}
Object.assign(payload, swarmEntryProvenance);
if (input.runId) payload.runId = input.runId;
+ delete payload.speakerId;
+ if (humanTurn && !syntheticPrompt && !continuation && !payload.steered && !payload.overheard)
+ payload.speakerId = actor.id;
if (actor.displayName?.trim() && typeof payload.name !== "string")
payload.name = actor.displayName.trim();
if (input.displayText?.trim() && payload.text === input.text && typeof payload.display !== "string")
diff --git a/src/directory/directory-store.ts b/src/directory/directory-store.ts
index f70a871f3..225935495 100644
--- a/src/directory/directory-store.ts
+++ b/src/directory/directory-store.ts
@@ -10,6 +10,7 @@ export interface DirectoryMember {
displayName: string;
type: PrincipalType;
slackId?: string;
+ avatarUrl?: string;
}
export interface DirectoryChannel {
diff --git a/src/directory/postgres-directory-store.ts b/src/directory/postgres-directory-store.ts
index 6c216f3f1..f485e824d 100644
--- a/src/directory/postgres-directory-store.ts
+++ b/src/directory/postgres-directory-store.ts
@@ -129,9 +129,10 @@ function memberRow(r: Record<string, unknown>): DirectoryMember {
displayName: r.display_name as string,
type: r.type as PrincipalType,
...(r.slack_id ? { slackId: r.slack_id as string } : {}),
+ ...(r.avatar_url ? { avatarUrl: r.avatar_url as string } : {}),
};
}
-const MEMBER_COLS = "principal_id, display_name, type, slack_id";
+const MEMBER_COLS = "principal_id, display_name, type, slack_id, avatar_url";
function channelRow(r: Record<string, unknown>): DirectoryChannel {
return {
channelId: r.channel_id as string,
@@ -183,6 +184,10 @@ export function createPostgresDirectoryStore(connectionString: string): Director
id: "directory/store/0004",
statements: ["ALTER TABLE directory_channels ADD COLUMN IF NOT EXISTS observed_at BIGINT"],
},
+ {
+ id: "directory/store/0005",
+ statements: ["ALTER TABLE directory_members ADD COLUMN IF NOT EXISTS avatar_url TEXT"],
+ },
]);
async function pick<T>(
@@ -275,14 +280,16 @@ export function createPostgresDirectoryStore(connectionString: string): Director
for (const m of members) if (m.principalId && m.type === "internal") byId.set(m.principalId, m);
const internal = [...byId.values()];
- const hash = hashRoster(internal.map((m) => `${m.principalId}|${m.displayName}|${m.type}|${m.slackId ?? ""}`));
+ const hash = hashRoster(
+ internal.map((m) => `${m.principalId}|${m.displayName}|${m.type}|${m.slackId ?? ""}|${m.avatarUrl ?? ""}`),
+ );
return swapIfChanged("members_hash", hash, syncedAt, async (client) => {
await client.query("DELETE FROM directory_members WHERE org_id = $1", [orgId]);
if (internal.length) {
await client.query(
- `INSERT INTO directory_members (org_id, principal_id, display_name, display_name_lc, type, slack_id)
- SELECT $1, * FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[])`,
+ `INSERT INTO directory_members (org_id, principal_id, display_name, display_name_lc, type, slack_id, avatar_url)
+ SELECT $1, * FROM unnest($2::text[], $3::text[], $4::text[], $5::text[], $6::text[], $7::text[])`,
[
orgId,
internal.map((m) => m.principalId),
@@ -290,6 +297,7 @@ export function createPostgresDirectoryStore(connectionString: string): Director
internal.map((m) => normDirectoryQuery(m.displayName)),
internal.map((m) => m.type),
internal.map((m) => m.slackId ?? null),
+ internal.map((m) => m.avatarUrl ?? null),
],
);
}
diff --git a/src/slack/directory.ts b/src/slack/directory.ts
index 6b70d78b8..73de0405e 100644
--- a/src/slack/directory.ts
+++ b/src/slack/directory.ts
@@ -159,7 +159,8 @@ export function createDirectory(deps: {
if (ids.identityMode === "email" && !u.is_bot && actor.externalId === u.id && u.team_id === ids.ownTeamId)
missingEmails++;
const timezone = slackUserTimezone(u);
- byId.set(u.id, { actor, ...(timezone ? { timezone } : {}) });
+ const avatarUrl = u.profile?.image_72;
+ byId.set(u.id, { actor, ...(timezone ? { timezone } : {}), ...(avatarUrl ? { avatarUrl } : {}) });
if (!u.deleted) {
indexName(u.name, u.id);
indexName(u.profile?.display_name, u.id);
@@ -461,6 +462,7 @@ export function createDirectory(deps: {
displayName: a.displayName ?? a.externalId,
type: "internal" as const,
...(slackId && slackId !== a.externalId ? { slackId } : {}),
+ ...(u.avatarUrl ? { avatarUrl: u.avatarUrl } : {}),
};
});
const fetched = await fetchChannels(client, invalidations, targetChannelIds);
diff --git a/src/slack/identity.ts b/src/slack/identity.ts
index 8bcd2b1c4..cde428e4c 100644
--- a/src/slack/identity.ts
+++ b/src/slack/identity.ts
@@ -18,7 +18,7 @@ export interface SlackUser {
is_bot?: boolean;
real_name?: string;
name?: string;
- profile?: { display_name?: string; email?: string; tz?: string };
+ profile?: { display_name?: string; email?: string; tz?: string; image_72?: string };
}
export type SlackIdentityMode = "slack-id" | "email";
@@ -31,6 +31,7 @@ export interface UserCache {
export interface CachedUser {
actor: ActorAssertion;
timezone?: string;
+ avatarUrl?: string;
}
export function createUserCache(opts: { ttlMs?: number; max?: number } = {}): UserCache {
diff --git a/test/directory-store.test.ts b/test/directory-store.test.ts
index 1d493a61b..d37797bc9 100644
--- a/test/directory-store.test.ts
+++ b/test/directory-store.test.ts
@@ -109,10 +109,17 @@ describe("member slackId (the real <@…> mention id for an email principal)", (
it("round-trips slackId through replace → get → list, and resolve", async () => {
const d = createDirectoryStore();
await d.replace([
- { principalId: "[email protected]", displayName: "Eve", type: "internal", slackId: "U9" },
+ {
+ principalId: "[email protected]",
+ displayName: "Eve",
+ type: "internal",
+ slackId: "U9",
+ avatarUrl: "https://avatars.slack-edge.com/eve.png",
+ },
{ principalId: "U5", displayName: "Dana", type: "internal" },
]);
assert.equal((await d.get("[email protected]"))?.slackId, "U9");
+ assert.equal((await d.get("[email protected]"))?.avatarUrl, "https://avatars.slack-edge.com/eve.png");
assert.equal((await d.get("U5"))?.slackId, undefined);
assert.equal((await d.list()).find((m) => m.principalId === "[email protected]")?.slackId, "U9");
const r = await d.resolve("Eve");
diff --git a/test/orchestrator.test.ts b/test/orchestrator.test.ts
index 614dc2527..6009ed113 100644
--- a/test/orchestrator.test.ts
+++ b/test/orchestrator.test.ts
@@ -134,6 +134,25 @@ test("internal DM turn runs end-to-end and records the session", async () => {
assert.deepEqual(types, ["user", "assistant"]);
});
+test("human transcript entries retain authenticated identity across duplicate names and renames", async () => {
+ const { app } = freshApp();
+ for (const actor of [
+ { externalId: "U1", displayName: "Alex" },
+ { externalId: "U2", displayName: "Alex" },
+ { externalId: "U1", displayName: "New Name" },
+ ]) {
+ const result = await app.turn(channel("hello", { actor, liveActor: true }));
+ assert.equal(result.status, "ok", result.reason);
+ const found = await app.getSession(result.sessionId!);
+ const payload = found!.entries.filter((entry) => entry.type === "user").at(-1)!.payload as {
+ speakerId?: string;
+ name?: string;
+ };
+ assert.equal(payload.speakerId, actor.externalId);
+ assert.equal(payload.name, actor.displayName);
+ }
+});
+
test("the persisted assistant entry carries authoritative turn timing for transcript rendering", async () => {
const { app } = freshApp();
const before = Date.now();
@@ -2228,6 +2247,7 @@ test("overheard messages are imported ONCE into the durable log, author-labeled,
);
assert.equal((ov1[1]!.payload as { sourceRole: string }).sourceRole, "agent");
assert.equal((ov1[0]!.payload as { name: string }).name, "Alice");
+ assert.ok(ov1.every((entry) => (entry.payload as { speakerId?: string }).speakerId === undefined));
assert.deepEqual((ov1[0]!.payload as { files: string[] }).files, ["cat.jpg"]);
const r2 = await app.turn(
@@ -3996,7 +4016,10 @@ test("a failure before the harness records the user message back-fills it — no
const t1 = await app.turn(dm("hello"));
assert.equal(t1.status, "ok");
- await assert.rejects(app.turn(dm("use the fancy model", { model: "not-a-real-model" })), /not approved/);
+ await assert.rejects(
+ app.turn(dm("use the fancy model", { model: "not-a-real-model", liveActor: true })),
+ /not approved/,
+ );
const found = await app.getSession(t1.sessionId!);
const failureIdx = found!.entries.findIndex((e) => turnFailure(e));
@@ -4004,6 +4027,7 @@ test("a failure before the harness records the user message back-fills it — no
const prior = found!.entries[failureIdx - 1]!;
assert.equal(prior.type, "user", "the message that failed sits right above its error — not an orphan bubble");
assert.equal((prior.payload as { text?: string }).text, "use the fancy model");
+ assert.equal((prior.payload as { speakerId?: string }).speakerId, "U1");
const after = await app.turn(dm("!histcount"));
assert.equal(after.status, "ok");
diff --git a/test/postgres-directory-store.test.ts b/test/postgres-directory-store.test.ts
index 7c4951a92..7b3f80ea3 100644
--- a/test/postgres-directory-store.test.ts
+++ b/test/postgres-directory-store.test.ts
@@ -85,10 +85,17 @@ test("pg directory: exact channel-id resolution has a matching expression index"
test("pg directory: slackId round-trips through replace → get/list/resolve; a change re-writes", { skip }, async () => {
const store = createPostgresDirectoryStore(URL!);
await store.replace([
- { principalId: "[email protected]", displayName: "Eve", type: "internal", slackId: "U9" },
+ {
+ principalId: "[email protected]",
+ displayName: "Eve",
+ type: "internal",
+ slackId: "U9",
+ avatarUrl: "https://avatars.slack-edge.com/eve.png",
+ },
{ principalId: "U5", displayName: "Dana", type: "internal" },
]);
assert.equal((await store.get("[email protected]"))?.slackId, "U9");
+ assert.equal((await store.get("[email protected]"))?.avatarUrl, "https://avatars.slack-edge.com/eve.png");
assert.equal((await store.get("U5"))?.slackId, undefined);
assert.equal((await store.list()).find((m) => m.principalId === "[email protected]")?.slackId, "U9");
const r = await store.resolve("Eve");