Multiplayer agent harness for work.
Slack channels: opt-in pinned header message instead of setting the description (#508)
Regan Bell0dbc4d8ac9dd
diff --git a/cli/templates/slack-manifest.json b/cli/templates/slack-manifest.jsonindex dcd8fbcca..4434a964a 100644--- a/cli/templates/slack-manifest.json+++ b/cli/templates/slack-manifest.json@@ -39,6 +39,8 @@"files:write","reactions:write","reactions:read",+ "pins:read",+ "pins:write","emoji:read"]}@@ -60,7 +62,9 @@"reaction_removed"]},- "interactivity": { "is_enabled": true },+ "interactivity": {+ "is_enabled": true+ },"org_deploy_enabled": false,"socket_mode_enabled": true,"token_rotation_enabled": falsediff --git a/deploy/stacks/acme/slack-app-manifest.yml b/deploy/stacks/acme/slack-app-manifest.ymlindex dd164c9a5..428d411b6 100644--- a/deploy/stacks/acme/slack-app-manifest.yml+++ b/deploy/stacks/acme/slack-app-manifest.yml@@ -34,6 +34,8 @@ oauth_config:- files:write- reactions:write- reactions:read+ - pins:read+ - pins:writesettings:event_subscriptions:bot_events:diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.htmlindex b6debbb63..445407f0c 100644--- a/plugins/admin/public/index.html+++ b/plugins/admin/public/index.html@@ -4339,6 +4339,33 @@><span class="status" id="st-org-ambient"></span></div></section>+ <section class="card setting-row hidden" id="card-channel-header-pin-default">+ <div class="head">+ <h2>Channel pinned header</h2>+ <p>+ Org-wide, default off. When on, the agent posts and pins a small header message (naming the model+ in use) in every Slack channel it's in. Channels can still override it either way from their+ project page.+ </p>+ </div>+ <div class="body">+ <label class="setting-toggle">+ <input type="checkbox" id="channel-header-pin-default" />+ <span class="setting-switch" aria-hidden="true"></span>+ <span class="setting-copy"+ ><strong>Pin the header by default</strong+ ><small+ >Applies to channels without an explicit choice; flipping this updates existing channels+ within a moment.</small+ ></span+ >+ </label>+ </div>+ <div class="foot">+ <button class="primary" data-save="channel-header-pin-default">Apply</button+ ><span class="status" id="st-channel-header-pin-default"></span>+ </div>+ </section><div class="governance-group" id="governance-intelligence"><h2>Models & browsing</h2><p>The models, browser runtime, and organization context available on future turns.</p>@@ -6363,6 +6390,9 @@const showInteractiveFastMode = scope.startsWith("org:") && "interactiveFastMode" in r.data;$("card-interactive-fast-mode").classList.toggle("hidden", !showInteractiveFastMode);if (showInteractiveFastMode) $("interactive-fast-mode").checked = r.data.interactiveFastMode === true;+ const showHeaderPinDefault = scope.startsWith("org:") && "channelHeaderPinDefault" in r.data;+ $("card-channel-header-pin-default").classList.toggle("hidden", !showHeaderPinDefault);+ if (showHeaderPinDefault) $("channel-header-pin-default").checked = !!r.data.channelHeaderPinDefault;const opts = r.data.baseModelOptions || [];const dflt = r.data.baseModelDefault || "";@@ -7984,6 +8014,7 @@"external-slack-participants": () => ({ on: $("external-slack-participants").checked }),"org-ambient": () => ({ on: $("org-ambient").checked }),"interactive-fast-mode": () => ({ on: $("interactive-fast-mode").checked }),+ "channel-header-pin-default": () => ({ on: $("channel-header-pin-default").checked }),runtime: () => ({ harnessId: $("base-harness").value, modelId: $("base-model").value }),"approved-harnesses": () => ({ids: Array.from(document.querySelectorAll("#approved-harnesses-list input[type=checkbox]:checked")).map(@@ -8016,6 +8047,7 @@"external-slack-participants": "st-external-slack-participants","org-ambient": "st-org-ambient","interactive-fast-mode": "st-interactive-fast-mode",+ "channel-header-pin-default": "st-channel-header-pin-default",runtime: "st-runtime","approved-harnesses": "st-approved-harnesses","webui-models": "st-webui-models",diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex dea65d1c2..c853dff91 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -1011,6 +1011,27 @@ const apiRoutes: readonly WebRoute[] = [return relayCore(res, "PUT", "/v1/runtime-config", JSON.stringify({ ...body, principalId: user, scopeId }));},},+ {+ method: "GET",+ path: "/api/channel-header-pin",+ handle: async (c) => {+ const { res, url, user } = c;+ const scopeId = url.searchParams.get("scopeId") || `personal:${user}`;+ const qs = new URLSearchParams({ principalId: user, scopeId });+ return relayCore(res, "GET", `/v1/channel-header-pin?${qs.toString()}`);+ },+ },+ {+ method: "PUT",+ path: "/api/channel-header-pin",+ handle: async (c) => {+ const { req, res, user } = c;+ const body = await readJson<Record<string, unknown>>(req, res);+ if (!body) return;+ const scopeId = typeof body.scopeId === "string" && body.scopeId ? body.scopeId : `personal:${user}`;+ return relayCore(res, "PUT", "/v1/channel-header-pin", JSON.stringify({ ...body, principalId: user, scopeId }));+ },+ },{method: "GET",path: "/api/scope-resources",diff --git a/plugins/web-ui/src/channel-header.ts b/plugins/web-ui/src/channel-header.tsnew file mode 100644index 000000000..ef09e51c2--- /dev/null+++ b/plugins/web-ui/src/channel-header.ts@@ -0,0 +1,154 @@+import { html, nothing, type TemplateResult } from "lit";+import { api } from "./core-bridge";+import { errMessage } from "../../chassis/src/errors";+import { fieldSelect } from "./ui";++interface HeaderPinWire {+ scopeId: string;+ on: boolean;+ configured?: boolean | null;+ default?: boolean;+}++export const channelHeaderState = {+ scope: null as string | null,+ loading: false,+ saving: false,+ on: false,+ configured: null as boolean | null,+ orgDefault: false,+ loaded: false,+ notice: "",+ noticeKind: "" as "" | "saved" | "error",+};++let loadSeq = 0;+let redraw: () => void = () => {};++export function channelHeaderApplies(scopeId: string): boolean {+ return scopeId.startsWith("channel:");+}++export function resetChannelHeader(): void {+ loadSeq += 1;+ channelHeaderState.scope = null;+ channelHeaderState.loading = false;+ channelHeaderState.saving = false;+ channelHeaderState.on = false;+ channelHeaderState.configured = null;+ channelHeaderState.orgDefault = false;+ channelHeaderState.loaded = false;+ channelHeaderState.notice = "";+ channelHeaderState.noticeKind = "";+}++export async function loadChannelHeader(scopeId: string, onChange: () => void): Promise<void> {+ redraw = onChange;+ if (!channelHeaderApplies(scopeId) || channelHeaderState.scope === scopeId) return;+ resetChannelHeader();+ const seq = ++loadSeq;+ channelHeaderState.scope = scopeId;+ channelHeaderState.loading = true;+ try {+ const r = await api<HeaderPinWire>(`/api/channel-header-pin?scopeId=${encodeURIComponent(scopeId)}`);+ if (seq !== loadSeq) return;+ channelHeaderState.on = r.on;+ channelHeaderState.configured = r.configured ?? null;+ channelHeaderState.orgDefault = r.default ?? false;+ channelHeaderState.loaded = true;+ } catch (e) {+ if (seq !== loadSeq) return;+ channelHeaderState.notice = errMessage(e, "Couldn't load the pinned header setting.");+ channelHeaderState.noticeKind = "error";+ } finally {+ if (seq === loadSeq) {+ channelHeaderState.loading = false;+ redraw();+ }+ }+}++async function save(scope: string, on: boolean | null): Promise<void> {+ if (channelHeaderState.saving) return;+ const seq = loadSeq;+ channelHeaderState.saving = true;+ channelHeaderState.notice = "";+ channelHeaderState.noticeKind = "";+ redraw();+ try {+ const r = await api<HeaderPinWire>("/api/channel-header-pin", {+ method: "PUT",+ body: JSON.stringify({ scopeId: scope, on }),+ });+ if (seq !== loadSeq) return;+ channelHeaderState.on = r.on;+ channelHeaderState.configured = r.configured ?? null;+ channelHeaderState.notice = r.on ? "Header pinned in the channel." : "Pinned header removed.";+ channelHeaderState.noticeKind = "saved";+ } catch (e) {+ if (seq !== loadSeq) return;+ channelHeaderState.notice = errMessage(e, "Couldn't update the pinned header setting.");+ channelHeaderState.noticeKind = "error";+ } finally {+ if (seq === loadSeq) {+ channelHeaderState.saving = false;+ redraw();+ }+ }+}++function configuredSelectValue(configured: boolean | null): "default" | "on" | "off" {+ if (configured === null) return "default";+ return configured ? "on" : "off";+}++export function channelHeaderSection(scopeId: string): TemplateResult | typeof nothing {+ if (!channelHeaderApplies(scopeId) || channelHeaderState.scope !== scopeId) return nothing;+ if (channelHeaderState.loading)+ return html`<section class="context-panel channel-header" aria-labelledby="channel-header-title">+ <h2 class="context-panel-title" id="channel-header-title">Pinned header</h2>+ <div class="context-panel-loading">Loading…</div>+ </section>`;+ return html`+ <section class="context-panel channel-header" aria-labelledby="channel-header-title">+ <div class="context-panel-heading">+ <div>+ <h2 class="context-panel-title" id="channel-header-title">Pinned header</h2>+ <p class="context-panel-copy">A small pinned message in the Slack channel naming the model in use.</p>+ </div>+ </div>+ ${+ channelHeaderState.loaded+ ? fieldSelect({+ id: "channel-header-select",+ className: "channel-header-select",+ focusKey: "channel-header",+ describedBy: "channel-header-hint",+ ariaLabel: "Pinned Slack header for this channel",+ disabled: channelHeaderState.saving,+ value: configuredSelectValue(channelHeaderState.configured),+ onChange: (v) => void save(scopeId, v === "default" ? null : v === "on"),+ options: [+ html`<option value="default" ?selected=${channelHeaderState.configured === null}>+ Default (${channelHeaderState.orgDefault ? "on" : "off"})+ </option>`,+ html`<option value="on" ?selected=${channelHeaderState.configured === true}>On</option>`,+ html`<option value="off" ?selected=${channelHeaderState.configured === false}>Off</option>`,+ ],+ })+ : nothing+ }+ <p class="channel-header-hint" id="channel-header-hint">+ Turning it on posts and pins the header; turning it off unpins and removes it. Default follows the org-wide+ setting. Model changes edit the pinned message in place.+ </p>+ ${+ channelHeaderState.notice+ ? html`<span class="context-model-status ${channelHeaderState.noticeKind}" aria-live="polite"+ >${channelHeaderState.notice}</span+ >`+ : nothing+ }+ </section>+ `;+}diff --git a/plugins/web-ui/src/context-model.ts b/plugins/web-ui/src/context-model.tsindex 0b4655753..3174a4c08 100644--- a/plugins/web-ui/src/context-model.ts+++ b/plugins/web-ui/src/context-model.ts@@ -146,7 +146,7 @@ export function contextModelSection(scopeId: string): TemplateResult | typeof no? "Following the org default — it changes when the org's does.": "Pinned for this project. Anyone in a chat can still pick a different model for that conversation."}- ${isSlack ? " The channel description in Slack names this model." : ""}+ ${isSlack ? " The pinned Slack header (when enabled below) names this model." : ""}</p>${contextModelState.noticediff --git a/plugins/web-ui/src/contexts.ts b/plugins/web-ui/src/contexts.tsindex 3f1169f0c..9c1684632 100644--- a/plugins/web-ui/src/contexts.ts+++ b/plugins/web-ui/src/contexts.ts@@ -39,6 +39,7 @@ import { cronRunSummary, cronRunSummaryTitle, cronScheduleSummary } from "./cronimport { restoreDialogFocus } from "./dialog-focus";import { ambientPolicySection, loadAmbientPolicy, resetAmbientPolicy } from "./ambient-policy";import { contextModelSection, loadContextModel, resetContextModel } from "./context-model";+import { channelHeaderSection, loadChannelHeader, resetChannelHeader } from "./channel-header";interface ScopeFile {id: string;@@ -190,6 +191,7 @@ export async function renderContexts(): Promise<void> {void loadScopeResources(contextsState.selected);void loadAmbientPolicy(contextsState.selected, drawContexts);void loadContextModel(contextsState.selected, drawContexts);+ void loadChannelHeader(contextsState.selected, drawContexts);}drawContexts();}@@ -506,7 +508,7 @@ function detailTpl(c: CoreContext): TemplateResult {</div><aside class="context-settings" aria-label=${c.project ? "Project settings" : "Context settings"}>${c.project ? projectMembersSection(c) : nothing} ${c.project ? projectSlackSection(c) : nothing}- ${contextModelSection(c.scopeId)} ${ambientPolicySection(c.scopeId)}+ ${contextModelSection(c.scopeId)} ${channelHeaderSection(c.scopeId)} ${ambientPolicySection(c.scopeId)}</aside></div></div>@@ -1429,12 +1431,14 @@ function selectContext(scopeId: string | null): void {contextsState.resourcesLoading = false;resetAmbientPolicy();resetContextModel();+ resetChannelHeader();syncUrlFromState();drawContexts();if (scopeId) {void loadScopeResources(scopeId);void loadAmbientPolicy(scopeId, drawContexts);void loadContextModel(scopeId, drawContexts);+ void loadChannelHeader(scopeId, drawContexts);}}diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex 08820165b..581b6614e 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -6313,6 +6313,21 @@ a.chat-row-open {.context-model-status.error {color: var(--destructive, #c0392b);}+.channel-header {+ display: flex;+ flex-direction: column;+ gap: 10px;+}+.channel-header-select {+ align-self: flex-start;+ min-width: min(260px, 100%);+}+.channel-header-hint {+ margin: 0;+ color: var(--muted-foreground);+ font-size: 12px;+ line-height: 1.45;+}.ambient-policy {display: flex;flex-direction: column;diff --git a/plugins/web-ui/test/channel-header-source.test.ts b/plugins/web-ui/test/channel-header-source.test.tsnew file mode 100644index 000000000..9ce92a48a--- /dev/null+++ b/plugins/web-ui/test/channel-header-source.test.ts@@ -0,0 +1,37 @@+import assert from "node:assert/strict";+import { readFileSync } from "node:fs";+import test from "node:test";++const panel = readFileSync(new URL("../src/channel-header.ts", import.meta.url), "utf8");+const contexts = readFileSync(new URL("../src/contexts.ts", import.meta.url), "utf8");+const server = readFileSync(new URL("../server/index.ts", import.meta.url), "utf8");+const css = readFileSync(new URL("../src/shell.css", import.meta.url), "utf8");++test("the pinned-header panel exists only for channel scopes and follows the org default", () => {+ assert.match(panel, /scopeId\.startsWith\("channel:"\)/);+ assert.match(panel, /\?selected=\$\{channelHeaderState\.configured === null\}/);+ assert.match(panel, /Default \(\$\{channelHeaderState\.orgDefault \? "on" : "off"\}\)/);+ assert.match(panel, /save\(scopeId, v === "default" \? null : v === "on"\)/);+});++test("the panel writes through the channel-header-pin endpoint and reports both directions", () => {+ assert.match(panel, /api<HeaderPinWire>\("\/api\/channel-header-pin", \{\s*method: "PUT"/);+ assert.match(panel, /Header pinned in the channel\./);+ assert.match(panel, /Pinned header removed\./);+});++test("the server proxies the toggle with the signed-in user as principal", () => {+ assert.match(server, /path: "\/api\/channel-header-pin"/);+ assert.match(server, /\/v1\/channel-header-pin\?\$\{qs\.toString\(\)\}/);+});++test("every context loads and resets the pinned-header setting with the page", () => {+ assert.match(contexts, /loadChannelHeader\(contextsState\.selected, drawContexts\)/);+ assert.match(contexts, /resetChannelHeader\(\)/);+ assert.match(contexts, /channelHeaderSection\(c\.scopeId\)/);+});++test("pinned-header panel styles use the shell theme contract", () => {+ const block = css.slice(css.indexOf(".channel-header {"), css.indexOf("\n.ambient-policy {"));+ assert.match(block, /color: var\(--muted-foreground\)/);+});diff --git a/plugins/web-ui/test/context-model-source.test.ts b/plugins/web-ui/test/context-model-source.test.tsindex 0d1a6fc1b..924d146d5 100644--- a/plugins/web-ui/test/context-model-source.test.ts+++ b/plugins/web-ui/test/context-model-source.test.ts@@ -18,7 +18,7 @@ test("the panel offers inheriting the org default and names what is serving now"assert.match(panel, /!options\.some\(\(o\) => o\.value === selected\)/);assert.match(panel, /no longer offered/);assert.match(panel, /Saved — new conversations here run on/);- assert.match(panel, /The channel description in Slack names this model\./);+ assert.match(panel, /The pinned Slack header \(when enabled below\) names this model\./);});test("the panel is labelled, focus-keyed, and disabled while saving", () => {diff --git a/src/api/agent-api-catalog.ts b/src/api/agent-api-catalog.tsindex f2abe4277..4ff05eeab 100644--- a/src/api/agent-api-catalog.ts+++ b/src/api/agent-api-catalog.ts@@ -50,6 +50,24 @@ const FAMILIES: AgentApiFamily[] = [},],},+ {+ match: (m, p) => p === "/v1/channel-header-pin" && (m === "GET" || m === "PUT"),+ guidance:+ "The pinned Slack header (a small pinned message naming the model in use) follows an org-wide default (off unless an admin turned it on). Only override it for a channel scope when someone in that channel asks.",+ routes: [+ {+ method: "GET",+ path: "/v1/channel-header-pin",+ summary: "read whether this channel scope shows the pinned model header in Slack",+ },+ {+ method: "PUT",+ path: "/v1/channel-header-pin",+ summary:+ "override the pinned Slack header for this channel scope with {on: boolean}; {on: null} reverts to the org default",+ },+ ],+ },{match: (m, p) =>(p === "/v1/projects" && (m === "GET" || m === "POST")) ||diff --git a/src/api/routes/admin-resources.ts b/src/api/routes/admin-resources.tsindex 6d3c2f22f..ea68a259a 100644--- a/src/api/routes/admin-resources.ts+++ b/src/api/routes/admin-resources.ts@@ -309,6 +309,23 @@ export const ADMIN_RESOURCES: readonly AdminResource[] = [(deps, scope, on) => deps.config!.setExternalSlackParticipants(scope, on),),},+ {+ id: "channel-header-pin-default",+ kind: "boolean",+ target: "org",+ label:+ "Channel pinned-header default: on means the agent posts and pins its header message (naming the model in use) in every Slack channel unless a channel explicitly turns it off.",+ readKey: "channelHeaderPinDefault",+ get: (deps, scope) => (parseScopeId(scope).kind === "org" ? deps.config!.getChannelHeaderPin(scope) : undefined),+ apply: generic<boolean>(+ (body, { scope }) => {+ const bad = orgOnly(scope, "the channel pinned-header default is org-wide");+ if (bad) return bad;+ return boolBody(body);+ },+ (deps, scope, on) => deps.config!.setChannelHeaderPinLatest(scope, on),+ ),+ },{id: "org-ambient",kind: "boolean",diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.tsindex b6b3437ff..81771f981 100644--- a/src/api/routes/surface.ts+++ b/src/api/routes/surface.ts@@ -1305,6 +1305,43 @@ async function putRuntimeConfig(ctx: ApiCtx): Promise<void> {return sendJson(ctx.res, 200, await runtimeConfigBody(ctx, target.scope));}+async function getChannelHeaderPin(ctx: ApiCtx): Promise<void> {+ if (!ctx.deps.config) return sendJson(ctx.res, 404, { error: "not_found" });+ const target = await runtimeTarget(ctx);+ if (!target) return sendJson(ctx.res, 403, { error: "forbidden" });+ const [on, configured, def] = await Promise.all([+ ctx.deps.config.getChannelHeaderPinDurable(target.scope),+ ctx.deps.config.getChannelHeaderPinOverrideDurable(target.scope),+ ctx.deps.config.getChannelHeaderPinDefaultDurable(),+ ]);+ return sendJson(ctx.res, 200, { scopeId: target.scope, on, configured, default: def });+}++async function putChannelHeaderPin(ctx: ApiCtx): Promise<void> {+ if (!ctx.deps.config || !isObj(ctx.body)) return sendJson(ctx.res, 400, { error: "bad_request" });+ if (ctx.capability && !livePersonCapability(ctx.capability))+ return sendJson(ctx.res, 403, { error: "live_actor_required" });+ const target = await runtimeTarget(ctx);+ if (!target) return sendJson(ctx.res, 403, { error: "forbidden" });+ if (typeof ctx.body.on !== "boolean" && ctx.body.on !== null)+ return sendJson(ctx.res, 400, {+ error: "bad_request",+ message: "expected { on: boolean | null } (null reverts to the org default)",+ });+ await ctx.deps.config.setChannelHeaderPinLatest(target.scope, ctx.body.on);+ audit(ctx.deps, {+ principalId: target.actorId,+ action: "channel-header-pin.update",+ resource: "channel-header-pin",+ scopeLabel: target.scope,+ });+ return sendJson(ctx.res, 200, {+ scopeId: target.scope,+ on: ctx.body.on ?? (await ctx.deps.config.getChannelHeaderPinDefaultDurable()),+ configured: ctx.body.on,+ });+}+function getSoul(ctx: ApiCtx): void {const { res, app, url, capability } = ctx;const scopeIdVal = capability?.scopeId ?? url.searchParams.get("scopeId");@@ -1408,6 +1445,8 @@ export const surfaceRoutes: ReadonlyArray<Route<ApiCtx>> = [{ method: "GET", path: "/v1/surface-config", auth: "source", handle: getSurfaceConfig },{ method: "GET", path: "/v1/runtime-config", auth: "either", handle: getRuntimeConfig },{ method: "PUT", path: "/v1/runtime-config", auth: "either", handle: putRuntimeConfig },+ { method: "GET", path: "/v1/channel-header-pin", auth: "either", handle: getChannelHeaderPin },+ { method: "PUT", path: "/v1/channel-header-pin", auth: "either", handle: putChannelHeaderPin },{ method: "GET", path: "/v1/soul", auth: "either", handle: getSoul },{ method: "POST", path: "/v1/soul", auth: "either", handle: postSoul },];diff --git a/src/api/slack-core-client.ts b/src/api/slack-core-client.tsindex 67f88aa97..43d231d11 100644--- a/src/api/slack-core-client.ts+++ b/src/api/slack-core-client.ts@@ -56,7 +56,9 @@ interface DirectoryPush {export interface SlackCoreClient {externalSlackParticipants(): Promise<boolean>;surfaceHeaderFacts(scope: ScopeId): Promise<{ agentLabel?: string; modelName: string }>;+ channelHeaderPinEnabled(scope: ScopeId): Promise<boolean>;onScopeModelChanged(listener: (scope: ScopeId) => void): void;+ onChannelHeaderPinChanged(listener: (scope: ScopeId) => void): void;stageBlob(bytes: Uint8Array): Promise<{ blobId: string; sizeBytes: number }>;readBlob(blobId: string): Promise<Buffer>;readFileArtifact(artifactId: string, viewerId: string): Promise<Buffer>;@@ -137,10 +139,18 @@ export function createSlackCoreClient(deps: SlackCoreClientDeps): SlackCoreClienreturn { ...(agentLabel ? { agentLabel } : {}), modelName: modelDisplayName(choice.modelId) };},+ async channelHeaderPinEnabled(scope) {+ return deps.config.getChannelHeaderPinDurable(scope);+ },+onScopeModelChanged(listener) {deps.config.onRuntimeSelectionChanged((scope) => listener(scope));},+ onChannelHeaderPinChanged(listener) {+ deps.config.onChannelHeaderPinChanged((scope) => listener(scope));+ },+async stageBlob(bytes) {const sha256 = createHash("sha256").update(bytes).digest("hex");const info = await deps.blobTransfer.put(Readable.from([Buffer.from(bytes)]), {diff --git a/src/resolution/config-store.ts b/src/resolution/config-store.tsindex 66e029c72..c10273342 100644--- a/src/resolution/config-store.ts+++ b/src/resolution/config-store.ts@@ -159,6 +159,12 @@ export interface ScopedConfigStore {setExternalSlackParticipants(id: ScopeId, on: boolean): void;clearExternalSlackParticipants(id: ScopeId): void;getExternalSlackParticipantsDurable(id: ScopeId): Promise<boolean>;+ getChannelHeaderPin(id: ScopeId): boolean;+ setChannelHeaderPinLatest(id: ScopeId, on: boolean | null): Promise<void>;+ getChannelHeaderPinDurable(id: ScopeId): Promise<boolean>;+ getChannelHeaderPinOverrideDurable(id: ScopeId): Promise<boolean | null>;+ getChannelHeaderPinDefaultDurable(): Promise<boolean>;+ onChannelHeaderPinChanged(listener: (id: ScopeId) => void): void;getBaseModel(id: ScopeId): string | null;setBaseModel(id: ScopeId, modelId: string | null): void;getRuntimeSelection(id: ScopeId): ScopedRuntimeSelection | null;@@ -215,6 +221,7 @@ export function createMemoryConfigStore(egressPolicies?: DurableMap<PersistedEgressPolicy>;unfulfilledInsights?: DurableMap<PersistedScopedFlag>;externalSlackParticipants?: DurableMap<PersistedScopedFlag>;+ channelHeaderPin?: DurableMap<PersistedScopedFlag>;baseModels?: DurableMap<PersistedBaseModel>;approvedHarnesses?: DurableMap<PersistedApprovedHarnesses>;orgAmbient?: DurableMap<PersistedScopedFlag>;@@ -239,6 +246,7 @@ export function createMemoryConfigStore(const egress = new Map<ScopeId, EgressPolicy>();const unfulfilledInsights = new Map<ScopeId, boolean>();const externalSlackParticipants = new Map<ScopeId, boolean>();+ const channelHeaderPin = new Map<ScopeId, boolean>();const baseModels = new Map<ScopeId, PersistedBaseModel>();let approvedHarnesses: string[] | null = null;let orgAmbient = true;@@ -257,6 +265,7 @@ export function createMemoryConfigStore(const egressStore = opts.egressPolicies ?? createMemoryMap<PersistedEgressPolicy>();const unfulfilledInsightsStore = opts.unfulfilledInsights ?? createMemoryMap<PersistedScopedFlag>();const externalSlackParticipantsStore = opts.externalSlackParticipants ?? createMemoryMap<PersistedScopedFlag>();+ const channelHeaderPinStore = opts.channelHeaderPin ?? createMemoryMap<PersistedScopedFlag>();const baseModelStore = opts.baseModels ?? createMemoryMap<PersistedBaseModel>();const approvedHarnessStore = opts.approvedHarnesses ?? createMemoryMap<PersistedApprovedHarnesses>();const orgAmbientStore = opts.orgAmbient ?? createMemoryMap<PersistedScopedFlag>();@@ -281,6 +290,16 @@ export function createMemoryConfigStore(pendingWrites.set(key, pending);void pending.catch(persistWarn(what));};+ const channelHeaderPinListeners = new Set<(id: ScopeId) => void>();+ const noteChannelHeaderPinChanged = (id: ScopeId): void => {+ for (const listener of channelHeaderPinListeners) {+ try {+ listener(id);+ } catch (e) {+ console.error("[config] channel-header-pin listener failed:", errMessage(e));+ }+ }+ };const runtimeSelectionListeners = new Set<(id: ScopeId) => void>();const noteRuntimeSelectionChanged = (id: ScopeId): void => {for (const listener of runtimeSelectionListeners) {@@ -397,6 +416,7 @@ export function createMemoryConfigStore(for (const r of await egressStore.all()) egress.set(r.scopeId, r.policy);for (const r of await unfulfilledInsightsStore.all()) unfulfilledInsights.set(r.scopeId, r.on);for (const r of await externalSlackParticipantsStore.all()) externalSlackParticipants.set(r.scopeId, r.on);+ for (const r of await channelHeaderPinStore.all()) channelHeaderPin.set(r.scopeId, r.on);for (const r of await baseModelStore.all()) baseModels.set(r.scopeId, r);approvedHarnesses = (await approvedHarnessStore.get(org))?.ids ?? null;orgAmbient = (await orgAmbientStore.get(org))?.on ?? true;@@ -635,6 +655,24 @@ export function createMemoryConfigStore(getExternalSlackParticipantsDurable: async (id) =>((await externalSlackParticipantsStore.get(org))?.on ?? false) ||((await externalSlackParticipantsStore.get(id))?.on ?? false),+ getChannelHeaderPin: (id) => channelHeaderPin.get(id) ?? channelHeaderPin.get(org) ?? false,+ async setChannelHeaderPinLatest(id, on) {+ await writeQueue(`channelHeaderPin:${id}`, async () => {+ if (on === null) await channelHeaderPinStore.delete(id);+ else await channelHeaderPinStore.put(id, { scopeId: id, on });+ if (on === null) channelHeaderPin.delete(id);+ else channelHeaderPin.set(id, on);+ });+ noteChannelHeaderPinChanged(id);+ },+ getChannelHeaderPinDurable: async (id) =>+ (await channelHeaderPinStore.get(id))?.on ??+ (id === org ? false : ((await channelHeaderPinStore.get(org))?.on ?? false)),+ getChannelHeaderPinOverrideDurable: async (id) => (await channelHeaderPinStore.get(id))?.on ?? null,+ getChannelHeaderPinDefaultDurable: async () => (await channelHeaderPinStore.get(org))?.on ?? false,+ onChannelHeaderPinChanged(listener) {+ channelHeaderPinListeners.add(listener);+ },getBaseModel: (id) => baseModels.get(id)?.modelId ?? null,setBaseModel(id, modelId) {if (modelId === null) {@@ -903,6 +941,7 @@ export function createMemoryConfigStore(brandingRow,orgAmbientRow,interactiveFastModeRow,+ channelHeaderPinRow,] = await Promise.all([soulStore.get(id),commandPolicyStore.get(id),@@ -916,6 +955,7 @@ export function createMemoryConfigStore(brandingStore.get(id),id === org ? orgAmbientStore.get(org) : null,id === org ? interactiveFastModeStore.get(org) : null,+ channelHeaderPinStore.get(id),]);let refreshedSoul = soul;const legacyHistory = legacySoulHistory.get(id) ?? [];@@ -956,6 +996,8 @@ export function createMemoryConfigStore(if (id === org) interactiveFastMode = interactiveFastModeRow?.on ?? false;if (brandingRow) branding.set(id, brandingRow.branding);else branding.delete(id);+ if (channelHeaderPinRow) channelHeaderPin.set(id, channelHeaderPinRow.on);+ else channelHeaderPin.delete(id);},async flushScope(id) {const keys = [@@ -969,6 +1011,8 @@ export function createMemoryConfigStore(`turnWallClock:${id}`,`branding:${id}`,...(id === org ? [`approvedHarnesses:${org}`, `orgAmbient:${org}`, `interactiveFastMode:${org}`] : []),+ `channelHeaderPin:${id}`,+ ...(id === org ? [`approvedHarnesses:${org}`, `orgAmbient:${org}`] : []),];await Promise.all(keys.map(async (key) => {diff --git a/src/slack/delivery.ts b/src/slack/delivery.tsindex 8f4a2f5cc..242abd961 100644--- a/src/slack/delivery.ts+++ b/src/slack/delivery.ts@@ -77,14 +77,10 @@ export function channelWelcomeMessage(surfaceUrl: string | undefined): string {return `Hi! I'm the agent for this channel. Everyone here can see and manage what I'm doing — scheduled jobs, skills, files, and apps — on this channel's shared page: ${surfaceUrl}`;}-export function surfaceHeaderText(- facts: { agentLabel?: string; modelName?: string },- projectUrl: string | undefined,-): string | undefined {- const agent = (facts.agentLabel ?? "").trim();+export function surfaceHeaderText(facts: { modelName?: string }, projectUrl: string | undefined): string | undefined {const model = (facts.modelName ?? "").trim();const url = (projectUrl ?? "").trim();- const modelText = model ? `${agent ? `${agent} is using` : "Using"} ${model} here.` : "";+ const modelText = model ? `Using ${model} here.` : "";const link = url ? `<${url}|More settings>` : "";return [modelText, link].filter(Boolean).join(" ") || undefined;}@@ -107,26 +103,66 @@ export function headerUpdate(const SURFACE_HEADER_MAX_TRACKED = 1000;export interface SurfaceHeaderClient {+ chat: {+ postMessage: (args: SlackReplyArgs) => Promise<{ ts?: string }>;+ update: (args: { channel: string; ts: string; text: string }) => Promise<unknown>;+ delete: (args: { channel: string; ts: string }) => Promise<unknown>;+ };+ pins: {+ list: (args: { channel: string }) => Promise<{ items?: PinnedItem[] }>;+ add: (args: { channel: string; timestamp: string }) => Promise<unknown>;+ remove: (args: { channel: string; timestamp: string }) => Promise<unknown>;+ };conversations: {info: (args: { channel: string }) => Promise<{ channel?: ChannelMeta }>;setTopic: (args: { channel: string; topic: string }) => Promise<unknown>;- setPurpose: (args: { channel: string; purpose: string }) => Promise<unknown>;};}+export interface PinnedItem {+ message?: { ts?: string; user?: string; text?: string };+}++export function isSurfaceHeaderMessage(text: string | undefined): boolean {+ const t = (text ?? "").trim();+ if (!t) return false;+ return /^(Using .+ here\.)?\s*(<[^<>|]+\|More settings>)?$/.test(t);+}++export function findHeaderPin(+ items: PinnedItem[] | undefined,+ botUserId: string,+): { ts: string; text: string } | undefined {+ for (const item of items ?? []) {+ const m = item.message;+ if (m?.ts && m.user === botUserId && isSurfaceHeaderMessage(m.text)) return { ts: m.ts, text: m.text ?? "" };+ }+ return undefined;+}++const HEADER_PIN_OFF = "<surface-header-off>";+export function createSurfaceHeaderEnsurer(opts: {headerFacts(scope: string): Promise<{ agentLabel?: string; modelName: string }>;+ channelPinEnabled?(scope: string): Promise<boolean>;webUiPublicUrl: string | undefined;ids: { botUserId: string };maxTracked?: number;-}): (client: SurfaceHeaderClient, channel: string, scopeId: string, kind: "dm" | "channel") => void {+}): (+ client: SurfaceHeaderClient,+ channel: string,+ scopeId: string,+ kind: "dm" | "channel",+ ensureOpts?: { pinNew?: boolean },+) => void {const maxTracked = opts.maxTracked ?? SURFACE_HEADER_MAX_TRACKED;const settled = new Map<string, string>();const inFlight = new Set<string>();- const requeued = new Set<string>();- return function ensure(client, channel, scopeId, kind) {+ const requeued = new Map<string, { pinNew?: boolean }>();+ return function ensure(client, channel, scopeId, kind, ensureOpts) {if (inFlight.has(channel)) {- requeued.add(channel);+ const prior = requeued.get(channel);+ requeued.set(channel, { pinNew: Boolean(prior?.pinNew) || Boolean(ensureOpts?.pinNew) });return;}inFlight.add(channel);@@ -136,21 +172,43 @@ export function createSurfaceHeaderEnsurer(opts: {await opts.headerFacts(scopeId),scopeSurfaceUrl(opts.webUiPublicUrl, scopeId),);- if (!desired || settled.get(channel) === desired) return;+ if (!desired) return;+ const enabled = kind === "dm" || ((await opts.channelPinEnabled?.(scopeId)) ?? false);+ const goal = enabled ? desired : HEADER_PIN_OFF;+ if (settled.get(channel) === goal) return;const info = (await client.conversations.info({ channel })).channel;- if (kind === "channel" && (isExternallyShared(info) || isMpim(info))) return;- const existing = kind === "dm" ? info?.topic : info?.purpose;- if (headerUpdate(existing, opts.ids.botUserId, desired) === "set") {- if (kind === "dm") await client.conversations.setTopic({ channel, topic: desired });- else await client.conversations.setPurpose({ channel, purpose: desired });+ if (kind === "dm") {+ if (headerUpdate(info?.topic, opts.ids.botUserId, desired) === "set")+ await client.conversations.setTopic({ channel, topic: desired });+ } else {+ if (isExternallyShared(info) || isMpim(info)) return;+ const pinned = findHeaderPin((await client.pins.list({ channel })).items, opts.ids.botUserId);+ if (!enabled) {+ if (pinned) {+ await client.pins.remove({ channel, timestamp: pinned.ts });+ await client.chat.delete({ channel, ts: pinned.ts });+ }+ } else if (pinned) {+ if (unwrapSlackLinks(pinned.text) !== unwrapSlackLinks(desired))+ await client.chat.update({ channel, ts: pinned.ts, text: desired });+ } else if (ensureOpts?.pinNew) {+ const posted = await client.chat.postMessage(+ slackReplyArgs(channel, desired, undefined, { unfurlLinks: false }),+ );+ if (posted.ts) await client.pins.add({ channel, timestamp: posted.ts });+ }}- settled.set(channel, desired);+ settled.set(channel, goal);capMap(settled, maxTracked);} catch (err) {console.error("[slack] surface header ensure failed:", errMessage(err));} finally {inFlight.delete(channel);- if (requeued.delete(channel)) ensure(client, channel, scopeId, kind);+ const again = requeued.get(channel);+ if (again) {+ requeued.delete(channel);+ ensure(client, channel, scopeId, kind, again);+ }}})();};@@ -161,7 +219,6 @@ export async function onBotJoinedChannel(opts: {chat: { postMessage: (args: SlackReplyArgs) => Promise<unknown> };conversations: {info: (args: { channel: string }) => Promise<{ channel?: ChannelMeta }>;- setPurpose: (args: { channel: string; purpose: string }) => Promise<unknown>;};};channel: string | undefined;diff --git a/src/slack/events.ts b/src/slack/events.tsindex 3deffafa1..cca6f5415 100644--- a/src/slack/events.ts+++ b/src/slack/events.ts@@ -27,7 +27,13 @@ export function registerSlackEvents(ids: BotIdentity;deduper: ReturnType<typeof createDeduper>;webUiPublicUrl?: string;- ensureHeader?: (client: SurfaceHeaderClient, channel: string, scopeId: string, kind: "dm" | "channel") => void;+ ensureHeader?: (+ client: SurfaceHeaderClient,+ channel: string,+ scopeId: string,+ kind: "dm" | "channel",+ ensureOpts?: { pinNew?: boolean },+ ) => void;},): void {const { handler, mirror, directory, ids, deduper } = deps;@@ -184,7 +190,9 @@ export function registerSlackEvents(...(deps.ensureHeader? {ensureHeader: (channel: string) =>- deps.ensureHeader!(client as SurfaceHeaderClient, channel, `channel:${channel}`, "channel"),+ deps.ensureHeader!(client as SurfaceHeaderClient, channel, `channel:${channel}`, "channel", {+ pinNew: true,+ }),}: {}),});diff --git a/src/slack/index.ts b/src/slack/index.tsindex 6160d6553..7d0180f1b 100644--- a/src/slack/index.ts+++ b/src/slack/index.ts@@ -1,4 +1,4 @@-import { swallow, swallowAs } from "../util/errors.ts";+import { errMessage, swallow, swallowAs } from "../util/errors.ts";import bolt from "@slack/bolt";import { WebClient } from "@slack/web-api";import { createDeduper, createThreadTracker } from "./lib.ts";@@ -131,6 +131,8 @@ export async function startSlackPlugin(const approvals = createApprovals({ core, bridge, directory, threads });const ensureHeader = createSurfaceHeaderEnsurer({headerFacts: (scope) => core.surfaceHeaderFacts(scope as Parameters<typeof core.surfaceHeaderFacts>[0]),+ channelPinEnabled: (scope) =>+ core.channelHeaderPinEnabled(scope as Parameters<typeof core.channelHeaderPinEnabled>[0]),webUiPublicUrl: cfg.webUiPublicUrl,ids,});@@ -138,6 +140,35 @@ export async function startSlackPlugin(const channel = scope.startsWith("channel:") ? scope.slice("channel:".length) : "";if (channel) ensureHeader(app.client as unknown as SurfaceHeaderClient, channel, scope, "channel");});+ core.onChannelHeaderPinChanged((scope) => {+ const channel = scope.startsWith("channel:") ? scope.slice("channel:".length) : "";+ if (channel) {+ ensureHeader(app.client as unknown as SurfaceHeaderClient, channel, scope, "channel", { pinNew: true });+ return;+ }+ if (!scope.startsWith("org:")) return;+ // The org-wide default changed: re-ensure every channel the bot is in. The+ // ensurer re-reads each scope's effective setting, so explicit per-channel+ // overrides come out unchanged.+ void (async () => {+ try {+ for await (const res of (app.client as any).paginate("conversations.list", {+ types: "public_channel,private_channel",+ exclude_archived: true,+ limit: 1000,+ }) as AsyncIterable<{ channels?: Array<{ id?: string; is_member?: boolean }> }>) {+ for (const c of res.channels ?? []) {+ if (!c?.id || !c.is_member) continue;+ ensureHeader(app.client as unknown as SurfaceHeaderClient, c.id, `channel:${c.id}`, "channel", {+ pinNew: true,+ });+ }+ }+ } catch (err) {+ console.error("[slack] channel header default sweep failed:", errMessage(err));+ }+ })();+ });const handler = createTurnHandler({bridge,directory,diff --git a/src/slack/lib.ts b/src/slack/lib.tsindex d0d33980a..3503667c2 100644--- a/src/slack/lib.ts+++ b/src/slack/lib.ts@@ -118,6 +118,8 @@ export {channelWelcomeMessage,surfaceHeaderText,headerUpdate,+ isSurfaceHeaderMessage,+ findHeaderPin,createSurfaceHeaderEnsurer,scopeSurfaceUrl,type SurfaceHeaderClient,diff --git a/src/slack/manifest.json b/src/slack/manifest.jsonindex f222b2a0e..4434a964a 100644--- a/src/slack/manifest.json+++ b/src/slack/manifest.json@@ -39,6 +39,8 @@"files:write","reactions:write","reactions:read",+ "pins:read",+ "pins:write","emoji:read"]}diff --git a/src/slack/turn-handler.ts b/src/slack/turn-handler.tsindex 0214c17a9..9267b88a1 100644--- a/src/slack/turn-handler.ts+++ b/src/slack/turn-handler.ts@@ -132,7 +132,13 @@ export function createTurnHandler(deps: {markEvent?: () => void;botToken: string;trustedFileHost?: string;- ensureHeader?: (client: SurfaceHeaderClient, channel: string, scopeId: string, kind: "dm" | "channel") => void;+ ensureHeader?: (+ client: SurfaceHeaderClient,+ channel: string,+ scopeId: string,+ kind: "dm" | "channel",+ ensureOpts?: { pinNew?: boolean },+ ) => void;}): TurnHandler {const {bridge,diff --git a/src/wiring.ts b/src/wiring.tsindex a92c23a41..d48b76e84 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -434,6 +434,7 @@ export function buildApp(egressPolicies: artifactMap<PersistedEgressPolicy>("egress_policies"),unfulfilledInsights: artifactMap<PersistedScopedFlag>("unfulfilled_insights_flag"),externalSlackParticipants: artifactMap<PersistedScopedFlag>("external_slack_participants_flag"),+ channelHeaderPin: artifactMap<PersistedScopedFlag>("channel_header_pin_flag"),baseModels: artifactMap<PersistedBaseModel>("base_model_configs"),approvedHarnesses: artifactMap<PersistedApprovedHarnesses>("approved_harness_configs"),orgAmbient: artifactMap<PersistedScopedFlag>("org_ambient_flag"),diff --git a/test/channel-header-pin-default.test.ts b/test/channel-header-pin-default.test.tsnew file mode 100644index 000000000..7ade1719c--- /dev/null+++ b/test/channel-header-pin-default.test.ts@@ -0,0 +1,70 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { createMemoryConfigStore } from "../src/resolution/config-store.ts";+import { scopeId, type ScopeId } from "../src/types.ts";++const org = scopeId("org", "acme");+const channel = "channel:C123" as ScopeId;+const other = "channel:C456" as ScopeId;++async function freshStore() {+ const store = createMemoryConfigStore("acme", {});+ await store.hydrate!();+ return store;+}++test("channel header pin defaults off with no org setting", async () => {+ const store = await freshStore();+ assert.equal(store.getChannelHeaderPin(channel), false);+ assert.equal(await store.getChannelHeaderPinDurable(channel), false);+ assert.equal(await store.getChannelHeaderPinDefaultDurable(), false);+});++test("an org default of on applies to channels without an explicit choice", async () => {+ const store = await freshStore();+ await store.setChannelHeaderPinLatest(org, true);+ assert.equal(store.getChannelHeaderPin(channel), true);+ assert.equal(await store.getChannelHeaderPinDurable(channel), true);+ assert.equal(await store.getChannelHeaderPinDefaultDurable(), true);+ assert.equal(await store.getChannelHeaderPinOverrideDurable(channel), null);+});++test("an explicit channel off beats an org default of on", async () => {+ const store = await freshStore();+ await store.setChannelHeaderPinLatest(org, true);+ await store.setChannelHeaderPinLatest(channel, false);+ assert.equal(store.getChannelHeaderPin(channel), false);+ assert.equal(await store.getChannelHeaderPinDurable(channel), false);+ assert.equal(await store.getChannelHeaderPinOverrideDurable(channel), false);+ // other channels still follow the default+ assert.equal(await store.getChannelHeaderPinDurable(other), true);+});++test("clearing a channel override reverts it to the org default", async () => {+ const store = await freshStore();+ await store.setChannelHeaderPinLatest(org, true);+ await store.setChannelHeaderPinLatest(channel, false);+ await store.setChannelHeaderPinLatest(channel, null);+ assert.equal(await store.getChannelHeaderPinDurable(channel), true);+ assert.equal(await store.getChannelHeaderPinOverrideDurable(channel), null);+});++test("changing the org default notifies listeners with the org scope", async () => {+ const store = await freshStore();+ const seen: ScopeId[] = [];+ store.onChannelHeaderPinChanged((id) => seen.push(id));+ await store.setChannelHeaderPinLatest(org, true);+ await store.setChannelHeaderPinLatest(channel, true);+ assert.deepEqual(seen, [org, channel]);+});++test("explicit overrides survive a scope refresh", async () => {+ const store = await freshStore();+ await store.setChannelHeaderPinLatest(org, true);+ await store.setChannelHeaderPinLatest(channel, false);+ await store.refreshScope(channel);+ assert.equal(store.getChannelHeaderPin(channel), false);+ await store.setChannelHeaderPinLatest(channel, null);+ await store.refreshScope(channel);+ assert.equal(store.getChannelHeaderPin(channel), true);+});diff --git a/test/slack-delivery.test.ts b/test/slack-delivery.test.tsindex 5eb0405fc..d1dc8ac38 100644--- a/test/slack-delivery.test.ts+++ b/test/slack-delivery.test.ts@@ -14,6 +14,8 @@ import {channelWelcomeMessage,surfaceHeaderText,headerUpdate,+ isSurfaceHeaderMessage,+ findHeaderPin,createSurfaceHeaderEnsurer,scopeSurfaceUrl,onBotJoinedChannel,@@ -202,15 +204,12 @@ const BOT = "UBOT";function fakeJoinClient(opts: {- setPurposeFails?: boolean;postMessageFails?: boolean;extShared?: boolean;- existingPurpose?: string;} = {},) {const calls = {posted: [] as Array<{ channel: string; text: string }>,- purposes: [] as Array<{ channel: string; purpose: string }>,};return {calls,@@ -230,18 +229,8 @@ function fakeJoinClient(info: async (_args: { channel: string }) => ({channel: {is_ext_shared: Boolean(opts.extShared),- ...(opts.existingPurpose !== undefined ? { purpose: { value: opts.existingPurpose } } : {}),},}),- setPurpose: async (args: { channel: string; purpose: string }) => {- if (opts.setPurposeFails) {- const err = new Error("missing_scope") as Error & { data?: unknown };- err.data = { error: "missing_scope" };- throw err;- }- calls.purposes.push(args);- return {};- },},},};@@ -262,9 +251,10 @@ test("channelWelcomeMessage includes the link when present, omits it cleanly wheassert.ok(linkless.length > 0);});-test("onBotJoinedChannel: posts welcome with the deep link and sets the description when the bot joins", async () => {+test("onBotJoinedChannel: posts welcome with the deep link and asks the ensurer to pin the header", async () => {const { client, calls } = fakeJoinClient();let synced = 0;+ const ensured: string[] = [];await onBotJoinedChannel({client,channel: "C123",@@ -274,12 +264,13 @@ test("onBotJoinedChannel: posts welcome with the deep link and sets the descriptsyncDirectory: async () => {synced++;},+ ensureHeader: (channel) => ensured.push(channel),});const expectedUrl = `${WEB_BASE}/projects/channel/C123`;assert.equal(calls.posted.length, 1);assert.equal(calls.posted[0]!.channel, "C123");assert.ok(calls.posted[0]!.text.includes(expectedUrl), "welcome message must contain the channel surface deep link");- assert.equal(calls.purposes.length, 0, "the description is the header ensurer's to write, not join's");+ assert.deepEqual(ensured, ["C123"], "the pinned header is the ensurer's to post, not join's");assert.equal(synced, 1, "directory sync must run on bot join");});@@ -297,12 +288,11 @@ test("onBotJoinedChannel: ignores a human joining (only the bot itself triggers},});assert.equal(calls.posted.length, 0);- assert.equal(calls.purposes.length, 0);assert.equal(synced, 0);});-test("onBotJoinedChannel: a setPurpose failure is swallowed and never blocks the welcome or sync", async () => {- const { client, calls } = fakeJoinClient({ setPurposeFails: true });+test("onBotJoinedChannel: an ensureHeader failure is swallowed and never blocks the welcome or sync", async () => {+ const { client, calls } = fakeJoinClient();let synced = 0;await assert.doesNotReject(onBotJoinedChannel({@@ -314,11 +304,13 @@ test("onBotJoinedChannel: a setPurpose failure is swallowed and never blocks thesyncDirectory: async () => {synced++;},+ ensureHeader: () => {+ throw new Error("missing_scope");+ },}),);- assert.equal(calls.posted.length, 1, "welcome still lands even when setPurpose throws");- assert.equal(calls.purposes.length, 0, "the failed setPurpose recorded nothing");- assert.equal(synced, 1, "directory sync still runs after a swallowed setPurpose error");+ assert.equal(calls.posted.length, 1, "welcome still lands even when the header hook throws");+ assert.equal(synced, 1, "directory sync still runs after a swallowed header error");});test("onBotJoinedChannel: a welcome-post failure still runs the directory sync", async () => {@@ -340,24 +332,6 @@ test("onBotJoinedChannel: a welcome-post failure still runs the directory sync",assert.equal(synced, 1, "directory sync still runs so members can reach the surface even if the welcome failed");});-test("onBotJoinedChannel: preserves a human-written channel purpose instead of clobbering it", async () => {- const { client, calls } = fakeJoinClient({ existingPurpose: "Engineering on-call rotation" });- let synced = 0;- await onBotJoinedChannel({- client,- channel: "C123",- joinerUserId: BOT,- botUserId: BOT,- webUiPublicUrl: WEB_BASE,- syncDirectory: async () => {- synced++;- },- });- assert.equal(calls.posted.length, 1, "welcome still lands");- assert.equal(calls.purposes.length, 0, "an existing purpose is never overwritten");- assert.equal(synced, 1, "directory sync still runs");-});-test("onBotJoinedChannel: stays silent in an externally-shared (Slack Connect) channel — no welcome, no purpose", async () => {const { client, calls } = fakeJoinClient({ extShared: true });let synced = 0;@@ -372,12 +346,11 @@ test("onBotJoinedChannel: stays silent in an externally-shared (Slack Connect) c},});assert.equal(calls.posted.length, 0, "the bot never posts into a Connect channel (an external could see it)");- assert.equal(calls.purposes.length, 0, "the bot never writes a description in a Connect channel");assert.equal(synced, 1, "directory sync (which never emits into the channel) still runs");});-test("onBotJoinedChannel: welcomes a normal internal channel and hands the description to the header ensurer", async () => {- const { client, calls } = fakeJoinClient({ existingPurpose: "" });+test("onBotJoinedChannel: welcomes a normal internal channel and hands the pinned header to the ensurer", async () => {+ const { client, calls } = fakeJoinClient();let synced = 0;const ensured: string[] = [];await onBotJoinedChannel({@@ -395,7 +368,6 @@ test("onBotJoinedChannel: welcomes a normal internal channel and hands the descrassert.equal(calls.posted.length, 1, "welcome lands on a normal internal channel");assert.ok(calls.posted[0]!.text.includes(expectedUrl), "welcome message contains the project deep link");assert.deepEqual(ensured, ["C123"], "join triggers exactly one header ensure");- assert.equal(calls.purposes.length, 0, "join no longer writes a second, competing description");assert.equal(synced, 1, "directory sync runs");});@@ -569,25 +541,39 @@ test("postWithVerify: threaded post verifies via conversations.replies", async (assert.equal(h.historyCalled, false, "threaded verify reads replies, not history");});-test("surfaceHeaderText names the agent, its model, and the project link — degrading gracefully", () => {- assert.equal(- surfaceHeaderText(- { agentLabel: "Quartermaster", modelName: "Claude Opus 4.8" },- "https://claw.acme.dev/projects/channel/C1",- ),- "Quartermaster is using Claude Opus 4.8 here. <https://claw.acme.dev/projects/channel/C1|More settings>",- );- assert.equal(- surfaceHeaderText({ agentLabel: "QM", modelName: "Claude Opus 4.8" }, undefined),- "QM is using Claude Opus 4.8 here.",- );+test("surfaceHeaderText names the model and the project link without branding — degrading gracefully", () => {assert.equal(- surfaceHeaderText({ modelName: "Claude Opus 4.8" }, undefined),- "Using Claude Opus 4.8 here.",- "an unbranded deployment keeps the bare model line",+ surfaceHeaderText({ modelName: "Claude Opus 4.8" }, "https://claw.acme.dev/projects/channel/C1"),+ "Using Claude Opus 4.8 here. <https://claw.acme.dev/projects/channel/C1|More settings>",);+ assert.equal(surfaceHeaderText({ modelName: "Claude Opus 4.8" }, undefined), "Using Claude Opus 4.8 here.");assert.equal(surfaceHeaderText({}, "https://claw.acme.dev"), "<https://claw.acme.dev|More settings>");- assert.equal(surfaceHeaderText({ agentLabel: "QM", modelName: " " }, " "), undefined);+ assert.equal(surfaceHeaderText({ modelName: " " }, " "), undefined);+});++test("isSurfaceHeaderMessage recognizes only the bot's own header shapes", () => {+ assert.ok(isSurfaceHeaderMessage("Using Claude Opus 4.8 here. <https://claw.acme.dev|More settings>"));+ assert.ok(isSurfaceHeaderMessage("Using Claude Opus 4.8 here."));+ assert.ok(isSurfaceHeaderMessage("<https://claw.acme.dev|More settings>"));+ assert.ok(!isSurfaceHeaderMessage("Reminder: standup at 10"));+ assert.ok(!isSurfaceHeaderMessage(""));+ assert.ok(!isSurfaceHeaderMessage(undefined));+});++test("findHeaderPin picks only the bot's own pinned header message", () => {+ const items = [+ { message: { ts: "1.0", user: "U0HUMAN", text: "Using X here." } },+ { message: { ts: "2.0", user: "U0BOT", text: "team norms doc" } },+ {+ message: { ts: "3.0", user: "U0BOT", text: "Using Claude Opus 4.8 here. <https://claw.acme.dev|More settings>" },+ },+ ];+ assert.deepEqual(findHeaderPin(items, "U0BOT"), {+ ts: "3.0",+ text: "Using Claude Opus 4.8 here. <https://claw.acme.dev|More settings>",+ });+ assert.equal(findHeaderPin(items, "U0OTHER"), undefined);+ assert.equal(findHeaderPin(undefined, "U0BOT"), undefined);});test("headerUpdate rewrites only an empty or self-authored header", () => {@@ -608,39 +594,79 @@ function headerHarness(existing?: { value?: string; creator?: string },model = "Claude Opus 4.8",kind: "dm" | "channel" = "dm",+ pinnedText?: string,) {- const calls = { info: 0, set: 0 };+ const calls = {+ info: 0,+ set: 0,+ pinsListed: 0,+ posted: [] as string[],+ updated: [] as string[],+ pinned: [] as string[],+ unpinned: [] as string[],+ deleted: [] as string[],+ };let current = existing;+ let pinned = pinnedText !== undefined ? { ts: "42.0", user: "U0BOT", text: pinnedText } : undefined;const client = {+ chat: {+ postMessage: async ({ text }: { text: string }) => {+ calls.posted.push(text);+ pinned = { ts: "99.0", user: "U0BOT", text };+ return { ts: "99.0" };+ },+ update: async ({ ts, text }: { ts: string; text: string }) => {+ calls.updated.push(text);+ if (pinned && pinned.ts === ts) pinned = { ...pinned, text };+ return {};+ },+ delete: async ({ ts }: { ts: string }) => {+ calls.deleted.push(ts);+ if (pinned && pinned.ts === ts) pinned = undefined;+ return {};+ },+ },+ pins: {+ list: async () => {+ calls.pinsListed += 1;+ return { items: pinned ? [{ message: pinned }] : [] };+ },+ add: async ({ timestamp }: { timestamp: string }) => {+ calls.pinned.push(timestamp);+ return {};+ },+ remove: async ({ timestamp }: { timestamp: string }) => {+ calls.unpinned.push(timestamp);+ return {};+ },+ },conversations: {info: async () => {calls.info += 1;if (!current) return { channel: {} };- return { channel: kind === "dm" ? { topic: current } : { purpose: current } };+ return { channel: kind === "dm" ? { topic: current } : {} };},setTopic: async ({ topic: value }: { channel: string; topic: string }) => {calls.set += 1;current = { value, creator: "U0BOT" };return {};},- setPurpose: async ({ purpose: value }: { channel: string; purpose: string }) => {- calls.set += 1;- current = { value, creator: "U0BOT" };- return {};- },},};+ const flags = { channelPinEnabled: true };const raw = createSurfaceHeaderEnsurer({- headerFacts: async () => ({ agentLabel: "Quartermaster", modelName: model }),+ headerFacts: async () => ({ modelName: model }),+ channelPinEnabled: async () => flags.channelPinEnabled,webUiPublicUrl: "https://claw.acme.dev",ids: { botUserId: "U0BOT" },});- const scope = kind === "dm" ? "personal:[email protected]" : "channel:C1";- const ensure = (c: unknown, channel: string) => raw(c as never, channel, scope, kind);+ const scope = kind === "dm" ? "personal:[email protected]" : "channel:C1";+ const ensure = (c: unknown, channel: string, ensureOpts?: { pinNew?: boolean }) =>+ raw(c as never, channel, scope, kind, ensureOpts);const flush = async (): Promise<void> => {for (let i = 0; i < 12; i++) await Promise.resolve();};- return { client, calls, ensure, flush, read: () => current, scope };+ return { client, calls, ensure, flush, read: () => current, readPin: () => pinned, scope, flags };}test("surface header ensurer writes the header once, then goes quiet", async () => {@@ -648,10 +674,7 @@ test("surface header ensurer writes the header once, then goes quiet", async ()h.ensure(h.client, "D1");await h.flush();assert.equal(h.calls.set, 1);- assert.equal(- h.read()?.value,- "Quartermaster is using Claude Opus 4.8 here. <https://claw.acme.dev/projects/user.one|More settings>",- );+ assert.equal(h.read()?.value, "Using Claude Opus 4.8 here. <https://claw.acme.dev/projects/josh|More settings>");h.ensure(h.client, "D1");await h.flush();assert.equal(h.calls.info, 1, "the settled memo spares a steady-state DM both calls");@@ -675,7 +698,8 @@ test("surface header ensurer collapses a burst on one channel into a single writ},};const ensure = createSurfaceHeaderEnsurer({- headerFacts: async () => ({ agentLabel: "Quartermaster", modelName: "Claude Opus 4.8" }),+ headerFacts: async () => ({ modelName: "Claude Opus 4.8" }),+ channelPinEnabled: async () => true,webUiPublicUrl: "https://claw.acme.dev",ids: { botUserId: "U0BOT" },});@@ -687,32 +711,47 @@ test("surface header ensurer collapses a burst on one channel into a single writtest("a model change during an in-flight ensure is re-run, not dropped", async () => {let model = "Claude Opus 4.8";- const purposes: string[] = [];+ const writes: string[] = [];+ let pinned: { ts: string; user: string; text: string } | undefined;const client = {+ chat: {+ postMessage: async ({ text }: { text: string }) => {+ writes.push(text);+ pinned = { ts: "9.0", user: "U0BOT", text };+ return { ts: "9.0" };+ },+ update: async ({ text }: { text: string }) => {+ writes.push(text);+ if (pinned) pinned = { ...pinned, text };+ return {};+ },+ },+ pins: {+ list: async () => ({ items: pinned ? [{ message: pinned }] : [] }),+ add: async () => ({}),+ },conversations: {info: async () => {await new Promise((r) => setTimeout(r, 15));- return { channel: { purpose: {} } };- },- setPurpose: async ({ purpose }: { channel: string; purpose: string }) => {- purposes.push(purpose);- return {};+ return { channel: {} };},+ setTopic: async () => ({}),},};const ensure = createSurfaceHeaderEnsurer({- headerFacts: async () => ({ agentLabel: "QM", modelName: model }),+ headerFacts: async () => ({ modelName: model }),+ channelPinEnabled: async () => true,webUiPublicUrl: "https://claw.acme.dev",ids: { botUserId: "U0BOT" },});- ensure(client as any, "C1", "channel:C1", "channel");+ ensure(client as any, "C1", "channel:C1", "channel", { pinNew: true });model = "Claude Haiku 4.5";ensure(client as any, "C1", "channel:C1", "channel");await new Promise((r) => setTimeout(r, 150));assert.deepEqual(- purposes.map((p) => p.split(" <")[0]),- ["QM is using Claude Opus 4.8 here.", "QM is using Claude Haiku 4.5 here."],- "the change that landed mid-probe still reaches the description",+ writes.map((p) => p.split(" <")[0]),+ ["Using Claude Opus 4.8 here.", "Using Claude Haiku 4.5 here."],+ "the change that landed mid-probe still reaches the pinned header",);});@@ -721,7 +760,8 @@ test("surface header ensurer caps its per-channel memo", async () => {conversations: { info: async () => ({ channel: {} }), setTopic: async () => ({}) },};const ensure = createSurfaceHeaderEnsurer({- headerFacts: async () => ({ agentLabel: "Quartermaster", modelName: "Claude Opus 4.8" }),+ headerFacts: async () => ({ modelName: "Claude Opus 4.8" }),+ channelPinEnabled: async () => true,webUiPublicUrl: "https://claw.acme.dev",ids: { botUserId: "U0BOT" },maxTracked: 3,@@ -745,47 +785,184 @@ test("surface header ensurer caps its per-channel memo", async () => {assert.equal(reprobed, 1, "an evicted channel is re-probed, so the map cannot grow forever");});-test("surface header ensurer writes a channel's description, not its topic", async () => {+test("surface header ensurer posts and pins a channel's header message when asked to create it", async () => {const h = headerHarness(undefined, "Claude Opus 4.8", "channel");+ h.ensure(h.client, "C1", { pinNew: true });+ await h.flush();+ assert.equal(h.calls.set, 0, "a channel's topic and description are left alone");+ assert.deepEqual(h.calls.posted, [+ "Using Claude Opus 4.8 here. <https://claw.acme.dev/projects/channel/C1|More settings>",+ ]);+ assert.deepEqual(h.calls.pinned, ["99.0"], "the posted header message is pinned");+});++test("surface header ensurer updates an existing pinned header in place instead of reposting", async () => {+ const h = headerHarness(+ undefined,+ "Claude Haiku 4.5",+ "channel",+ "Using Claude Opus 4.8 here. <https://claw.acme.dev/projects/channel/C1|More settings>",+ );h.ensure(h.client, "C1");await h.flush();- assert.equal(h.calls.set, 1);- assert.equal(- h.read()?.value,- "Quartermaster is using Claude Opus 4.8 here. <https://claw.acme.dev/projects/channel/C1|More settings>",- "a channel shows ITS scope's default model and links to ITS project page",+ assert.deepEqual(h.calls.posted, [], "no new message when a pinned header already exists");+ assert.deepEqual(h.calls.updated, [+ "Using Claude Haiku 4.5 here. <https://claw.acme.dev/projects/channel/C1|More settings>",+ ]);+ assert.equal(h.readPin()?.text.startsWith("Using Claude Haiku 4.5"), true);+});++test("the pinned header is off by default — join creates nothing until the scope opts in", async () => {+ let wrote = 0;+ const client = {+ chat: {+ postMessage: async () => {+ wrote += 1;+ return { ts: "1.0" };+ },+ update: async () => {+ wrote += 1;+ return {};+ },+ delete: async () => ({}),+ },+ pins: {+ list: async () => ({ items: [] }),+ add: async () => {+ wrote += 1;+ return {};+ },+ remove: async () => ({}),+ },+ conversations: { info: async () => ({ channel: {} }), setTopic: async () => ({}) },+ };+ const ensure = createSurfaceHeaderEnsurer({+ headerFacts: async () => ({ modelName: "Claude Opus 4.8" }),+ webUiPublicUrl: "https://claw.acme.dev",+ ids: { botUserId: "U0BOT" },+ });+ ensure(client as any, "C1", "channel:C1", "channel", { pinNew: true });+ await new Promise((r) => setTimeout(r, 30));+ assert.equal(wrote, 0, "without an opt-in the join posts no header at all");+});++test("disabling the toggle unpins and deletes the bot's header message", async () => {+ const h = headerHarness(+ undefined,+ "Claude Opus 4.8",+ "channel",+ "Using Claude Opus 4.8 here. <https://claw.acme.dev/projects/channel/C1|More settings>",);+ h.flags.channelPinEnabled = false;+ h.ensure(h.client, "C1");+ await h.flush();+ assert.deepEqual(h.calls.unpinned, ["42.0"], "the header pin is removed");+ assert.deepEqual(h.calls.deleted, ["42.0"], "the header message is deleted");+ assert.equal(h.readPin(), undefined);+ assert.deepEqual(h.calls.posted, []);+});++test("re-enabling the toggle re-creates the pinned header on the next create-flagged ensure", async () => {+ const h = headerHarness(undefined, "Claude Opus 4.8", "channel");+ h.flags.channelPinEnabled = false;+ h.ensure(h.client, "C1", { pinNew: true });+ await h.flush();+ assert.deepEqual(h.calls.posted, [], "disabled: nothing posted");+ h.flags.channelPinEnabled = true;+ h.ensure(h.client, "C1", { pinNew: true });+ await h.flush();+ assert.deepEqual(h.calls.posted, [+ "Using Claude Opus 4.8 here. <https://claw.acme.dev/projects/channel/C1|More settings>",+ ]);+ assert.deepEqual(h.calls.pinned, ["99.0"]);+});++test("a DM topic ignores the channel toggle entirely", async () => {+ const h = headerHarness();+ h.flags.channelPinEnabled = false;+ h.ensure(h.client, "D1");+ await h.flush();+ assert.equal(h.calls.set, 1, "the DM topic is still written with the toggle off");+});++test("surface header ensurer never posts into an existing channel without the create flag", async () => {+ const h = headerHarness(undefined, "Claude Opus 4.8", "channel");+ h.ensure(h.client, "C1");+ await h.flush();+ assert.deepEqual(h.calls.posted, [], "no pinned header exists, and none may be created mid-conversation");+ assert.deepEqual(h.calls.updated, []);+ assert.deepEqual(h.calls.pinned, []);});test("surface header ensurer writes no channel header where an external member could read it", async () => {for (const shape of [{ is_ext_shared: true }, { is_mpim: true }]) {- let sets = 0;+ let writes = 0;const client = {- conversations: {- info: async () => ({ channel: { ...shape, purpose: {} } }),- setPurpose: async () => {- sets += 1;+ chat: {+ postMessage: async () => {+ writes += 1;+ return { ts: "1.0" };+ },+ update: async () => {+ writes += 1;+ return {};+ },+ },+ pins: {+ list: async () => {+ writes += 1;+ return { items: [] };+ },+ add: async () => {+ writes += 1;return {};},},+ conversations: {+ info: async () => ({ channel: { ...shape } }),+ setTopic: async () => ({}),+ },};const ensure = createSurfaceHeaderEnsurer({- headerFacts: async () => ({ agentLabel: "Quartermaster", modelName: "Claude Opus 4.8" }),+ headerFacts: async () => ({ modelName: "Claude Opus 4.8" }),+ channelPinEnabled: async () => true,webUiPublicUrl: "https://claw.acme.dev",ids: { botUserId: "U0BOT" },});- ensure(client as any, "C1", "channel:C1", "channel");+ ensure(client as any, "C1", "channel:C1", "channel", { pinNew: true });await new Promise((r) => setTimeout(r, 30));- assert.equal(sets, 0, `a ${JSON.stringify(shape)} conversation is not the bot's to describe`);+ assert.equal(writes, 0, `a ${JSON.stringify(shape)} conversation is not the bot's to post a header into`);}});-test("surface header ensurer never clobbers a human-written channel description", async () => {- const h = headerHarness({ value: "Where we plan the launch", creator: "U0HUMAN" }, "Claude Opus 4.8", "channel");- h.ensure(h.client, "C1");- await h.flush();- assert.equal(h.calls.set, 0, "a description a human wrote is theirs");- assert.equal(h.read()?.value, "Where we plan the launch");+test("surface header ensurer never edits a pinned message the bot does not own", async () => {+ let updates = 0;+ const client = {+ chat: {+ postMessage: async () => ({ ts: "1.0" }),+ update: async () => {+ updates += 1;+ return {};+ },+ },+ pins: {+ list: async () => ({ items: [{ message: { ts: "5.0", user: "U0HUMAN", text: "Where we plan the launch" } }] }),+ add: async () => ({}),+ },+ conversations: {+ info: async () => ({ channel: {} }),+ setTopic: async () => ({}),+ },+ };+ const ensure = createSurfaceHeaderEnsurer({+ headerFacts: async () => ({ modelName: "Claude Opus 4.8" }),+ channelPinEnabled: async () => true,+ webUiPublicUrl: "https://claw.acme.dev",+ ids: { botUserId: "U0BOT" },+ });+ ensure(client as any, "C1", "channel:C1", "channel");+ await new Promise((r) => setTimeout(r, 30));+ assert.equal(updates, 0, "a message a human pinned is theirs");});test("scopeSurfaceUrl deep-links each context to its own project page", () => {diff --git a/test/slack-index.integration.test.ts b/test/slack-index.integration.test.tsindex a5bc2a65a..b93d9bdde 100644--- a/test/slack-index.integration.test.ts+++ b/test/slack-index.integration.test.ts@@ -61,15 +61,28 @@ class FakeSlackClient {this.channelsById.set(channel, { ...existing, topic: { value: topic, creator: "UBOT" } });return { ok: true };},- setPurpose: async ({ channel, purpose }: { channel: string; purpose: string }) => {- this.purposes.push({ channel, purpose });- const existing = this.channelsById.get(channel) ?? { id: channel };- this.channelsById.set(channel, { ...existing, purpose: { value: purpose, creator: "UBOT" } });+ };+ readonly topics: { channel: string; topic: string }[] = [];+ readonly pinnedByChannel = new Map<string, { ts: string; user: string; text: string }[]>();+ readonly pins = {+ list: async ({ channel }: { channel: string }) => ({+ items: (this.pinnedByChannel.get(channel) ?? []).map((message) => ({ message })),+ }),+ add: async ({ channel, timestamp }: { channel: string; timestamp: string }) => {+ const lastPost = this.posts.filter((p) => p.channel === channel).at(-1);+ const pinned = this.pinnedByChannel.get(channel) ?? [];+ pinned.push({ ts: timestamp, user: "UBOT", text: lastPost?.text ?? "" });+ this.pinnedByChannel.set(channel, pinned);+ return { ok: true };+ },+ remove: async ({ channel, timestamp }: { channel: string; timestamp: string }) => {+ this.pinnedByChannel.set(+ channel,+ (this.pinnedByChannel.get(channel) ?? []).filter((m) => m.ts !== timestamp),+ );return { ok: true };},};- readonly topics: { channel: string; topic: string }[] = [];- readonly purposes: { channel: string; purpose: string }[] = [];readonly chat = {postMessage: async (body: any) => {this.posts.push(body);@@ -199,6 +212,8 @@ class FakeCore implements SlackCoreClient {private runGate: Promise<void> | undefined;private releaseRun: (() => void) | undefined;readonly modelChangeListeners: Array<(scope: any) => void> = [];+ readonly headerPinChangeListeners: Array<(scope: any) => void> = [];+ readonly headerPinScopes = new Set<string>();async externalSlackParticipants(): Promise<boolean> {return this.externalParticipants;@@ -209,6 +224,12 @@ class FakeCore implements SlackCoreClient {onScopeModelChanged(listener: (scope: any) => void): void {this.modelChangeListeners.push(listener);}+ async channelHeaderPinEnabled(scope: any): Promise<boolean> {+ return this.headerPinScopes.has(String(scope));+ }+ onChannelHeaderPinChanged(listener: (scope: any) => void): void {+ this.headerPinChangeListeners.push(listener);+ }async stageBlob(bytes: Uint8Array): Promise<{ blobId: string; sizeBytes: number }> {return { blobId: "blob-1", sizeBytes: bytes.byteLength };}@@ -409,8 +430,7 @@ test("a human's DM sets the conversation header to the serving model + web surfaassert.deepEqual(f.client.topics, [{channel: "D1",- topic:- "Quartermaster is using Claude Opus 4.8 here. <https://claw.example.dev/contexts?scope=personal%3AU1|More settings>",+ topic: "Using Claude Opus 4.8 here. <https://claw.example.dev/contexts?scope=personal%3AU1|More settings>",},]);await f.app.emitMessage({ channel: "D1", channel_type: "im", user: "U1", text: "again", ts: "100.2" });@@ -421,39 +441,94 @@ test("a human's DM sets the conversation header to the serving model + web surfa}});-test("a channel's description names the channel's own default model and project page", async () => {+test("joining a channel posts the welcome and a pinned header naming the model and project page", async () => {+ const f = await fixture({ webUiPublicUrl: "https://claw.example.dev" });+ try {+ f.core.headerPinScopes.add("channel:C1");+ await f.app.emitEvent("member_joined_channel", { user: "UBOT", channel: "C1", event_ts: "100.1" }, "Ev-bot-join");+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.deepEqual(+ f.client.pinnedByChannel.get("C1")?.map((m) => m.text),+ ["Using Claude Opus 4.8 here. <https://claw.example.dev/projects/channel/C1|More settings>"],+ );+ assert.deepEqual(f.client.topics, [], "a channel's topic stays the members' own scratch space");+ } finally {+ await f.stop();+ }+});++test("joining a channel with the toggle off (the default) posts only the welcome — no pin", async () => {+ const f = await fixture({ webUiPublicUrl: "https://claw.example.dev" });+ try {+ await f.app.emitEvent("member_joined_channel", { user: "UBOT", channel: "C1", event_ts: "100.1" }, "Ev-bot-join");+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.equal(f.client.posts.length, 1, "only the welcome message lands");+ assert.equal(f.client.pinnedByChannel.get("C1"), undefined);+ } finally {+ await f.stop();+ }+});++test("flipping the toggle on creates the pinned header; flipping it off removes it", async () => {+ const f = await fixture({ webUiPublicUrl: "https://claw.example.dev" });+ try {+ assert.equal(f.core.headerPinChangeListeners.length, 1, "the plugin subscribes to toggle changes");+ f.core.headerPinScopes.add("channel:C1");+ for (const listener of f.core.headerPinChangeListeners) listener("channel:C1");+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.deepEqual(+ f.client.pinnedByChannel.get("C1")?.map((m) => m.text),+ ["Using Claude Opus 4.8 here. <https://claw.example.dev/projects/channel/C1|More settings>"],+ "toggle-on posts and pins the header",+ );+ f.core.headerPinScopes.delete("channel:C1");+ for (const listener of f.core.headerPinChangeListeners) listener("channel:C1");+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.deepEqual(f.client.pinnedByChannel.get("C1"), [], "toggle-off unpins the header");+ assert.equal(f.client.deletes.length, 1, "and deletes the bot's header message");+ } finally {+ await f.stop();+ }+});++test("a mention in a channel with no pinned header never creates one", async () => {const f = await fixture({ webUiPublicUrl: "https://claw.example.dev" });try {const mention = { channel: "C1", channel_type: "channel", user: "U1", text: "<@UBOT> hi", ts: "100.1" };f.client.messagesByChannel.set("C1", [mention]);await f.app.emitEvent("app_mention", mention, "Ev-channel-header");- await new Promise((resolve) => setImmediate(resolve));- assert.deepEqual(f.client.purposes, [- {- channel: "C1",- purpose:- "Quartermaster is using Claude Opus 4.8 here. <https://claw.example.dev/projects/channel/C1|More settings>",- },- ]);- assert.deepEqual(f.client.topics, [], "a channel's topic stays the members' own scratch space");+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.equal(f.client.pinnedByChannel.get("C1"), undefined);+ assert.deepEqual(f.client.updates, []);} finally {await f.stop();}});-test("a scope's model change rewrites its channel description without waiting for a message", async () => {+test("a scope's model change rewrites its channel's pinned header without waiting for a message", async () => {const f = await fixture({ webUiPublicUrl: "https://claw.example.dev" });try {assert.equal(f.core.modelChangeListeners.length, 1, "the plugin subscribes to core's model changes");- for (const listener of f.core.modelChangeListeners) listener("channel:C1");- await new Promise((resolve) => setTimeout(resolve, 20));- assert.deepEqual(f.client.purposes, [+ f.core.headerPinScopes.add("channel:C1");+ f.client.pinnedByChannel.set("C1", [{- channel: "C1",- purpose:- "Quartermaster is using Claude Opus 4.8 here. <https://claw.example.dev/projects/channel/C1|More settings>",+ ts: "50.0",+ user: "UBOT",+ text: "Using Claude Sonnet 5 here. <https://claw.example.dev/projects/channel/C1|More settings>",},]);+ for (const listener of f.core.modelChangeListeners) listener("channel:C1");+ await new Promise((resolve) => setTimeout(resolve, 20));+ assert.deepEqual(+ f.client.updates.map((u) => ({ channel: u.channel, ts: u.ts, text: u.text })),+ [+ {+ channel: "C1",+ ts: "50.0",+ text: "Using Claude Opus 4.8 here. <https://claw.example.dev/projects/channel/C1|More settings>",+ },+ ],+ );for (const listener of f.core.modelChangeListeners) listener("personal:[email protected]");await new Promise((resolve) => setTimeout(resolve, 20));assert.deepEqual(f.client.topics, [], "a DM's topic settles on the person's next message, not on a push");