Multiplayer agent harness for work.
Add opt-in Slack task cards for ongoing work (#1655)
Joshua France82342138176e
diff --git a/plugins/admin/ui/settings-flags.ts b/plugins/admin/ui/settings-flags.tsindex 99d1a9dac..ebe9572ae 100644--- a/plugins/admin/ui/settings-flags.ts+++ b/plugins/admin/ui/settings-flags.ts@@ -135,6 +135,7 @@ function template() {><option value="persistent_subagents">Persistent subagents</option><option value="inbox_loops">Inbox Loops</option>+ <option value="slack_loading_indicator">Slack loading indicator (experimental)</option></select></label><div>@@ -142,7 +143,13 @@ function template() {<div id="feature-flag-scopes" aria-labelledby="feature-flag-scope-label" ?inert=${state.saving}>${state.selector || "Loading people and scopes…"}</div>- <span class="hint">Persistent subagents are available for personal scopes only.</span>+ <span class="hint"+ >${+ state.feature === "slack_loading_indicator"+ ? "Shows an activity card in Slack threads, including background work and monitors. After five minutes, the card links to the web conversation. Everyone in a shared thread can see it. Top-level DMs stay unchanged. Turning this off leaves existing cards."+ : "Persistent subagents are available for personal scopes only."+ }</span+ ></div></div></div>diff --git a/src/api/routes/surface.ts b/src/api/routes/surface.tsindex cfcab4370..853fc2ae4 100644--- a/src/api/routes/surface.ts+++ b/src/api/routes/surface.ts@@ -1,3 +1,4 @@+import { conversationWebUrl } from "../../util/conversation-links.ts";import { isSessionStatus } from "../../sessions/session-status.ts";import { suggestedActivityRoutes } from "./suggested-activities.ts";import { runtimeFallback, runtimeConfigBody, userRuntimeConfigBody, webuiModelEnabled } from "../runtime-config.ts";@@ -60,19 +61,6 @@ function isConversationColor(value: unknown): value is string | null {return value === null || (typeof value === "string" && /^#[0-9a-fA-F]{6}$/.test(value));}-function conversationWebUrl(publicWebUrl: string | undefined, sessionId: string): string | undefined {- const raw = publicWebUrl?.trim();- if (!raw || !/^https?:\/\//i.test(raw) || /[?#]/.test(raw)) return undefined;- try {- const base = new URL(raw);- if ((base.protocol !== "http:" && base.protocol !== "https:") || base.username || base.password) return undefined;- base.pathname = `${base.pathname.replace(/\/+$/, "")}/s/${encodeURIComponent(sessionId)}`;- return base.toString();- } catch {- return undefined;- }-}-async function regenerateSessionTitle(ctx: ApiCtx): Promise<void> {const { res, app, body } = ctx;const id = ctx.params.id!;diff --git a/src/api/slack-core-client.ts b/src/api/slack-core-client.tsindex f67f53549..8b3d2adf8 100644--- a/src/api/slack-core-client.ts+++ b/src/api/slack-core-client.ts@@ -1,4 +1,11 @@import { replayableRequest } from "../core/orchestrator/turn-helpers.ts";+import {+ createSlackSessionStatus,+ type SlackStatusActivity,+ type SlackSessionStatus,+ type SlackSessionStatusState,+} from "../slack/session-status.ts";+import type { FeatureFlagStore } from "../feature-flags.ts";import { decideDeploymentAccess } from "../slack/deploy-access.ts";import type { IdentityService } from "../identity/identity-service.ts";import type { ActorAssertion } from "../types.ts";@@ -96,6 +103,7 @@ export interface SlackCoreClient {decideDeploymentAccess(value: string, actor: ActorAssertion, approve: boolean): Promise<string>;keychainApprovals?: KeychainApprovals;taskAcknowledgements?: TaskAcknowledgements;+ sessionStatus?: SlackSessionStatus;externalSlackParticipants(): Promise<boolean>;internalMemberOverrides(): Promise<string[]>;ackEmojiOverride(): Promise<string[] | null>;@@ -166,6 +174,9 @@ export interface SlackCoreClientDeps {identity: IdentityService;keychainApprovals?: KeychainApprovals;taskAcknowledgements?: DurableMap<TaskAckState>;+ sessionStatus?: DurableMap<SlackSessionStatusState>;+ statusActivity?: SlackStatusActivity;+ featureFlags?: FeatureFlagStore;app: App;config: ScopedConfigStore;runtimeFallback: RuntimeChoice;@@ -245,6 +256,18 @@ export function createSlackCoreClient(deps: SlackCoreClientDeps): SlackCoreClien...(deps.taskAcknowledgements? { taskAcknowledgements: createTaskAcknowledgements(deps.taskAcknowledgements, lease, deps) }: {}),+ ...(deps.sessionStatus && deps.featureFlags+ ? {+ sessionStatus: createSlackSessionStatus(+ deps.sessionStatus,+ lease,+ deps.runs,+ deps.featureFlags,+ Date.now,+ deps.statusActivity,+ ),+ }+ : {}),async externalSlackParticipants() {return (await deps.config.getExternalSlackParticipantsDurable(orgScope)) === true;},@@ -333,8 +356,8 @@ export function createSlackCoreClient(deps: SlackCoreClientDeps): SlackCoreClienlet replyingSignaled = false;let firstBlockSignaled = false;let surfaceSignaled = false;- const signalReplying = (): void => {- if (replyingSignaled || !deps.turnStream.replying(runId)) return;+ const signalReplying = (durable = false): void => {+ if (replyingSignaled || !(durable || deps.turnStream.replying(runId))) return;replyingSignaled = true;hooks.onReplying?.();};@@ -399,7 +422,7 @@ export function createSlackCoreClient(deps: SlackCoreClientDeps): SlackCoreClienif (view?.surfacePosted) signalSurface();return (view?.result as TurnResult | null | undefined) ?? null;}- signalReplying();+ signalReplying(run.deliveryState?.replying === true);await emitTasks();await emitGoal().catch(swallowAs("slack-core-client: goal refresh", undefined));const fb = deps.turnStream.firstBlock(runId);diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex ce56bb996..4e87e9338 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -2439,7 +2439,14 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {}}- if (input.runId) deps.turnStream?.begin(input.runId);+ if (input.runId) {+ if ((input.surface === "slack" || input.surface === "monitor") && input.runLeaseToken) {+ await deps.runs+ ?.setDeliveryState(input.runId, input.runLeaseToken, { replying: true })+ .catch(swallowAs("orchestrator: persist reply engagement", false));+ }+ deps.turnStream?.begin(input.runId);+ }const backgroundBroker =deps.processes && supportsProcessSessions(deps.sandbox)diff --git a/src/feature-flags.ts b/src/feature-flags.tsindex 6fc1a42ed..2a91fd85e 100644--- a/src/feature-flags.ts+++ b/src/feature-flags.ts@@ -2,7 +2,12 @@ import type { DurableMap } from "./persistence/durable-map.ts";import { orgId as configOrgId } from "./config.ts";import { scopeId, type ScopeId } from "./types.ts";-export const FEATURE_NAMES = ["persistent_subagents", "responsive_spine", "inbox_loops"] as const;+export const FEATURE_NAMES = [+ "persistent_subagents",+ "responsive_spine",+ "inbox_loops",+ "slack_loading_indicator",+] as const;export type FeatureName = (typeof FEATURE_NAMES)[number];export interface FeatureFlagRecord {diff --git a/src/runs/memory-run-store.ts b/src/runs/memory-run-store.tsindex 4fb614d8d..88ff6eb43 100644--- a/src/runs/memory-run-store.ts+++ b/src/runs/memory-run-store.ts@@ -152,7 +152,7 @@ export function createMemoryRunStore(opts?: { maxClaims?: number }): MemoryRunticonst run = runs.get(runId);if (!run) return false;if (leaseToken !== null && run.leaseToken !== leaseToken) return false;- run.deliveryState = state;+ run.deliveryState = { ...run.deliveryState, ...state };return true;},diff --git a/src/runs/postgres-run-store.ts b/src/runs/postgres-run-store.tsindex 1d2ca1296..2bdad1004 100644--- a/src/runs/postgres-run-store.ts+++ b/src/runs/postgres-run-store.ts@@ -363,12 +363,14 @@ export function createPostgresRunStore(connectionString: string, opts?: { maxClaasync setDeliveryState(runId: string, leaseToken: string | null, state: RunDeliveryState): Promise<boolean> {const { rowCount } =leaseToken === null- ? await q("UPDATE runs SET delivery_state=$1 WHERE id=$2", [JSON.stringify(state), runId])- : await q("UPDATE runs SET delivery_state=$1 WHERE id=$2 AND lease_token=$3", [- JSON.stringify(state),- runId,- leaseToken,- ]);+ ? await q(+ "UPDATE runs SET delivery_state=(COALESCE(delivery_state, '{}')::jsonb || $1::jsonb)::text WHERE id=$2",+ [JSON.stringify(state), runId],+ )+ : await q(+ "UPDATE runs SET delivery_state=(COALESCE(delivery_state, '{}')::jsonb || $1::jsonb)::text WHERE id=$2 AND lease_token=$3",+ [JSON.stringify(state), runId, leaseToken],+ );return rowCount > 0;},diff --git a/src/runs/run-store.ts b/src/runs/run-store.tsindex 185eba9db..347c1425a 100644--- a/src/runs/run-store.ts+++ b/src/runs/run-store.ts@@ -15,6 +15,7 @@ export interface ReapEvent {}export interface RunDeliveryState {+ replying?: boolean;editRef?: string;}diff --git a/src/slack/README.md b/src/slack/README.mdindex 2f1c63df1..8f582cbc4 100644--- a/src/slack/README.md+++ b/src/slack/README.md@@ -24,10 +24,10 @@ Slack ⇄ (WebSocket) slack surface (in core) ── direct calls ──▶### Slack Agents (top-bar pin)The manifest enables Slack's [Agents & AI Apps](https://docs.slack.dev/ai/developing-agents)-feature (`agent_view`) for one reason: users can pin the app to the Slack top bar and open-it anywhere. Conversations in the resulting split pane are ordinary DM thread messages and-flow through the normal DM machinery unchanged — none of the extra agent UI (status-indicators, thread titles, context passing, suggested prompts) is implemented.+feature (`agent_view`) so users can pin the app to the Slack top bar and open it anywhere.+Conversations in the resulting split pane are ordinary DM thread messages and flow through+the normal DM machinery unchanged. Thread titles, context passing and suggested prompts+are not implemented. Activity cards are experimental and off by default.Two caveats:@@ -39,6 +39,37 @@ Two caveats:the plugin acknowledges them as no-ops). Installs that don't update keep workingexactly as before.+### Optional activity cards++In Admin → Customize → Feature flags, enable **Slack loading indicator (experimental)**+for selected people or conversation scopes. It is off by default. The Slack app must+support [`task_card`](https://docs.slack.dev/reference/block-kit/blocks/task-card-block)+blocks and have `chat:write`.++After QM commits to answering, one card is posted in the existing reply thread and+updated in place: **Working**, **Waiting to resume**, **Background work**, **Monitoring**,+or **No active work**. This describes recorded activity, not success, failure or delivery.+Quiet ambient turns and unthreaded DMs do not create cards. Cards are visible to everyone+in their thread; own status cards and edits are excluded from conversation history.++Waiting cards survive turns and restarts. Only this conversation's registered background+jobs and enabled, unexpired process monitors count, not recurring crons or agent prose.+Unwatched exits become visible when checked, reconciled during sandbox setup, or expired.+Commands and monitor instructions are never rendered. After more than five minutes,+including waits, a subtle **Follow via QM Web** link opens the exact web conversation+with normal authorization. Without a configured web URL, the link is omitted.++A minute sweep refreshes activity and retries transient failures. Durable receipts and+per-thread leases preserve card identity across workers; expired run leases are shown as+waiting, not working. Slack has no conditional writes: late updates are repaired, and an+ambiguous initial post can duplicate if Slack does not deduplicate `client_msg_id`.+An outage can leave a stale card until recovery. Status calls have a separate five-second+timeout and never delay reply delivery.++Once no activity remains, the card settles without a spinner and is no longer tracked.+Later work creates a fresh card. Disabling the flag settles existing cards without+stopping work or deleting messages. Native session status and Stop events are not used.+> **Running locally alongside another developer? Each dev needs their OWN app.**> See [Local dev with multiple developers](#local-dev-with-multiple-developers)> below — set the manifest `name`/`display_name` to `agent-<yourname>` beforediff --git a/src/slack/events.ts b/src/slack/events.tsindex 60eebb115..11a39f77d 100644--- a/src/slack/events.ts+++ b/src/slack/events.ts@@ -18,7 +18,7 @@ import type { DenyResponder } from "./allow-from.ts";import { swallowAs } from "../util/errors.ts";import type { Mirror } from "./mirror.ts";import type { TurnHandler } from "./turn-handler.ts";-import { shouldMirrorMessage } from "./message-gating.ts";+import { shouldMirrorMessage, isOwnStatusCard } from "./message-gating.ts";interface EventArgs {event: unknown;@@ -175,6 +175,7 @@ export function registerSlackEvents(app.message(async ({ message, body, client, context }: MessageArgs) => {try {const m = parseMessageEvent(message);+ if (isOwnStatusCard(m.message ?? m.previous_message ?? m, ids.botUserId, ids.ownBotId)) return;if (m.channel &&!m.channel_type &&diff --git a/src/slack/history.ts b/src/slack/history.tsindex fc9d2f76d..1510d595e 100644--- a/src/slack/history.ts+++ b/src/slack/history.ts@@ -1,3 +1,4 @@+import { isOwnStatusCard } from "./message-gating.ts";import { slackMessageToIngestEvent } from "./mirror.ts";import { messageWithForwardedContent } from "./forwards.ts";import type { SlackContextSource } from "./config.ts";@@ -53,6 +54,7 @@ export function createSlackHistoryReader(deps: {? await historyClient.conversations.replies({ ...paging, ts: threadTs }): await historyClient.conversations.history(paging),);+ page.messages = page.messages.filter((m) => !isOwnStatusCard(m, deps.ids.botUserId, deps.ids.ownBotId));const raw = threadTs ? page.messages : page.messages.slice().reverse();if (!threadTs && expandThreads) {const parents = raw.filter((m) => m.ts && Number(m.reply_count) > 0).slice(-5);@@ -69,7 +71,8 @@ export function createSlackHistoryReader(deps: {}),);const byTs = new Map<string, SlackHistoryMessage>();- for (const m of [...raw, ...expanded.flatMap((result) => result.page.messages)]) if (m.ts) byTs.set(m.ts, m);+ for (const m of [...raw, ...expanded.flatMap((result) => result.page.messages)])+ if (m.ts && !isOwnStatusCard(m, deps.ids.botUserId, deps.ids.ownBotId)) byTs.set(m.ts, m);return {raw: [...byTs.values()],hasMore: page.hasMore,@@ -262,6 +265,7 @@ export function createSlackHistoryReader(deps: {? await historyClient.conversations.replies({ ...paging, ts: threadTs }): await historyClient.conversations.history(paging),);+ page.messages = page.messages.filter((m) => !isOwnStatusCard(m, deps.ids.botUserId, deps.ids.ownBotId));if (page.messages.length && deps.core.rememberSurfaceHistory) {await deps.core.rememberSurfaceHistory(diff --git a/src/slack/index.ts b/src/slack/index.tsindex adcd20dc4..feca1cd14 100644--- a/src/slack/index.ts+++ b/src/slack/index.ts@@ -325,10 +325,35 @@ export async function startSlackPlugin(}})();});+ const statusClient = new WebClient(BOT_TOKEN, {+ ...CLIENT_OPTIONS,+ timeout: 5_000,+ rejectRateLimitedCalls: true,+ });+ const statusAccount = () => `${ids.ownTeamId}:${ids.botUserId}`;+ let statusSync: Promise<void> | undefined;+ const reconcileStatus = () => {+ statusSync ??= core.sessionStatus+ ?.reconcile(statusClient, statusAccount())+ .catch(swallowAs("slack: session status reconciliation", undefined))+ .finally(() => {+ statusSync = undefined;+ });+ return statusSync;+ };+ const statusSweep = createSweeper(reconcileStatus, 60_000, { label: "slack session status", immediate: true });const handler = createTurnHandler({accountId: ACCOUNT_LABEL,...(cfg.externalAccess ? { externalAccess: cfg.externalAccess } : {}),continuePrivate: (runId, task) => continueInPrivate(core, runId, task, (id) => slackAccountClients.get(id)),+ onEngaged: (runId, channel, threadTs) => {+ void core.sessionStatus?.start(statusClient, statusAccount(), runId, channel, threadTs).finally(() => {+ void reconcileStatus();+ });+ },+ onSettled: () => {+ void reconcileStatus();+ },rateLimitNotice,readHistory,core,@@ -520,6 +545,7 @@ export async function startSlackPlugin(}});};+ statusSweep.start();let unsubscribeDeliveries = (): void => {};let deliveriesTimer: NodeJS.Timeout | undefined;if (CORE_SINGLETON || cfg.externalAccess) {@@ -553,6 +579,7 @@ export async function startSlackPlugin(}stopped = true;if (slackAccountClients.get(ACCOUNT_LABEL)?.client === app.client) slackAccountClients.delete(ACCOUNT_LABEL);+ await statusSweep.stop();await replaySweeper?.stop();if (deliveriesTimer) clearInterval(deliveriesTimer);if (emojiCatalogTimer) clearInterval(emojiCatalogTimer);diff --git a/src/slack/message-gating.ts b/src/slack/message-gating.tsindex 3061684d2..634970ed2 100644--- a/src/slack/message-gating.ts+++ b/src/slack/message-gating.ts@@ -1,5 +1,27 @@+import { isObj } from "../util/objects.ts";import { LRUCache } from "lru-cache";+export const SLACK_STATUS_TASK_PREFIX = "qm_status:";++export function isOwnStatusCard(+ message: { user?: string; bot_id?: string; blocks?: unknown[] },+ botUserId: string,+ ownBotId = "",+): boolean {+ const own = (botUserId && message.user === botUserId) || (ownBotId && message.bot_id === ownBotId);+ return Boolean(+ own &&+ Array.isArray(message.blocks) &&+ message.blocks.some(+ (block) =>+ isObj(block) &&+ block.type === "task_card" &&+ typeof block.task_id === "string" &&+ block.task_id.startsWith(SLACK_STATUS_TASK_PREFIX),+ ),+ );+}+export function mentionsBot(text: string, botUserId: string): boolean {return botUserId ? text.includes(`<@${botUserId}>`) : false;}diff --git a/src/slack/mirror.ts b/src/slack/mirror.tsindex 4b4600a6e..aa13fe099 100644--- a/src/slack/mirror.ts+++ b/src/slack/mirror.ts@@ -1,3 +1,4 @@+import { isOwnStatusCard } from "./message-gating.ts";import { swallow } from "../util/errors.ts";import { decodeSlackEntities, mentionsBot } from "./lib.ts";import { messageWithForwardedContent } from "./forwards.ts";@@ -117,6 +118,7 @@ export function createMirror(deps: {kind?: "channel" | "dm" | "group";} = {},): Promise<void> {+ if (isOwnStatusCard(m, ids.botUserId, ids.ownBotId)) return;const container = m.channel;const ts = m.ts;if (!container || !ts) return;diff --git a/src/slack/payloads.ts b/src/slack/payloads.tsindex 73933413e..af0ce636b 100644--- a/src/slack/payloads.ts+++ b/src/slack/payloads.ts@@ -19,6 +19,7 @@ export function parseEventId(body: unknown): string | undefined {}export interface SlackMessageEvent {+ blocks?: unknown[];channel: string;channel_type?: string;subtype?: string;@@ -35,7 +36,7 @@ export interface SlackMessageEvent {deleted_ts?: string;files: SlackFile[];message?: SlackMessageEvent;- previous_message?: { user?: string; bot_id?: string; thread_ts?: string; text?: string };+ previous_message?: { user?: string; bot_id?: string; thread_ts?: string; text?: string; blocks?: unknown[] };}function fileList(v: unknown): SlackFile[] {@@ -71,6 +72,7 @@ export function parseMessageEvent(event: unknown): SlackMessageEvent {message: nested ? parseMessageEvent(nested) : undefined,previous_message: prev? {+ ...(Array.isArray(prev.blocks) ? { blocks: prev.blocks } : {}),user: str(prev.user),bot_id: str(prev.bot_id),thread_ts: coerced(prev.thread_ts),@@ -144,6 +146,7 @@ export function parseBlockAction<T extends string>(}export interface SlackHistoryMessage {+ blocks?: unknown[];edited?: { ts?: string };mentionsSelf?: boolean;ts?: string;diff --git a/src/slack/session-status.ts b/src/slack/session-status.tsnew file mode 100644index 000000000..2bc7c9e56--- /dev/null+++ b/src/slack/session-status.ts@@ -0,0 +1,209 @@+import { SLACK_STATUS_TASK_PREFIX } from "./message-gating.ts";+import { randomUUID } from "node:crypto";+import type { DurableMap } from "../persistence/durable-map.ts";+import type { LeaderLease } from "../persistence/leader-lease.ts";+import type { FeatureFlagStore } from "../feature-flags.ts";+import { isTerminal, leaseLapsed, type RunStore } from "../runs/run-store.ts";+import type { ProcessRegistry } from "../processes/process-registry.ts";+import type { SessionStore } from "../sessions/session-store.ts";+import type { MonitorStore } from "../monitors/monitor-store.ts";+import { conversationScope } from "../resolution/resolution-service.ts";+import { conversationWebUrl } from "../util/conversation-links.ts";+import { createKeyedQueue, sleep } from "../util/async.ts";+import { swallowAs } from "../util/errors.ts";++export interface SlackSessionStatusState {+ writer?: string;+ account: string;+ channel: string;+ threadTs: string;+ anchorRunId: string;+ startedAt?: number;+ cardId?: string;+ cardTs?: string;+ cardContent?: string;+ followUrl?: string;+}++interface StatusClient {+ apiCall(method: string, args: Record<string, unknown>): Promise<unknown>;+}++export interface SlackStatusActivity {+ sessions?: Pick<SessionStore, "getByThread">;+ processes?: Pick<ProcessRegistry, "liveByScope">;+ monitors?: Pick<MonitorStore, "enabled">;+ publicWebUrl?: string;+}++export function createSlackSessionStatus(+ store: DurableMap<SlackSessionStatusState>,+ lease: LeaderLease,+ runs: Pick<RunStore, "get" | "inFlightForThread">,+ flags: Pick<FeatureFlagStore, "enabled">,+ now = Date.now,+ activity: SlackStatusActivity = {},+) {+ if (!store.update || !store.deleteIf) throw new Error("Slack status requires atomic durable updates");+ const update = store.update.bind(store);+ const deleteIf = store.deleteIf.bind(store);+ const queue = createKeyedQueue<string>();+ const key = (account: string, channel: string, threadTs: string) => JSON.stringify([account, channel, threadTs]);+ async function sync(client: StatusClient, id: string, next?: SlackSessionStatusState) {+ await queue(id, async () => {+ for (let attempt = 0; attempt < 300; attempt++) {+ const applied = await lease.hold(`slack:session-status:${id}`, async (lost) => {+ let leaseLost = false;+ void lost.then(() => {+ leaseLost = true;+ });+ const writer = randomUUID();+ const anchor = await runs.get((next ?? (await store.get(id)))?.anchorRunId ?? "");+ const scope = anchor && conversationScope(anchor.request.conversation, anchor.request.actor.id);+ const optedIn = !!scope && (await flags.enabled("slack_loading_indicator", scope));+ if (+ next &&+ (!optedIn ||+ !anchor?.deliveryState?.replying ||+ anchor.request.privateSessionMessage ||+ isTerminal(anchor.status))+ )+ return true;+ if (leaseLost) return true;+ if (next) await store.putIfAbsent(id, { ...next, writer });+ if (leaseLost) {+ await deleteIf(id, (row) => row.writer === writer && !row.cardTs);+ return true;+ }+ let state = await update(id, (row) =>+ leaseLost ? row : { ...row, writer, ...(next ? { anchorRunId: next.anchorRunId } : {}) },+ );+ if (!state || leaseLost || state.writer !== writer) return true;+ const persist = async (patch: Partial<SlackSessionStatusState>) => {+ const saved = await update(id, (row) => (!leaseLost && row.writer === writer ? { ...row, ...patch } : row));+ if (!saved || leaseLost || saved.writer !== writer) return false;+ state = saved;+ return true;+ };+ const active =+ optedIn && anchor+ ? (await runs.inFlightForThread(anchor.sessionId)).filter(+ (run) => run.deliveryState?.replying && !run.request.privateSessionMessage,+ )+ : [];+ const processing = active.some((run) => run.status === "running" && !leaseLapsed(run, now()));+ const threadRef = anchor?.request.conversation.threadRef;+ const jobs =+ optedIn && threadRef+ ? ((await activity.processes?.liveByScope(scope!, now())) ?? []).filter(+ (job) => job.kind === "background" && job.sessionRef === threadRef,+ )+ : [];+ const monitors =+ optedIn && threadRef+ ? ((await activity.monitors?.enabled()) ?? []).filter(+ (monitor) =>+ monitor.ownerScopeId === scope && monitor.threadRef === threadRef && monitor.expiresAt > now(),+ )+ : [];+ const ongoing = active.length > 0 || jobs.length > 0 || monitors.length > 0;+ let title = "No active work";+ if (processing) title = "Working";+ else if (active.length) title = "Waiting to resume";+ else if (monitors.length) title = "Monitoring";+ else if (jobs.length) title = "Background work";+ state = {+ ...state,+ startedAt: state.startedAt ?? now(),+ cardId: state.cardId ?? randomUUID(),+ };+ if (now() - state.startedAt! > 5 * 60_000 && anchor?.sessionId) {+ const session = await activity.sessions?.getByThread(anchor.sessionId);+ if (session) state.followUrl = conversationWebUrl(activity.publicWebUrl, session.id);+ }+ if (leaseLost) return true;+ if (!(await persist(state))) return true;+ const blocks: Record<string, unknown>[] = [+ {+ type: "task_card",+ task_id: `${SLACK_STATUS_TASK_PREFIX}${state.cardId}`,+ title,+ status: ongoing ? "in_progress" : "complete",+ },+ ];+ if (state.followUrl)+ blocks.push({+ type: "context",+ elements: [{ type: "mrkdwn", text: `<${state.followUrl}|Follow via QM Web>` }],+ });+ const content = JSON.stringify(blocks);+ try {+ if (state.cardContent !== content && (state.cardTs || optedIn)) {+ const result = (await client.apiCall(state.cardTs ? "chat.update" : "chat.postMessage", {+ channel: state.channel,+ ...(state.cardTs ? { ts: state.cardTs } : { thread_ts: state.threadTs, client_msg_id: state.cardId }),+ text: title,+ blocks,+ unfurl_links: false,+ unfurl_media: false,+ })) as { ts?: string };+ const cardTs = state.cardTs ?? result.ts;+ if (!cardTs) throw new Error("Slack task card response missing timestamp");+ if (leaseLost) {+ await update(id, (row) => (row.cardId === state!.cardId && !row.cardTs ? { ...row, cardTs } : row));+ state = { ...state, cardTs };+ return true;+ }+ if (!(await persist({ cardTs, cardContent: content }))) return true;+ }+ if (!ongoing) await deleteIf(id, (row) => !leaseLost && row.writer === writer);+ } catch (error) {+ const code = (error as { data?: { error?: string } }).data?.error;+ if (+ [+ "channel_not_found",+ "not_authorized",+ "no_permission",+ "thread_ts_not_allowed",+ "message_not_found",+ ].includes(code ?? "") &&+ !leaseLost+ )+ await deleteIf(id, (row) => !leaseLost && row.writer === writer);+ throw error;+ } finally {+ if (leaseLost) {+ await store.putIfAbsent(id, state);+ await update(id, (row) => ({ ...row, cardContent: undefined }));+ }+ }+ return true;+ });+ if (applied) return;+ await sleep(50);+ }+ throw new Error("Slack session status lock timed out");+ });+ }+ return {+ async start(client: StatusClient, account: string, runId: string, channel: string, threadTs?: string) {+ if (!threadTs) return;+ await sync(client, key(account, channel, threadTs), {+ account,+ channel,+ threadTs,+ anchorRunId: runId,+ startedAt: now(),+ cardId: randomUUID(),+ }).catch(swallowAs("slack: start session status", undefined));+ },+ async reconcile(client: StatusClient, account: string) {+ for (const [id, state] of await store.entries()) {+ if (state.account !== account) continue;+ await sync(client, id).catch(swallowAs("slack: reconcile session status", undefined));+ }+ },+ };+}++export type SlackSessionStatus = ReturnType<typeof createSlackSessionStatus>;diff --git a/src/slack/turn-handler.ts b/src/slack/turn-handler.tsindex d9f2d2f3b..41b2d103d 100644--- a/src/slack/turn-handler.ts+++ b/src/slack/turn-handler.ts@@ -138,6 +138,8 @@ export function createTurnHandler(deps: {externalAccess?: ExternalSlackAccess;continuePrivate?: (runId: string, task: string) => Promise<void>;rateLimitNotice?: SlackRateLimitNotice;+ onEngaged?: (runId: string, channel: string, threadTs?: string) => void;+ onSettled?: () => void;core: SlackCoreClient;flow: TurnFlow;directory: Directory;@@ -587,6 +589,14 @@ export function createTurnHandler(deps: {{ ...turn, intakePreambleMs: Math.round(tSubmit - t0), clientSentAt: Date.now() },{deferDeliveryAck: true,+ ...(inc.synthetic+ ? {}+ : {+ onReplying: () => {+ if (acknowledges) startAck();+ if (queuedRunId && replyThreadTs) deps.onEngaged?.(queuedRunId, inc.channel, replyThreadTs);+ },+ }),onQueued: async (runId) => {queuedRunId = runId;inFlightRunByThread.set(threadRef, runId);@@ -603,7 +613,6 @@ export function createTurnHandler(deps: {},...(acknowledges? {- onReplying: () => void startAck(),onFirstBlock: (blockText: string) => {startAck().onFirstBlock(extractPrivateContinuation(cleanAgentReplyForSlack(blockText).text).text);},@@ -644,7 +653,10 @@ export function createTurnHandler(deps: {}return;} finally {- if (queuedRunId) inFlightRunByThread.clear(threadRef, queuedRunId);+ if (queuedRunId) {+ inFlightRunByThread.clear(threadRef, queuedRunId);+ deps.onSettled?.();+ }}// This message was folded into a run that was already live. The handler that OWNS that rundiff --git a/src/util/conversation-links.ts b/src/util/conversation-links.tsnew file mode 100644index 000000000..5ecdaf4a2--- /dev/null+++ b/src/util/conversation-links.ts@@ -0,0 +1,12 @@+export function conversationWebUrl(publicWebUrl: string | undefined, sessionId: string): string | undefined {+ const raw = publicWebUrl?.trim();+ if (!raw || !/^https?:\/\//i.test(raw) || /[?#]/.test(raw)) return undefined;+ try {+ const base = new URL(raw);+ if ((base.protocol !== "http:" && base.protocol !== "https:") || base.username || base.password) return undefined;+ base.pathname = `${base.pathname.replace(/\/+$/, "")}/s/${encodeURIComponent(sessionId)}`;+ return base.toString();+ } catch {+ return undefined;+ }+}diff --git a/src/wiring.ts b/src/wiring.tsindex d431f88f8..393e0c28e 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -1,3 +1,4 @@+import type { SlackSessionStatusState } from "./slack/session-status.ts";import { availableRuntimeError } from "./api/runtime-config.ts";import { createApprovalStore } from "./core/approval-store.ts";import { createKeychainApprovals } from "./credentials/keychain-approval.ts";@@ -2195,6 +2196,9 @@ export function buildApp(: {}),surfaceCache,taskAcknowledgements: artifactMap<TaskAckState>("slack_task_acknowledgements"),+ sessionStatus: artifactMap<SlackSessionStatusState>("slack_session_status"),+ statusActivity: { processes, monitors, sessions, publicWebUrl: config.publicWebUrl },+ featureFlags,inboxEvent: (event) => inboxRealtime.onConversationEvent(event),app,leaderLease,diff --git a/test/postgres-store.test.ts b/test/postgres-store.test.tsindex 634eea983..da7a33b69 100644--- a/test/postgres-store.test.ts+++ b/test/postgres-store.test.ts@@ -2010,6 +2010,13 @@ test("pg run store: delivery state round-trips; onTerminal fires once with it",const seen: string[] = [];runs.onTerminal((run) => seen.push(`${run.id}:${run.status}:${run.deliveryState?.editRef ?? ""}`));const claimed = await runs.claimById(r.id, "w1", 5_000);+ assert.equal(await runs.setDeliveryState(r.id, "wrong-token", { replying: true }), false);+ assert.equal((await runs.get(r.id))?.deliveryState?.replying, undefined);+ await Promise.all([+ runs.setDeliveryState(r.id, claimed!.leaseToken!, { replying: true }),+ runs.setDeliveryState(r.id, null, { editRef: "171.002" }),+ ]);+ assert.deepEqual((await runs.get(r.id))?.deliveryState, { editRef: "171.002", replying: true });await runs.complete(r.id, claimed!.leaseToken!, { status: "ok", reply: "done" });assert.deepEqual(seen, [`${r.id}:done:171.002`], "terminal listener sees the checkpointed state");diff --git a/test/run-store.test.ts b/test/run-store.test.tsindex 6d4c6c01c..81a0f5236 100644--- a/test/run-store.test.ts+++ b/test/run-store.test.ts@@ -360,6 +360,9 @@ for (const backend of backends) {assert.equal((await runs.get(r.id))?.deliveryState?.editRef, "171.002");assert.equal(await runs.setDeliveryState(r.id, claimed?.leaseToken ?? "", { editRef: "171.003" }), true);assert.equal((await runs.get(r.id))?.deliveryState?.editRef, "171.003");+ assert.equal(await runs.setDeliveryState(r.id, claimed?.leaseToken ?? "", { replying: true }), true);+ await runs.setDeliveryState(r.id, null, { editRef: "171.003" });+ assert.deepEqual((await runs.get(r.id))?.deliveryState, { editRef: "171.003", replying: true });const seen: string[] = [];runs.onTerminal((run) => seen.push(`${run.id}:${run.status}:${run.deliveryState?.editRef ?? ""}`));await runs.complete(r.id, claimed?.leaseToken ?? "", { status: "ok", reply: "done" });diff --git a/test/slack-index.integration.test.ts b/test/slack-index.integration.test.tsindex 7f8489094..301a29ac5 100644--- a/test/slack-index.integration.test.ts+++ b/test/slack-index.integration.test.ts@@ -240,6 +240,8 @@ class FakeCore implements SlackCoreClient {activeRun: string | undefined;abortedRuns: string[] = [];queuedRunId: string | undefined;+ engageRun = false;+ sessionStatus?: SlackCoreClient["sessionStatus"];private heldRunClaimed = false;readonly polled: string[] = [];private runGate: Promise<void> | undefined;@@ -302,8 +304,9 @@ class FakeCore implements SlackCoreClient {}return this.result;}- async waitRun(runId: string): Promise<TurnResult | null> {+ async waitRun(runId: string, hooks?: { onReplying?(): void }): Promise<TurnResult | null> {this.polled.push(runId);+ if (this.engageRun) hooks?.onReplying?.();if (this.runGate) await this.runGate;return this.result;}@@ -1704,3 +1707,124 @@ test("a denyMessage account stays silent on ambient channel chatter from unlisteawait f.stop();}});++test("thread status is detached from reply delivery and steering cannot take ownership", async () => {+ const f = await fixture({ coreSingleton: false });+ const starts: unknown[][] = [];+ let release!: () => void;+ const network = new Promise<void>((resolve) => {+ release = resolve;+ });+ f.core.sessionStatus = {+ start: async (...args) => {+ starts.push(args.slice(1));+ await network;+ },+ reconcile: async () => {},+ };+ f.core.engageRun = true;+ f.core.holdRun("r1");+ try {+ const original = f.app.emitEvent("app_mention", { channel: "C1", user: "U1", text: "<@UBOT> work", ts: "700.1" });+ await waitFor(() => starts.length === 1);+ await f.app.emitEvent("app_mention", {+ channel: "C1",+ thread_ts: "700.1",+ user: "U1",+ text: "<@UBOT> also this",+ ts: "700.2",+ });+ assert.deepEqual(starts, [["T1:UBOT", "r1", "C1", "700.1"]]);+ f.core.finishRun({ status: "ok", reply: "finished" });+ await original;+ assert.ok(f.client.posts.some((post) => post.text === "finished" && post.thread_ts === "700.1"));+ assert.equal(starts.length, 1);+ } finally {+ release();+ await f.stop();+ }+});++test("top-level DM replies remain top-level and never start native thread status", async () => {+ const f = await fixture();+ let starts = 0;+ f.core.sessionStatus = {+ start: async () => {+ starts++;+ },+ reconcile: async () => {},+ };+ f.core.engageRun = true;+ f.core.holdRun("r1");+ try {+ const incoming = f.app.emitMessage({ channel: "D1", channel_type: "im", user: "U1", text: "hello", ts: "701.1" });+ await waitFor(() => f.core.polled.length === 1);+ f.core.finishRun({ status: "ok", reply: "hello back" });+ await incoming;+ assert.equal(starts, 0);+ assert.ok(f.client.posts.some((post) => post.text === "hello back" && !post.thread_ts));+ } finally {+ await f.stop();+ }+});++test("own task-card status events never enter the mirror, but ordinary bot edits remain", async () => {+ const f = await fixture();+ const status = {+ user: "UBOT",+ bot_id: "BBOT",+ text: "Working",+ ts: "200.1",+ blocks: [{ type: "task_card", task_id: "qm_status:test", title: "Working", status: "in_progress" }],+ };+ try {+ await f.app.emitMessage({ channel: "C1", channel_type: "channel", ...status });+ await f.app.emitMessage({+ channel: "C1",+ channel_type: "channel",+ subtype: "message_changed",+ message: { ...status, text: "Finished" },+ previous_message: status,+ ts: "200.2",+ });+ await f.app.emitMessage({+ channel: "C1",+ channel_type: "channel",+ subtype: "message_deleted",+ previous_message: status,+ deleted_ts: status.ts,+ ts: "200.3",+ });+ assert.equal(f.core.ingests.flat().filter((event: any) => event.ts === status.ts).length, 0);+ assert.equal(f.core.turns.length, 0);+ await f.app.emitMessage({+ channel: "C1",+ channel_type: "channel",+ subtype: "message_changed",+ message: { user: "UBOT", bot_id: "BBOT", text: "Updated answer", ts: "201.1" },+ ts: "201.2",+ });+ assert.equal(f.core.ingests.flat().find((event: any) => event.ts === "201.1")?.text, "Updated answer");+ await f.app.emitMessage({+ channel: "C1",+ channel_type: "channel",+ user: "UBOT",+ bot_id: "BBOT",+ text: "ordinary malformed blocks",+ ts: "201.3",+ blocks: { unexpected: true },+ });+ assert.equal(f.core.ingests.flat().find((event: any) => event.ts === "201.3")?.text, "ordinary malformed blocks");+ await f.app.emitMessage({+ channel: "C1",+ channel_type: "channel",+ ...status,+ user: "U1",+ bot_id: undefined,+ ts: "202.1",+ });+ assert.ok(f.core.ingests.flat().some((event: any) => event.ts === "202.1"));+ } finally {+ await f.stop();+ }+});diff --git a/test/slack-mirror-context.test.ts b/test/slack-mirror-context.test.tsindex 592f4e3fe..6b4207a72 100644--- a/test/slack-mirror-context.test.ts+++ b/test/slack-mirror-context.test.ts@@ -400,3 +400,25 @@ test("automatic context keeps the thread parent and recent exchange but excludesfalse,);});++for (const source of ["live", "mirror"] as const) {+ test(`own status cards are excluded from ${source} history and backfill`, async () => {+ const f = fixture();+ const messages = [+ { user: "U1", ts: "1", text: "question" },+ { user: "UBOT", ts: "2", text: "Working", blocks: [{ type: "task_card", task_id: "qm_status:test" }] },+ { user: "UBOT", ts: "3", text: "ordinary answer" },+ { user: "UOTHER", ts: "4", text: "other bot task", blocks: [{ type: "task_card", task_id: "qm_status:other" }] },+ ];+ const read = createSlackHistoryReader({ core: f.core, ids, source });+ const client = { conversations: { history: async () => ({ messages }), replies: async () => ({ messages }) } };+ const result = await read(client, "C1", "1");+ assert.deepEqual(+ result.raw.map((m) => m.ts),+ ["1", "3", "4"],+ );+ assert.ok(!(await f.cache.readMessages("C1", { limit: 100 })).some((m) => m.ts === "2"));+ const expanded = await read(client, "C1", undefined, undefined, true);+ assert.ok(!expanded.raw.some((m) => m.ts === "2"));+ });+}diff --git a/test/slack-session-status.test.ts b/test/slack-session-status.test.tsnew file mode 100644index 000000000..aa02b4570--- /dev/null+++ b/test/slack-session-status.test.ts@@ -0,0 +1,373 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import { createMemoryMap } from "../src/persistence/durable-map.ts";+import { createNoopLeaderLease } from "../src/persistence/leader-lease.ts";+import { createFeatureFlagStore } from "../src/feature-flags.ts";+import { createSlackSessionStatus, type SlackSessionStatusState } from "../src/slack/session-status.ts";+import { createSlackCoreClient, type SlackCoreClientDeps } from "../src/api/slack-core-client.ts";+import { createTurnStream } from "../src/runs/turn-stream.ts";+import type { ProcessRecord } from "../src/processes/process-registry.ts";+import type { Session, Monitor } from "../src/types.ts";+import { isTerminal, type Run } from "../src/runs/run-store.ts";++function deferred() {+ let resolve!: () => void;+ const promise = new Promise<void>((done) => {+ resolve = done;+ });+ return { promise, resolve };+}++function fixture() {+ let at = 1_000;+ const store = createMemoryMap<SlackSessionStatusState>();+ const flags = createFeatureFlagStore(createMemoryMap());+ const records = new Map<string, Run>();+ const jobs: ProcessRecord[] = [];+ const watches: Monitor[] = [];+ const runs = {+ get: async (id: string) => records.get(id) ?? null,+ inFlightForThread: async (threadRef: string) =>+ [...records.values()].filter((run) => run.sessionId === threadRef && !isTerminal(run.status)),+ };+ const cards: Array<{ method: string; args: Record<string, unknown> }> = [];+ const client = {+ apiCall: async (method: string, args: Record<string, unknown>) => {+ assert.ok(["chat.postMessage", "chat.update"].includes(method));+ cards.push({ method, args });+ return { ts: method === "chat.update" ? String(args.ts) : `card.${cards.length}` };+ },+ };+ const manager = () =>+ createSlackSessionStatus(store, createNoopLeaderLease(), runs, flags, () => at, {+ processes: {+ liveByScope: async (scope) =>+ jobs.filter((job) => job.scopeId === scope && job.status === "running" && job.expiresAt > at),+ },+ monitors: { enabled: async () => watches.filter((watch) => watch.enabled) },+ publicWebUrl: "https://qm.example.test/web-ui/",+ sessions: {+ getByThread: async (threadRef) => (threadRef === "ch:C1:1.0" ? ({ id: "canonical-uuid" } as Session) : null),+ },+ });+ const status = manager();+ const add = (id: string) => {+ const run = {+ id,+ sessionId: "ch:C1:1.0",+ createdAt: at,+ status: "running",+ leaseExpiresAt: Number.MAX_SAFE_INTEGER,+ deliveryState: { replying: true },+ request: { conversation: { kind: "channel", channelRef: "C1", threadRef: "ch:C1:1.0" }, actor: { id: "U1" } },+ } as Run;+ records.set(id, run);+ return run;+ };+ const background = (sessionRef = "ch:C1:1.0") => {+ const job: ProcessRecord = {+ processId: "p1",+ scopeId: "channel:C1",+ kind: "background",+ command: "secret-command",+ startedAt: at,+ expiresAt: at + 3_600_000,+ status: "running",+ sessionRef,+ };+ jobs.push(job);+ return job;+ };+ const watch = (threadRef = "ch:C1:1.0") => {+ const monitor = {+ id: "m1",+ ownerScopeId: "channel:C1",+ processId: "p1",+ command: "secret-command",+ instructions: "secret-instructions",+ enabled: true,+ expiresAt: at + 3_600_000,+ threadRef,+ } as Monitor;+ watches.push(monitor);+ return monitor;+ };+ return {+ store,+ flags,+ records,+ runs,+ cards,+ client,+ manager,+ status,+ add,+ background,+ watch,+ enable: () => flags.setEnabled("slack_loading_indicator", "channel:C1", true, "admin"),+ start: (id: string, account = "T1:B1") => status.start(client, account, id, "C1", "1.0"),+ reconcile: () => status.reconcile(client, "T1:B1"),+ card: () => cards.at(-1)!.args.blocks as Array<Record<string, unknown>>,+ advance: (ms: number) => {+ at += ms;+ },+ };+}++test("cards require opt-in, a reply thread and non-private engagement", async () => {+ const f = fixture();+ const run = f.add("r1");+ await f.start(run.id);+ await f.enable();+ await f.status.start(f.client, "T1:B1", run.id, "D1");+ run.deliveryState = null;+ await f.start(run.id);+ run.deliveryState = { replying: true };+ run.request.privateSessionMessage = true;+ await f.start(run.id);+ assert.deepEqual(f.cards, []);+ assert.deepEqual(await f.store.all(), []);+});++test("concurrent starts share one card, terminal runs cannot clear active work, and later work gets a fresh card", async () => {+ const f = fixture();+ await f.enable();+ const old = f.add("old");+ const next = f.add("next");+ await Promise.all([f.start(old.id), f.start(next.id), f.start(old.id)]);+ assert.equal(f.cards.length, 1);+ old.status = "done";+ await f.reconcile();+ await f.start(old.id);+ assert.equal(f.cards.length, 1);+ next.status = "failed";+ await f.reconcile();+ assert.equal(f.card()[0]?.title, "No active work");+ assert.equal(f.card()[0]?.status, "complete");+ assert.deepEqual(await f.store.all(), []);+ const oldCard = f.card()[0]?.task_id;+ f.add("later");+ await f.start("later");+ assert.equal(f.cards.at(-1)?.method, "chat.postMessage");+ assert.notEqual(f.card()[0]?.task_id, oldCard);+});++test("restart preserves card identity and pending or expired-lease work is waiting, not working", async () => {+ const f = fixture();+ await f.enable();+ const run = f.add("r1");+ await f.start(run.id);+ const restarted = f.manager();+ await restarted.reconcile(f.client, "T1:B1");+ assert.equal(f.cards.length, 1);+ run.leaseExpiresAt = 0;+ await restarted.reconcile(f.client, "T1:B1");+ assert.equal(f.card()[0]?.title, "Waiting to resume");+ run.status = "pending";+ await restarted.reconcile(f.client, "T1:B1");+ assert.equal(f.cards.length, 2);+ run.status = "running";+ run.leaseExpiresAt = Number.MAX_SAFE_INTEGER;+ await restarted.reconcile(f.client, "T1:B1");+ assert.equal(f.card()[0]?.title, "Working");+ assert.ok(f.cards.slice(1).every((call) => call.args.ts === "card.1"));+});++test("background lifecycle survives restart and gains a canonical link after five minutes including waits", async () => {+ const f = fixture();+ await f.enable();+ const run = f.add("r1");+ await f.start(run.id);+ const job = f.background();+ run.status = "done";+ await f.reconcile();+ assert.equal(f.card()[0]?.title, "Background work");+ const monitor = f.watch();+ await f.manager().reconcile(f.client, "T1:B1");+ assert.equal(f.card()[0]?.title, "Monitoring");+ f.advance(300_000);+ await f.reconcile();+ assert.equal(f.card().length, 1);+ f.advance(1);+ await f.reconcile();+ assert.deepEqual(f.card()[1], {+ type: "context",+ elements: [{ type: "mrkdwn", text: "<https://qm.example.test/web-ui/s/canonical-uuid|Follow via QM Web>" }],+ });+ const wake = f.add("wake");+ await f.reconcile();+ assert.equal(f.card()[0]?.title, "Working");+ assert.equal((await f.store.all())[0]?.startedAt, 1_000);+ wake.status = "done";+ job.status = "exited";+ monitor.enabled = false;+ await f.reconcile();+ assert.equal(f.card()[0]?.title, "No active work");+ assert.equal(f.card().length, 2);+ assert.equal(f.cards.filter((call) => call.method === "chat.postMessage").length, 1);+ assert.ok(!JSON.stringify(f.cards).includes("secret-"));+});++test("unrelated, expired, disabled, private and nonengaged work never keeps a card active", async () => {+ const f = fixture();+ await f.enable();+ const run = f.add("r1");+ await f.start(run.id);+ f.background("other-thread");+ f.background().scopeId = "channel:other";+ f.background().kind = "dev-server";+ f.background().expiresAt = 0;+ f.watch("other-thread");+ f.watch().ownerScopeId = "channel:other";+ f.watch().enabled = false;+ f.watch().expiresAt = 0;+ f.add("quiet").deliveryState = null;+ f.add("private").request.privateSessionMessage = true;+ f.add("other").sessionId = "other-thread";+ run.status = "done";+ await f.reconcile();+ assert.equal(f.card()[0]?.title, "No active work");+});++test("opt-out settles only this account's card without cancelling work", async () => {+ const f = fixture();+ await f.enable();+ f.add("r1");+ await f.start("r1");+ await f.start("r1", "T2:B2");+ const job = f.background();+ await f.flags.setEnabled("slack_loading_indicator", "channel:C1", false, "admin");+ await f.reconcile();+ assert.equal(f.card()[0]?.title, "No active work");+ assert.equal(f.card()[0]?.status, "complete");+ assert.equal(job.status, "running");+ assert.deepEqual(+ (await f.store.all()).map((row) => row.account),+ ["T2:B2"],+ );+});++test("transient failures retry the same card after restart; inaccessible threads retire", async () => {+ const f = fixture();+ await f.enable();+ const run = f.add("r1");+ await f.start(run.id);+ const call = f.client.apiCall;+ f.client.apiCall = async () => {+ throw new Error("timeout");+ };+ run.status = "done";+ await f.reconcile();+ assert.equal((await f.store.all()).length, 1);+ f.client.apiCall = call;+ await f.manager().reconcile(f.client, "T1:B1");+ assert.equal(f.cards.at(-1)?.args.ts, "card.1");+ assert.deepEqual(await f.store.all(), []);+ f.add("new");+ f.client.apiCall = async () => {+ throw Object.assign(new Error("missing"), { data: { error: "channel_not_found" } });+ };+ await f.start("new");+ assert.deepEqual(await f.store.all(), []);+});++test("delayed insert after lease loss cannot replace a newer card", async () => {+ const f = fixture();+ await f.enable();+ const old = f.add("old");+ const lost = deferred(),+ blocked = deferred(),+ begun = deferred();+ const first = createSlackSessionStatus(+ {+ ...f.store,+ putIfAbsent: async (id, value) => {+ begun.resolve();+ await blocked.promise;+ return f.store.putIfAbsent(id, value);+ },+ },+ { hold: async (_key, fn) => fn(lost.promise) },+ f.runs,+ f.flags,+ );+ const pending = first.start(f.client, "T1:B1", old.id, "C1", "1.0");+ await begun.promise;+ lost.resolve();+ old.status = "done";+ f.add("new");+ await f.start("new");+ const newer = (await f.store.all())[0]!;+ blocked.resolve();+ await pending;+ assert.equal((await f.store.all())[0]?.cardId, newer.cardId);+ assert.equal(f.cards.length, 1);+});++for (const method of ["chat.postMessage", "chat.update"]) {+ test(`late ${method} after lease loss retains its receipt and repairs stale content`, async () => {+ const f = fixture();+ await f.enable();+ const run = f.add("r1");+ const lost = deferred(),+ blocked = deferred(),+ begun = deferred();+ const first = createSlackSessionStatus(f.store, { hold: async (_key, fn) => fn(lost.promise) }, f.runs, f.flags);+ if (method === "chat.update") {+ await f.start(run.id);+ run.status = "done";+ }+ const delayed = {+ apiCall: async (called: string, args: Record<string, unknown>) => {+ begun.resolve();+ await blocked.promise;+ return f.client.apiCall(called, args);+ },+ };+ const pending =+ method === "chat.update" ? first.reconcile(delayed, "T1:B1") : first.start(delayed, "T1:B1", run.id, "C1", "1.0");+ await begun.promise;+ lost.resolve();+ if (method === "chat.update") {+ f.add("new");+ await f.start("new");+ } else run.status = "done";+ blocked.resolve();+ await pending;+ await f.reconcile();+ assert.equal(f.cards.filter((call) => call.method === "chat.postMessage").length, 1);+ assert.equal(f.card()[0]?.title, method === "chat.update" ? "Working" : "No active work");+ });+}++test("core engagement is signaled once for local or durable replies, never quiet ambient turns", async () => {+ for (const mode of ["quiet", "local", "remote"]) {+ const stream = createTurnStream();+ let polls = 0,+ engaged = 0;+ const core = createSlackCoreClient({+ runs: {+ onTerminal() {},+ get: async () => {+ if (++polls === 1 && mode === "local") stream.begin("r1");+ return {+ id: "r1",+ status: polls < 3 ? "running" : "done",+ deliveryState: mode === "remote" ? { replying: true } : null,+ };+ },+ },+ turnStream: stream,+ tasks: { list: async () => [] },+ app: { getRun: async () => ({ result: { status: "silent" } }) },+ agentRequests: createMemoryMap(),+ } as unknown as SlackCoreClientDeps);+ await core.waitRun("r1", {+ onReplying: () => {+ engaged++;+ },+ });+ assert.equal(engaged, mode === "quiet" ? 0 : 1);+ stream.end("r1");+ }+});diff --git a/test/turn-stream.test.ts b/test/turn-stream.test.tsindex 5c88d4ef8..7f127d8d4 100644--- a/test/turn-stream.test.ts+++ b/test/turn-stream.test.ts@@ -326,6 +326,7 @@ test("a harvested first block is stripped from the final reply (never shown twic});const finished = await built.runs.waitFor(ack.runId!, 5_000);assert.equal(finished.status, "done");+ assert.equal(finished.deliveryState?.replying, true, "Slack engagement survives outside the worker stream");assert.equal(finished.result?.reply, "All clear — nothing broke.", "the acked preamble is stripped from the reply");} finally {await built.runtime.stop();@@ -452,3 +453,22 @@ test("goalViewFromEntry extracts goal snapshots from tool results and system entnull,);});++test("monitor wakes persist engagement after the reply gate", async () => {+ const built = buildApp(testConfig({ dataDir: mkdtempSync(join(tmpdir(), "ts-monitor-")), workers: 1 }));+ built.runtime.start();+ try {+ const ack = await built.app.turn({+ surface: "monitor",+ actor: { externalId: "U1" },+ conversation: { kind: "dm", threadRef: "t-monitor" },+ text: "!preamble Checking background results.",+ async: true,+ });+ const finished = await built.runs.waitFor(ack.runId!, 5_000);+ assert.equal(finished.status, "done");+ assert.equal(finished.deliveryState?.replying, true);+ } finally {+ await built.runtime.stop();+ }+});