The Open Framework for Building Agents
fix(slack): keep the thread status on the current work between model steps (#4202)
Andrew Barba0bf95b0c92f1
diff --git a/.changeset/slack-status-keeps-context.md b/.changeset/slack-status-keeps-context.mdnew file mode 100644index 000000000..428e3d506--- /dev/null+++ b/.changeset/slack-status-keeps-context.md@@ -0,0 +1,5 @@+---+"eve": patch+---++The default Slack thread status now keeps naming the latest work across model steps, including tool progress, reasoning, and long replies, instead of resetting to `Thinking...`. eve clears it while a turn waits on an approval, answer, or sign-in.diff --git a/.changeset/tui-readable-agent-names.md b/.changeset/tui-readable-agent-names.mdnew file mode 100644index 000000000..bc0ac3518--- /dev/null+++ b/.changeset/tui-readable-agent-names.md@@ -0,0 +1,5 @@+---+"eve": patch+---++The dev TUI now shows readable names for subagents and unlabeled tools, such as `subagent(worker)` for `code__worker` and `List issues` for `linear__list_issues`, using the same naming as the Slack status and task cards.diff --git a/docs/channels/slack.mdx b/docs/channels/slack.mdxindex 1a4bf9f32..34156a1ec 100644--- a/docs/channels/slack.mdx+++ b/docs/channels/slack.mdx@@ -457,20 +457,26 @@ The bases say where a call may go. `apiBaseUrl` is the base Slack Web API methodeve shows an agent's progress in two places. Short work, such as thinking or a tool call, appears in the thread status and never posts a message. [Tasks](/docs/tools/tasks), which keep working while the conversation continues, appear in a task card: one message per turn that eve updates in place. Replies post as ordinary messages, so the thread holds the conversation, the task card, and nothing else.-| Moment | Thread status |-| ---------------------------------- | ------------------------------------------------------------------------------- |-| A mention or DM arrives | `Thinking...`, right away, while the message hook is still deciding |-| The message hook drops the message | Cleared |-| The turn starts | `Working...` |-| The model reasons | The first line of its reasoning |-| The model calls tools | Its narration before the calls, or an action label such as `Search useEveAgent` |-| The turn waits on its tasks | `Waiting on researcher...`, or `Waiting on 3 tasks...` |-| The model starts its next step | `Reviewing results...` after a task finishes, otherwise `Thinking...` |-| A reply posts | Cleared by Slack |--Slack clears a thread status after two minutes without a message, so during a long wait the task card is what shows the work is still going.--Action labels follow the same rule as the task card titles described below, plus `+N more` when the model requests several actions at once. They leave out the model's own `task_wait` and `task_cancel` calls. Reasoning snippets build progressively: extensions of at least four characters appear immediately, while smaller streamed deltas use a five-second refresh interval to avoid one Slack request per token.+| Moment | Thread status |+| ------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- |+| A mention or DM arrives | `Thinking...`, right away, while the message hook is still deciding |+| The message hook drops the message | Cleared |+| The turn starts | `Thinking...` |+| The model reasons | Its latest reasoning heading, or its latest finished sentence |+| The model calls tools | Its narration before the calls, or the first action label, such as `Search useEveAgent`, plus `+N more` for the step's other calls |+| A tool reports progress | The tool's `label.delta` text |+| A tool finishes | The tool's `label.complete` text, when it defines one; otherwise the status stays |+| The model starts its next step | `Reviewing researcher's results...` after a task finishes, otherwise the same status again |+| The model streams a long reply | `Writing a reply...`, once the text runs past 280 characters |+| The turn waits on its tasks | `Waiting on researcher...`, or `Waiting on 3 tasks...` |+| The turn waits on an approval, answer, or sign-in | Cleared until the turn resumes, then the status it had |+| A reply posts | Cleared by Slack |++A model step never resets the status to a generic line. The status keeps naming the latest work until something newer replaces it, so a user watching the thread sees `Checking recent deploys`, then `Found 4 failed deploys`, then `Reading build logs`, without `Thinking...` in between.++Slack removes a thread status after two minutes without a message from the app, and clears it whenever the app posts in the thread. eve sets the current status again at each model step, after it posts a new task card, and as a tool reports progress. A tool that runs longer than two minutes without reporting progress loses its status. Report progress with [`label.delta`](/docs/tools#label-tool-activity), or run the work as a [task](/docs/tools/tasks), whose card shows it is still going.++Action labels follow the same rule as the task card titles described below. They leave out the model's own `task_wait` and `task_cancel` calls. Reasoning shows one piece at a time: a heading when the model titles its reasoning, as reasoning summaries do, otherwise the latest finished sentence. Each piece of reasoning, and each progress label, stays up for at least three seconds, so the status changes at a readable pace instead of sending a Slack request per token. Every status is cut to 50 characters at a word boundary.Replies up to 12,000 characters render inline. Longer replies are uploaded unchanged as a Markdown snippet named `eve-response.md` with a short in-thread note, which requires the `files:write` bot scope.diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.mdindex 9e1bd098b..f91701f77 100644--- a/docs/guides/dev-tui.md+++ b/docs/guides/dev-tui.md@@ -98,7 +98,9 @@ Type a message and press `Enter` to send it. When the agent asks a question or rThe activity line shows **Thinking** while the model reasons or waits to respond, **Generating** while it writes a response or tool input, and **Running** while tools execute. A blinking dot and elapsed time indicate progress, with token counts shown when available. While [tasks](../tools/tasks) work, the drawer header replaces this line: it shows the parent's current activity, task count, and turn elapsed time without token counts. **Waiting** means the parent is waiting on work; **Working** appears without a turn timer when tasks remain active between turns.-A task, such as a call to a subagent, writes one line to the transcript when it starts and one when it finishes, fails, or is stopped. The finished line names how long the task took and, for a subagent, what it did, such as `Read 3 files, Ran 2 commands`. Task starts use the same tool-call styling as synchronous calls. While tasks work, an activity drawer above the prompt shows each task's name, current activity, and elapsed time without repeating its launch prompt. Subagents use labels such as `subagent(self-modification)`, with elapsed time beside the name and the latest observed tool grouped beneath an elbow. The tool remains visible between calls rather than switching to a starting placeholder. During questions and approvals, activity stays visible above the request with a shared divider when screen space permits; the request takes priority on small terminals. Background work started by a followed subagent appears beneath that subagent; deeper work uses an ownership path instead of further indentation. The panel caps its height and prioritizes tasks needing approval when work overflows. The UI does not show the model's own `task_wait` and `task_cancel` calls; their effect appears as the **Waiting** header and a stopped task's line.+A tool call shows the tool's own `label`, or eve's copy for built-in tools such as `Read README.md`. Any other call shows a readable tool name without its extension or connection prefix, such as `List issues` for `linear__list_issues`. Approval prompts show the exact tool name unless the tool provides a title.++A task, such as a call to a subagent, writes one line to the transcript when it starts and one when it finishes, fails, or is stopped. The finished line names how long the task took and, for a subagent, what it did, such as `Read 3 files, Ran 2 commands`. Task starts use the same tool-call styling as synchronous calls. While tasks work, an activity drawer above the prompt shows each task's name, current activity, and elapsed time without repeating its launch prompt. Subagents use readable labels, such as `subagent(stock price)` for a `stock-price` subagent or `subagent(worker)` for the `code__worker` subagent of the code extension, with elapsed time beside the name and the latest observed tool grouped beneath an elbow. The tool remains visible between calls rather than switching to a starting placeholder. During questions and approvals, activity stays visible above the request with a shared divider when screen space permits; the request takes priority on small terminals. Background work started by a followed subagent appears beneath that subagent; deeper work uses an ownership path instead of further indentation. The panel caps its height and prioritizes tasks needing approval when work overflows. The UI does not show the model's own `task_wait` and `task_cancel` calls; their effect appears as the **Waiting** header and a stopped task's line.The prompt stays open while the agent works, including turns started elsewhere, such as a scheduled run. While a turn is running, `Enter` sends your message immediately as steering. Before assistant output begins, the runtime interrupts pending model generation and continues the same turn with your correction. Executing tools finish safely. After output begins, steering applies at the next workflow boundary and preserves streamed text.diff --git a/packages/eve/src/cli/dev/tui/task-activity.test.ts b/packages/eve/src/cli/dev/tui/task-activity.test.tsindex 524028c7c..5d3e7240d 100644--- a/packages/eve/src/cli/dev/tui/task-activity.test.ts+++ b/packages/eve/src/cli/dev/tui/task-activity.test.ts@@ -89,7 +89,7 @@ describe("live task panel", () => {});it("puts parent state and turn time in the header with breathing room around tasks", () => {- const rows = renderTaskPanelRows([task("self-modification__agent")], {+ const rows = renderTaskPanelRows([task("agent editor")], {width: 80,maxRows: 6,theme,diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.test.tsindex c79012899..a1e963761 100644--- a/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.test.ts@@ -3843,9 +3843,9 @@ describe("TerminalRenderer conversation", () => {];renderer.renderConversation(conversationOf(working, { working: true }));const during = screen.snapshot();- expect(during).toContain("▪ Delegate subagent(number_picker) Pick a number for Alice.");- expect(during).toMatch(/── Waiting · 1 task · \S+ ─+\n\n subagent\(number_picker\) \S+/);- expect(during).toMatch(/subagent\(number_picker\) \S+\n\n─+\n❯/);+ expect(during).toContain("▪ Delegate subagent(number picker) Pick a number for Alice.");+ expect(during).toMatch(/── Waiting · 1 task · \S+ ─+\n\n subagent\(number picker\) \S+/);+ expect(during).toMatch(/subagent\(number picker\) \S+\n\n─+\n❯/);expect(during).not.toContain("Starting");expect(countOccurrences(during, "Pick a number for Alice.")).toBe(1);expect(during).not.toContain("Waiting for");@@ -3862,14 +3862,14 @@ describe("TerminalRenderer conversation", () => {expect(screen.snapshot()).toContain("Approve wait_random_number?");expect(screen.snapshot()).toMatch(/── Waiting · 1 task/);expect(screen.snapshot()).toMatch(- /subagent\(number_picker\) \S+\n\n─+\n\n Approve wait_random_number\?/,+ /subagent\(number picker\) \S+\n\n─+\n\n Approve wait_random_number\?/,);- expect(countOccurrences(screen.snapshot(), " subagent(number_picker)")).toBe(1);+ expect(countOccurrences(screen.snapshot(), " subagent(number picker)")).toBe(1);input.enter();await expect(approval).resolves.toEqual({ approved: true });expect(screen.snapshot()).toContain("Waiting · 1 task");const prompt = readPrompt(renderer);- expect(screen.snapshot()).toMatch(/subagent\(number_picker\) \S+\n\n─+\n❯/);+ expect(screen.snapshot()).toMatch(/subagent\(number picker\) \S+\n\n─+\n❯/);renderer.renderConversation(conversationOf(@@ -3881,7 +3881,7 @@ describe("TerminalRenderer conversation", () => {),);const after = screen.snapshot();- expect(after).toMatch(/✓ subagent\(number_picker\) +finished in/);+ expect(after).toMatch(/✓ subagent\(number picker\) +finished in/);expect(after).not.toContain("Waiting · 1 task");renderer.requestInterrupt();await prompt.catch(() => {});diff --git a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts b/packages/eve/src/cli/dev/tui/tool-presentation.test.tsindex 23b8c5672..b0180d0ac 100644--- a/packages/eve/src/cli/dev/tui/tool-presentation.test.ts+++ b/packages/eve/src/cli/dev/tui/tool-presentation.test.ts@@ -13,7 +13,7 @@ describe("presentPreparingTool", () => {it("leads unknown tools with their name", () => {const presentation = presentPreparingTool("linear__list_issues");- expect(presentation.title).toBe("linear__list_issues …");+ expect(presentation.title).toBe("List issues …");expect(presentation.subtitle).toBe("");});});@@ -177,22 +177,22 @@ describe("presentTool", () => {it("falls back to the generic formatter for malformed input", () => {const presentation = presentTool("web_fetch", { format: "markdown" });- expect(presentation.title).toBe("web_fetch");+ expect(presentation.title).toBe("Web fetch");expect(presentation.subtitle).toContain('format="markdown"');});it("does not retain semantic copy for the removed task_sleep tool", () => {- expect(presentTool("task_sleep", { seconds: 30 }).title).toBe("task_sleep");+ expect(presentTool("task_sleep", { seconds: 30 }).title).toBe("Task sleep");});it("does not retain semantic copy for the removed task_update tool", () => {const presentation = presentTool("task_update", { message: "Checking the next region." });- expect(presentation.title).toBe("task_update");+ expect(presentation.title).toBe("Task update");expect(presentation.subtitle).toContain('message="Checking the next region."');expect(presentation.group).toBeUndefined();expect(presentation.doneTitle).toBeUndefined();expect(presentPreparingTool("task_update")).toMatchObject({- title: "task_update …",+ title: "Task update …",subtitle: "",});});@@ -210,13 +210,20 @@ describe("presentTool", () => {{ message: "Look up GOOG.\nDetails…" },{ isSubagent: true },);- expect(parsed.title).toBe("Delegate subagent(stock-price)");- expect(parsed.doneTitle).toBe("Delegated subagent(stock-price)");+ expect(parsed.title).toBe("Delegate subagent(stock price)");+ expect(parsed.doneTitle).toBe("Delegated subagent(stock price)");expect(parsed.subtitle).toBe("Look up GOOG.");// The tool's name carries the target, so it shows before args parse.expect(presentPreparingTool("stock-price", { isSubagent: true }).title).toBe(- "Delegate subagent(stock-price) …",+ "Delegate subagent(stock price) …",+ );+ // An extension's subagents go by their own name, and its `agent` by the extension's.+ expect(presentTool("code__worker", {}, { isSubagent: true }).title).toBe(+ "Delegate subagent(worker)",+ );+ expect(presentTool("code_review__agent", {}, { isSubagent: true }).title).toBe(+ "Delegate subagent(code review)",);const selfModification = presentTool("self-modification__agent",@@ -226,7 +233,7 @@ describe("presentTool", () => {expect(selfModification.title).toBe("Delegate agent editor");expect(selfModification.doneTitle).toBe("Delegated agent editor");// Without roster knowledge the generic formatter keeps its shape.- expect(presentTool("stock-price", { message: "x" }).title).toBe("stock-price");+ expect(presentTool("stock-price", { message: "x" }).title).toBe("Stock price");});it("names the self-modification subagent without its extension namespace", () => {@@ -239,7 +246,7 @@ describe("presentTool", () => {it("keeps unknown tools on the generic formatter", () => {const presentation = presentTool("linear__list_issues", { teamId: "T1" });- expect(presentation.title).toBe("linear__list_issues");+ expect(presentation.title).toBe("List issues");expect(presentation.subtitle).toContain('teamId="T1"');expect(presentation.group).toBeUndefined();});diff --git a/packages/eve/src/cli/dev/tui/tool-presentation.ts b/packages/eve/src/cli/dev/tui/tool-presentation.tsindex 3b7e339e9..6b8dff2ff 100644--- a/packages/eve/src/cli/dev/tui/tool-presentation.ts+++ b/packages/eve/src/cli/dev/tui/tool-presentation.ts@@ -1,5 +1,6 @@import { diffWriteDetail, type ToolDetailLine } from "./line-diff.js";import { stripTerminalControls } from "#cli/ui/terminal-text.js";+import { displayName, displayTitle } from "#shared/display-name.js";import { summarizeToolArgs, summarizeToolResult } from "./tool-format.js";/** Renderer-ready copy derived from a tool call without owning its lifecycle. */@@ -27,7 +28,7 @@ export interface ToolPresentationContext {/*** True when the tool dispatches a named subagent (each subagent exposes a* tool bearing its own name). The presentation reads as a delegation —- * `Delegate stock-price` — instead of a generic tool call.+ * `Delegate subagent(stock price)` — instead of a generic tool call.*/readonly isSubagent?: boolean;/** The tool's own `label.start` copy, used when eve has no copy of its own for the tool. */@@ -178,7 +179,7 @@ function presentWriteFileTool(const write = readWriteFileInput(toolName, input);if (write === undefined) {return {- title: toolName,+ title: toolDisplayTitle(toolName),subtitle: summarizeToolArgs(input),summarizeResult: summarizeToolResult,};@@ -285,12 +286,20 @@ export function presentTool(}return {- title: toolName,+ title: toolDisplayTitle(toolName),subtitle: summarizeToolArgs(input),summarizeResult: summarizeToolResult,};}+/**+ * A person's name for a tool with no copy of its own: `linear__list_issues` →+ * `List issues`.+ */+export function toolDisplayTitle(toolName: string): string {+ return displayTitle(toolBaseName(toolName));+}+/*** The bundled self-modification subagent's compiled name: its extension* namespace joined to `subagents/agent` by the compiler's `__` rule.@@ -312,18 +321,24 @@ export function isSelfModificationAgent(toolName: string): boolean {return toolBaseName(toolName) === SELF_MODIFICATION_AGENT_NAME;}-/** The name an agent task goes by in the delegate row, task line, and task panel. */+/**+ * The name an agent task goes by in the delegate row, task line, and task+ * panel, from its {@link agentDisplayName} and any `:N` ordinal.+ */export function agentTaskLabel(name: string): string {- const readable = name- .replace(/^self-modification__agent(?=:\d+$|$)/u, "agent editor")- .replace(/__agent(?=:\d+$|$)/u, "");- return /^subagent(?::\d+)?$/u.test(readable) || readable.startsWith("agent editor")- ? readable- : `subagent(${readable})`;+ return /^subagent(?::\d+)?$/u.test(name) || name.startsWith("agent editor")+ ? name+ : `subagent(${name})`;}++/**+ * A person's name for the agent a tool dispatches: `code__worker` →+ * `worker`. An extension's own subagent compiles to `<extension>__agent`, so+ * the extension names it.+ */export function agentDisplayName(toolName: string): string {const baseName = toolBaseName(toolName);- return AGENT_DISPLAY_NAMES.get(baseName) ?? baseName;+ return AGENT_DISPLAY_NAMES.get(baseName) ?? displayName(baseName.replace(/(?<=.)__agent$/u, ""));}/**@@ -351,7 +366,7 @@ export function presentPreparingTool(}const verb = baseName === "write_file" ? WRITE_FILE_VERB : BUILTIN_TOOL_COPY[baseName]?.verb;return {- title: `${verb ?? toolName} …`,+ title: `${verb ?? toolDisplayTitle(toolName)} …`,subtitle: "",summarizeResult: () => undefined,};diff --git a/packages/eve/src/cli/dev/tui/transcript-parts.ts b/packages/eve/src/cli/dev/tui/transcript-parts.tsindex 5341ab64f..39cd26f69 100644--- a/packages/eve/src/cli/dev/tui/transcript-parts.ts+++ b/packages/eve/src/cli/dev/tui/transcript-parts.ts@@ -23,6 +23,7 @@ import {agentTaskLabel,presentPreparingTool,presentTool,+ toolDisplayTitle,type ToolPresentationContext,} from "./tool-presentation.js";@@ -132,22 +133,23 @@ export function nestedTaskRecord(task: ConversationTask,block: Block,): TaskRecord {+ const name =+ task.kind === "agent"+ ? agentDisplayName(stripTerminalControls(part.toolName))+ : stripTerminalControls(toolDisplayTitle(part.toolName));return {callId,taskId: task.taskId,callIds: [part.toolCallId],kind: task.kind,- name:- task.kind === "agent"- ? agentDisplayName(stripTerminalControls(part.toolName))- : stripTerminalControls(part.toolName),+ name,toolName: part.toolName,input: part.input,label: undefined,purpose:task.kind === "agent"? agentTaskSummary(part.input)- : block.subtitle || (block.title === part.toolName ? undefined : block.title),+ : block.subtitle || (block.title === name ? undefined : block.title),startedAtMs: Date.now(),ended: false,};diff --git a/packages/eve/src/cli/dev/tui/transcript.test.ts b/packages/eve/src/cli/dev/tui/transcript.test.tsindex 3593c345b..638adc31e 100644--- a/packages/eve/src/cli/dev/tui/transcript.test.ts+++ b/packages/eve/src/cli/dev/tui/transcript.test.ts@@ -459,7 +459,7 @@ describe("ConversationTranscript", () => {transcript.project(view(started, true), options);expect(transcript.tasks[0]).toMatchObject({name: "research",- children: [{ name: "download", kind: "tool", startedAtMs: 0 }],+ children: [{ name: "Download", kind: "tool", startedAtMs: 0 }],});expect(transcript.tasks[0]!.childTools.size).toBe(0);vi.setSystemTime(12_000);diff --git a/packages/eve/src/public/channels/slack/action-status.ts b/packages/eve/src/public/channels/slack/action-status.tsindex b29c7707c..9dcd4d5d6 100644--- a/packages/eve/src/public/channels/slack/action-status.ts+++ b/packages/eve/src/public/channels/slack/action-status.ts@@ -9,18 +9,17 @@ import type { RuntimeActionRequest } from "#shared/action-types.js";import { displayName, displayTitle } from "#shared/display-name.js";import { AGENT_TOOL_NAME } from "#tools/framework/agent-contract.js";-/**- * The first call's label, or its tool or agent display title, plus `+N more`- * when the model requested several calls at once.- */-export function describeActionRequests(- actions: readonly RuntimeActionRequest[],+/** The call's start label, or its tool or agent display title. */+export function actionLabel(+ action: RuntimeActionRequest,presentation: ActionPresentationByCallId | undefined,): string {- const [first] = actions;- if (first === undefined) return "Working...";- const label = presentation?.[first.callId]?.label ?? displayTitle(actionRequestName(first));- return actions.length === 1 ? label : `${label} +${String(actions.length - 1)} more`;+ return presentation?.[action.callId]?.label ?? displayTitle(actionRequestName(action));+}++/** The first call's label, plus `+N more` when the model made several calls in one step. */+export function withMoreCalls(label: string, count: number): string {+ return count <= 1 ? label : `${label} +${String(count - 1)} more`;}/**@@ -35,3 +34,14 @@ export function waitingOnTasks(names: readonly string[]): string {? "Waiting on a task...": `Waiting on ${String(names.length)} tasks...`;}++/**+ * `Reviewing researcher's results...` when every settled task called the same+ * named agent, otherwise `Reviewing results...`. `null` stands for a task+ * that isn't a named agent call.+ */+export function reviewingResults(names: readonly (string | null)[]): string {+ const [first] = names;+ const named = first != null && first !== AGENT_TOOL_NAME && names.every((name) => name === first);+ return named ? `Reviewing ${displayName(first)}'s results...` : "Reviewing results...";+}diff --git a/packages/eve/src/public/channels/slack/defaults.test.ts b/packages/eve/src/public/channels/slack/defaults.test.tsindex e1c9de9bf..3fefb7662 100644--- a/packages/eve/src/public/channels/slack/defaults.test.ts+++ b/packages/eve/src/public/channels/slack/defaults.test.ts@@ -822,7 +822,7 @@ describe("defaultEvents turn.completed", () => {await defaultEvents["turn.started"]!(turn, channel, sessionCtx);await defaultEvents["turn.completed"]!({ ...turn, sequence: 1 }, channel, sessionCtx);- expect(startTyping.mock.calls).toEqual([["Working..."], []]);+ expect(startTyping.mock.calls).toEqual([["Thinking..."], []]);expect(post).not.toHaveBeenCalled();});});diff --git a/packages/eve/src/public/channels/slack/defaults.ts b/packages/eve/src/public/channels/slack/defaults.tsindex 9a88feb8f..957aa7504 100644--- a/packages/eve/src/public/channels/slack/defaults.ts+++ b/packages/eve/src/public/channels/slack/defaults.ts@@ -2,7 +2,12 @@ import { workingTaskNames } from "#channel/task-card.js";import type { SessionAuthContext } from "#channel/types.js";import { createLogger, extractErrorId, formatErrorHint } from "#internal/logging.js";-import { describeActionRequests, waitingOnTasks } from "#public/channels/slack/action-status.js";+import {+ actionLabel,+ reviewingResults,+ waitingOnTasks,+ withMoreCalls,+} from "#public/channels/slack/action-status.js";import { isTaskControlTool } from "#protocol/task-tools.js";import { buildSlackAuthContext, slackUserIdForPrincipal } from "#public/channels/slack/auth.js";import {@@ -21,18 +26,71 @@ import type {SlackChannelInternalEvents,SlackChannelState,SlackContext,+ SlackEventContext,SlackMentionResult,} from "#public/channels/slack/slackChannel.js";+import {+ clearStatus,+ hideStatus,+ reasoningStatus,+ showStatus,+} from "#public/channels/slack/thread-status.js";const log = createLogger("slack.defaults");-const REASONING_TYPING_REFRESH_INTERVAL_MS = 5_000;-const REASONING_TYPING_MIN_PROGRESS_CHARS = 4;-interface ReasoningAccumulator {+/** Each piece of reasoning, or a tool's progress, stays up at least this long so it can be read. */+const STATUS_HOLD_MS = 3_000;+/** Narration before tool calls rarely runs this long, so longer text is the reply being written. */+const WRITING_REPLY_MIN_CHARS = 280;++/**+ * What the current model step has streamed so far. One workflow step runs a+ * model call and delivers its events to the same state object, so this never+ * needs to survive serialization, and a new step starts empty.+ */+interface StepStream {+ /** The step's tool calls: the first call's label, or the model's narration, and how many. */+ calls: { readonly count: number; readonly label: string; readonly narrated: boolean } | null;+ /** The current reasoning block, and when a piece of it last showed. */+ reasoning: string;+ reasoningShownAtMs: number | null;+ replyChars: number;readonly stepIndex: number;- readonly text: string;readonly turnId: string;}-const reasoningByState = new WeakMap<SlackChannelState, ReasoningAccumulator>();+const streamByState = new WeakMap<SlackChannelState, StepStream>();++function stepStream(state: SlackChannelState, turnId: string, stepIndex: number): StepStream {+ const current = streamByState.get(state);+ if (current?.turnId === turnId && current.stepIndex === stepIndex) return current;+ const fresh: StepStream = {+ calls: null,+ reasoning: "",+ reasoningShownAtMs: null,+ replyChars: 0,+ stepIndex,+ turnId,+ };+ streamByState.set(state, fresh);+ return fresh;+}++function heldWithin(atMs: number | null | undefined, now: number): boolean {+ return atMs != null && now - atMs >= 0 && now - atMs < STATUS_HOLD_MS;+}++async function showReasoning(+ channel: SlackEventContext,+ stream: StepStream,+ options?: { readonly complete?: boolean },+): Promise<void> {+ const piece = reasoningStatus(stream.reasoning, options);+ if (piece === undefined) return;+ if (truncateTypingStatus(piece) === channel.state.threadStatus?.text) return;+ const now = Date.now();+ if (heldWithin(stream.reasoningShownAtMs, now)) return;+ await showStatus(channel, piece);+ stream.reasoningShownAtMs = now;+}interface SlackSemanticErrorSummary {readonly hint?: string;@@ -170,101 +228,120 @@ function firstNonEmptyLine(text: string): string | undefined {*/export const defaultEvents: SlackChannelInternalEvents = {...approvalEvents,+ // A turn held on a person's approval, answer, or sign-in isn't working, and+ // the prompt asking them says so. Its status comes back when it resumes.async "turn.waiting"(event, channel, _ctx) {+ if (event.on === "input") {+ await hideStatus(channel);+ return;+ }const working = workingTaskNames(channel.state.taskCards?.[event.turnId]?.turn);- if (working.length > 0) await channel.thread.startTyping(waitingOnTasks(working));+ if (working.length > 0) await showStatus(channel, waitingOnTasks(working));},// The turn's next model step reads the results, so `step.started` can say so.async "task.settled"(event, channel, _ctx) {- if (event.cancel === undefined) channel.state.pendingTaskResultsTurnId = event.turnId;+ if (event.cancel !== undefined) return;+ const pending = channel.state.pendingTaskResults;+ const names = pending?.turnId === event.turnId ? pending.names : [];+ const name = event.kind === "agent" && event.name !== undefined ? event.name : null;+ channel.state.pendingTaskResults = { names: [...names, name], turnId: event.turnId };},- // Each later step replaces the status left by the previous one, such as a- // finished tool's label or `Waiting on 3 tasks...`, which would otherwise- // linger until the model streams something. `turn.started` covers step 0.+ // A model step means nothing to someone reading the thread, so the status+ // keeps naming the work, such as the call that just finished, and is written+ // again so Slack doesn't time it out. Only task results the step is about to+ // read change it. `turn.started` covers step 0.async "step.started"(event, channel, _ctx) {if (event.stepIndex === 0) return;- const reviewing = channel.state.pendingTaskResultsTurnId === event.turnId;- channel.state.pendingTaskResultsTurnId = null;- await channel.thread.startTyping(reviewing ? "Reviewing results..." : "Thinking...");+ const pending = channel.state.pendingTaskResults;+ channel.state.pendingTaskResults = null;+ const status =+ pending?.turnId === event.turnId+ ? reviewingResults(pending.names)+ : (channel.state.threadStatus?.text ?? "Thinking...");+ await showStatus(channel, status, { force: true });},async "turn.started"(_event, channel, _ctx) {- channel.state.pendingTaskResultsTurnId = null;+ channel.state.pendingTaskResults = null;channel.state.pendingToolCallMessage = null;- channel.state.lastReasoningTypingAtMs = null;- channel.state.lastReasoningTypingStatus = null;- reasoningByState.delete(channel.state);- await channel.thread.startTyping("Working...");+ streamByState.delete(channel.state);+ await showStatus(channel, "Thinking...", { force: true });},// A reply clears the status, but a turn ended by an `endsTurn` tool posts// none, and Slack would otherwise show the status until it times out.async "turn.completed"(_event, channel, _ctx) {- await channel.thread.startTyping();+ await clearStatus(channel);},+ // Shows the newest heading or sentence, each for at least a few seconds, so+ // a long reasoning block reads as progress instead of its opening words.async "reasoning.appended"(event, channel, _ctx) {- const current = reasoningByState.get(channel.state);- const continuesCurrentBlock =- current?.turnId === event.turnId && current.stepIndex === event.stepIndex;- if (!continuesCurrentBlock) {- channel.state.lastReasoningTypingAtMs = null;- channel.state.lastReasoningTypingStatus = null;- }- const reasoning = (continuesCurrentBlock ? current.text : "") + event.reasoningDelta;- reasoningByState.set(channel.state, {- stepIndex: event.stepIndex,- text: reasoning,- turnId: event.turnId,- });- const line = firstNonEmptyLine(reasoning);- if (line === undefined) return;-- const status = truncateTypingStatus(line);- const lastStatus = channel.state.lastReasoningTypingStatus;- const isProgressiveExtension =- lastStatus !== null &&- lastStatus !== undefined &&- status.startsWith(lastStatus) &&- status.length >= lastStatus.length + REASONING_TYPING_MIN_PROGRESS_CHARS;- const now = Date.now();- const lastAt = channel.state.lastReasoningTypingAtMs;- if (!isProgressiveExtension && lastAt !== null && lastAt !== undefined) {- const elapsed = now - lastAt;- if (elapsed >= 0 && elapsed < REASONING_TYPING_REFRESH_INTERVAL_MS) return;- }-- await channel.thread.startTyping(status);- channel.state.lastReasoningTypingAtMs = now;- channel.state.lastReasoningTypingStatus = status;+ const stream = stepStream(channel.state, event.turnId, event.stepIndex);+ if (stream.reasoning === "") stream.reasoningShownAtMs = null;+ stream.reasoning += event.reasoningDelta;+ await showReasoning(channel, stream);},+ // The block's last sentence never shows while it streams unless it fills+ // the status, so a short one only shows once the block ends.async "reasoning.completed"(event, channel, _ctx) {- const current = reasoningByState.get(channel.state);- if (current?.turnId !== event.turnId || current.stepIndex !== event.stepIndex) return;- reasoningByState.delete(channel.state);- channel.state.lastReasoningTypingAtMs = null;- channel.state.lastReasoningTypingStatus = null;+ const stream = stepStream(channel.state, event.turnId, event.stepIndex);+ stream.reasoning = event.reasoning;+ await showReasoning(channel, stream, { complete: true });+ stream.reasoning = "";},+ async "message.appended"(event, channel, _ctx) {+ const stream = stepStream(channel.state, event.turnId, event.stepIndex);+ const before = stream.replyChars;+ stream.replyChars += event.messageDelta.length;+ if (before < WRITING_REPLY_MIN_CHARS && stream.replyChars >= WRITING_REPLY_MIN_CHARS) {+ await showStatus(channel, "Writing a reply...");+ }+ },++ // Calls in one step stream in one at a time, so the step keeps its first+ // label, or the model's narration, and counts the rest. Calls a tool makes+ // on the model's behalf, such as a connection tool, belong to their parent.async "actions.requested"(event, channel, _ctx) {- const buffered = channel.state.pendingToolCallMessage;+ const narration = channel.state.pendingToolCallMessage;channel.state.pendingToolCallMessage = null;- if (buffered) {- await channel.thread.startTyping(truncateTypingStatus(buffered));- return;- }const actions = event.actions.filter(- (action) => action.kind !== "tool-call" || !isTaskControlTool(action.toolName),+ (action) =>+ action.kind !== "tool-call" ||+ (!isTaskControlTool(action.toolName) && action.parentCallId === undefined),);- if (actions.length === 0) return;- await channel.thread.startTyping(- truncateTypingStatus(describeActionRequests(actions, event.presentation)),+ if (!narration && actions.length === 0) return;+ const stream = stepStream(channel.state, event.turnId, event.stepIndex);+ const calls =+ !narration && stream.calls+ ? { ...stream.calls, count: stream.calls.count + actions.length }+ : {+ count: actions.length,+ label: narration ?? actionLabel(actions[0]!, event.presentation),+ narrated: narration != null,+ };+ stream.calls = calls;+ await showStatus(+ channel,+ calls.narrated ? calls.label : withMoreCalls(calls.label, calls.count),);},+ async "action.partial"(event, channel, _ctx) {+ const label = event.presentation?.[event.result.callId]?.label;+ if (!label || heldWithin(channel.state.threadStatus?.atMs, Date.now())) return;+ await showStatus(channel, label);+ },++ async "action.result"(event, channel, _ctx) {+ const label = event.presentation?.[event.result.callId]?.label;+ if (label) await showStatus(channel, label);+ },+async "message.completed"(event, channel, _ctx) {if (event.finishReason === "tool-calls") {channel.state.pendingToolCallMessage = event.message@@ -274,9 +351,11 @@ export const defaultEvents: SlackChannelInternalEvents = {}channel.state.pendingToolCallMessage = null;if (!event.message) {- await channel.thread.startTyping();+ await clearStatus(channel);return;}+ // Slack clears the status when the reply posts.+ channel.state.threadStatus = null;await deliverCompletedSlackReply(channel, event.message, { turnId: event.turnId });},@@ -393,7 +472,7 @@ export const defaultEvents: SlackChannelInternalEvents = {async "authorization.completed"(event, channel, _ctx) {const displayName = event.authorization?.displayName ?? formatConnectionDisplayName(event.name);if (event.outcome === "authorized" && event.candidateId === undefined) {- await channel.thread.startTyping(`Connected to ${displayName}. Resuming...`);+ await showStatus(channel, `Connected to ${displayName}. Resuming...`, { force: true });}const pending = channel.state.pendingAuthMessageTs ?? {};diff --git a/packages/eve/src/public/channels/slack/limits.test.ts b/packages/eve/src/public/channels/slack/limits.test.tsindex 8928f00df..c3f9618c2 100644--- a/packages/eve/src/public/channels/slack/limits.test.ts+++ b/packages/eve/src/public/channels/slack/limits.test.ts@@ -52,6 +52,14 @@ describe("truncateTypingStatus", () => {expect(result.endsWith("...")).toBe(true);});+ it("cuts at a word boundary when one is near", () => {+ expect(+ truncateTypingStatus(+ "Need to inspect the implementation and verify the Slack typing status behavior.",+ ),+ ).toBe("Need to inspect the implementation and verify...");+ });+it("does not append ellipsis when the input is exactly at the limit", () => {const exact = "a".repeat(SLACK_TYPING_STATUS_MAX_LENGTH);expect(truncateTypingStatus(exact)).toBe(exact);diff --git a/packages/eve/src/public/channels/slack/limits.ts b/packages/eve/src/public/channels/slack/limits.tsindex 70334aa31..e2095c8ef 100644--- a/packages/eve/src/public/channels/slack/limits.ts+++ b/packages/eve/src/public/channels/slack/limits.ts@@ -69,11 +69,15 @@ export const SLACK_MODAL_TITLE_MAX_LENGTH = 24;* assistant-thread status does not render, trims, collapses runs of* whitespace into a single space, then truncates to* {@link SLACK_TYPING_STATUS_MAX_LENGTH} with a trailing ellipsis when- * needed.+ * needed, at a word boundary when one is near.*/export function truncateTypingStatus(status: string): string {const normalized = stripTypingStatusMarkdown(status).trim().replace(/\s+/gu, " ");- return truncateWithEllipsis(normalized, SLACK_TYPING_STATUS_MAX_LENGTH);+ if (normalized.length <= SLACK_TYPING_STATUS_MAX_LENGTH) return normalized;+ const cut = normalized.slice(0, SLACK_TYPING_STATUS_MAX_LENGTH - 3);+ const space = cut.lastIndexOf(" ");+ const words = space > SLACK_TYPING_STATUS_MAX_LENGTH / 2 ? cut.slice(0, space) : cut;+ return `${words.trimEnd()}...`;}/**diff --git a/packages/eve/src/public/channels/slack/slackChannel.test.ts b/packages/eve/src/public/channels/slack/slackChannel.test.tsindex e1fa1f55c..59553f27d 100644--- a/packages/eve/src/public/channels/slack/slackChannel.test.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.test.ts@@ -771,11 +771,13 @@ describe("slackChannel() default event handlers", () => {expect(slackStatuses(fetchMock)).toEqual(["Waiting on 3 tasks...","Waiting on reviewer...",+ // The fourth task's new card clears the status, so it shows again.+ "Waiting on reviewer...","Waiting on a task...",]);});- it("replaces the previous step's status when the model starts another step", async () => {+ it("keeps naming the work across model steps, and says when the next step reviews task results", async () => {const adapter = withState(getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),THREAD_STATE,@@ -789,11 +791,17 @@ describe("slackChannel() default event handlers", () => {await callEvent(adapter, stepStarted(0), ctx);await callEvent(adapter, taskStarted("c1", "researcher"), ctx);await callEvent(adapter, taskStarted("c2", "reviewer"), ctx);- await callEvent(adapter, makeEvent("turn.waiting", { sequence: 1, turnId: "t1" }), ctx);+ await callEvent(+ adapter,+ makeEvent("turn.waiting", { on: "tasks", sequence: 1, turnId: "t1" }),+ ctx,+ );await callEvent(adapter,makeEvent("task.settled", {callId: "c1",+ kind: "agent",+ name: "researcher",status: "completed",taskId: "researcher-1",turnId: "t1",@@ -801,7 +809,11 @@ describe("slackChannel() default event handlers", () => {ctx,);await callEvent(adapter, stepStarted(1), ctx);- await callEvent(adapter, makeEvent("turn.waiting", { sequence: 1, turnId: "t1" }), ctx);+ await callEvent(+ adapter,+ makeEvent("turn.waiting", { on: "tasks", sequence: 1, turnId: "t1" }),+ ctx,+ );await callEvent(adapter,makeEvent("actions.requested", {@@ -827,10 +839,11 @@ describe("slackChannel() default event handlers", () => {expect(slackStatuses(fetchMock)).toEqual(["Waiting on 2 tasks...",- "Reviewing results...",+ "Reviewing researcher's results...","Waiting on reviewer...","Search",- "Thinking...",+ // The next step writes the finished call's label again, so Slack keeps it.+ "Search",]);});@@ -943,13 +956,13 @@ describe("slackChannel() default event handlers", () => {expect(ctx.state.pendingToolCallMessage).toBeNull();});- it("shows the first call's start label in the typing status, or its display title, without the model's own task calls", async () => {+ it("shows a step's first call label, or its display title, and counts the step's other calls, without the model's own task calls or calls its tools make", async () => {const adapter = withState(getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),THREAD_STATE,);const ctx = buildAdapterContext(adapter, stubAccessor());- const requested = (toolNames: readonly string[]) =>+ const requested = (toolNames: readonly string[], stepIndex: number) =>makeEvent("actions.requested", {actions: toolNames.map((toolName) => ({callId: `call_${toolName}`,@@ -959,17 +972,38 @@ describe("slackChannel() default event handlers", () => {})),presentation: { call_search: { label: "Search checkout incidents" } },sequence: 0,- stepIndex: 0,+ stepIndex,turnId: "t1",});- await callEvent(adapter, requested(["task_wait"]), ctx);+ await callEvent(adapter, requested(["task_wait"], 0), ctx);expect(fetchMock).not.toHaveBeenCalled();- await callEvent(adapter, requested(["task_cancel", "search", "ops__deploy_preview"]), ctx);- await callEvent(adapter, requested(["task_cancel", "ops__deploy_preview"]), ctx);+ await callEvent(adapter, requested(["task_cancel", "search", "ops__deploy_preview"], 0), ctx);+ // Streamed calls arrive one at a time; the step keeps its first label.+ await callEvent(adapter, requested(["lookup"], 0), ctx);+ await callEvent(+ adapter,+ makeEvent("actions.requested", {+ actions: [+ {+ callId: "call_lookup:1",+ input: {},+ kind: "tool-call",+ parentCallId: "call_lookup",+ toolName: "linear__search_issues",+ },+ ],+ sequence: 0,+ stepIndex: 0,+ turnId: "t1",+ }),+ ctx,+ );+ await callEvent(adapter, requested(["task_cancel", "ops__deploy_preview"], 1), ctx);expect(slackStatuses(fetchMock)).toEqual(["Search checkout incidents +1 more",+ "Search checkout incidents +2 more","Deploy preview",]);});@@ -1420,8 +1454,8 @@ describe("slackChannel() default event handlers", () => {expect(body).toMatchObject({channel_id: "C01",thread_ts: "1700000000.000001",- status: "Working...",- loading_messages: ["Working..."],+ status: "Thinking...",+ loading_messages: ["Thinking..."],});});@@ -1481,41 +1515,66 @@ describe("slackChannel() default event handlers", () => {expect(onTurnStarted).toHaveBeenCalledOnce();});- it("reasoning.appended calls assistant.threads.setStatus with a truncated snippet", async () => {+ it("shows a reasoning block's latest finished sentence, each for a few seconds", async () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-06-18T12:00:00Z"));+ const adapter = withState(+ getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),+ THREAD_STATE,+ );+ const ctx = buildAdapterContext(adapter, stubAccessor());+ const reasoning = (reasoningDelta: string) =>+ makeEvent("reasoning.appended", { reasoningDelta, sequence: 0, stepIndex: 0, turnId: "t1" });++ // Nothing shows until a sentence finishes.+ await callEvent(adapter, reasoning("Need to inspect the implementation"), ctx);+ await callEvent(+ adapter,+ reasoning(" and verify the Slack typing status behavior before editing.\nThen"),+ ctx,+ );+ // Each piece stays up for a few seconds, then the newest one replaces it.+ vi.setSystemTime(new Date("2026-06-18T12:00:01Z"));+ await callEvent(adapter, reasoning(" compare the old labels. Finally"), ctx);+ vi.setSystemTime(new Date("2026-06-18T12:00:04Z"));+ await callEvent(adapter, reasoning(" check the docs table. Done"), ctx);++ expect(slackStatuses(fetchMock)).toEqual([+ "Need to inspect the implementation and verify...",+ "Finally check the docs table.",+ ]);+ });++ it("shows a reasoning block's short closing sentence once the block ends", async () => {const adapter = withState(getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),THREAD_STATE,);const ctx = buildAdapterContext(adapter, stubAccessor());- const longReasoning =- "Need to inspect the implementation and verify the Slack typing status behavior before editing.";+ const reasoning = "Checking the failed deploys.";await callEvent(adapter,makeEvent("reasoning.appended", {- reasoningDelta: `${longReasoning}\nThen continue.`,+ reasoningDelta: reasoning,sequence: 0,stepIndex: 0,turnId: "t1",}),ctx,);+ // It might still be streaming, so it waits for the block to end.+ expect(fetchMock).not.toHaveBeenCalled();+ await callEvent(+ adapter,+ makeEvent("reasoning.completed", { reasoning, sequence: 0, stepIndex: 0, turnId: "t1" }),+ ctx,+ );- expect(fetchMock).toHaveBeenCalledTimes(1);- const [url, init] = fetchMock.mock.calls[0]!;- expect(String(url)).toBe("https://slack.com/api/assistant.threads.setStatus");- const body = parseSlackRequestBody(init as RequestInit);- expect(body).toMatchObject({- channel_id: "C01",- thread_ts: "1700000000.000001",- });- expect((body.status as string).length).toBeLessThanOrEqual(50);- expect((body.status as string).endsWith("...")).toBe(true);- expect(body.loading_messages).toEqual([body.status]);- expect(ctx.state.lastReasoningTypingStatus).toBe(body.status);+ expect(slackStatuses(fetchMock)).toEqual([reasoning]);});- it("reasoning.appended immediately publishes progressive extensions of four characters", async () => {+ it("shows the latest heading of titled reasoning", async () => {vi.useFakeTimers();vi.setSystemTime(new Date("2026-06-18T12:00:00Z"));const adapter = withState(@@ -1523,26 +1582,21 @@ describe("slackChannel() default event handlers", () => {THREAD_STATE,);const ctx = buildAdapterContext(adapter, stubAccessor());- const reasoningEvent = (reasoningDelta: string) =>- makeEvent("reasoning.appended", {- reasoningDelta,- sequence: 0,- stepIndex: 0,- turnId: "t1",- });-- await callEvent(adapter, reasoningEvent("I"), ctx);- await callEvent(adapter, reasoningEvent(" ca"), ctx);- await callEvent(adapter, reasoningEvent("n"), ctx);+ const reasoning = (reasoningDelta: string) =>+ makeEvent("reasoning.appended", { reasoningDelta, sequence: 0, stepIndex: 0, turnId: "t1" });- const statuses = fetchMock.mock.calls.map(- ([, init]) => parseSlackRequestBody(init as RequestInit).status,+ await callEvent(+ adapter,+ reasoning("**Reviewing deploys**\n\nI listed yesterday's deploys. Two"),+ ctx,);- expect(statuses).toEqual(["I", "I can"]);- expect(ctx.state).not.toHaveProperty("reasoningText");+ vi.setSystemTime(new Date("2026-06-18T12:00:04Z"));+ await callEvent(adapter, reasoning(" failed.\n\n**Comparing build logs**\n\nThe"), ctx);++ expect(slackStatuses(fetchMock)).toEqual(["Reviewing deploys", "Comparing build logs"]);});- it("reasoning.appended refreshes a short extension after the throttle interval", async () => {+ it("shows a new reasoning block or step's first sentence without waiting", async () => {vi.useFakeTimers();vi.setSystemTime(new Date("2026-06-18T12:00:00Z"));const adapter = withState(@@ -1550,28 +1604,31 @@ describe("slackChannel() default event handlers", () => {THREAD_STATE,);const ctx = buildAdapterContext(adapter, stubAccessor());- const reasoningEvent = (reasoningDelta: string) =>- makeEvent("reasoning.appended", {- reasoningDelta,+ const reasoning = (reasoningDelta: string, stepIndex: number) =>+ makeEvent("reasoning.appended", { reasoningDelta, sequence: 0, stepIndex, turnId: "t1" });++ await callEvent(adapter, reasoning("The first block starts here. Then", 0), ctx);+ await callEvent(+ adapter,+ makeEvent("reasoning.completed", {+ reasoning: "The first block starts here. Then",sequence: 0,stepIndex: 0,turnId: "t1",- });-- await callEvent(adapter, reasoningEvent("Need"), ctx);- vi.setSystemTime(new Date("2026-06-18T12:00:01Z"));- await callEvent(adapter, reasoningEvent(" to"), ctx);- vi.setSystemTime(new Date("2026-06-18T12:00:05Z"));- await callEvent(adapter, reasoningEvent("."), ctx);-- expect(fetchMock).toHaveBeenCalledTimes(2);- const statuses = fetchMock.mock.calls.map(- ([, init]) => parseSlackRequestBody(init as RequestInit).status,+ }),+ ctx,);- expect(statuses).toEqual(["Need", "Need to."]);+ await callEvent(adapter, reasoning("The second block starts here. Then", 0), ctx);+ await callEvent(adapter, reasoning("The next step starts here. Then", 1), ctx);++ expect(slackStatuses(fetchMock)).toEqual([+ "The first block starts here.",+ "The second block starts here.",+ "The next step starts here.",+ ]);});- it("starts fresh reasoning status for completed blocks and new steps", async () => {+ it("shows a tool's progress, a few seconds apart, then its completion label", async () => {vi.useFakeTimers();vi.setSystemTime(new Date("2026-06-18T12:00:00Z"));const adapter = withState(@@ -1579,37 +1636,59 @@ describe("slackChannel() default event handlers", () => {THREAD_STATE,);const ctx = buildAdapterContext(adapter, stubAccessor());- const reasoningEvent = (reasoningDelta: string, stepIndex: number) =>- makeEvent("reasoning.appended", {- reasoningDelta,+ const result = { callId: "c1", output: {}, toolName: "build" };+ const partial = (label: string) =>+ makeEvent("action.partial", {+ presentation: { c1: { label } },+ result,sequence: 0,- stepIndex,+ stepIndex: 0,turnId: "t1",});- await callEvent(adapter, reasoningEvent("First block", 0), ctx);+ await callEvent(adapter, partial("Building 1 of 3 packages"), ctx);+ vi.setSystemTime(new Date("2026-06-18T12:00:01Z"));+ await callEvent(adapter, partial("Building 2 of 3 packages"), ctx);+ vi.setSystemTime(new Date("2026-06-18T12:00:04Z"));+ await callEvent(adapter, partial("Building 3 of 3 packages"), ctx);await callEvent(adapter,- makeEvent("reasoning.completed", {- reasoning: "First block",+ makeEvent("action.result", {+ presentation: { c1: { label: "Built 3 packages" } },+ result,sequence: 0,+ status: "completed",stepIndex: 0,turnId: "t1",}),ctx,);- await callEvent(adapter, reasoningEvent("Second block", 0), ctx);- await callEvent(adapter, reasoningEvent("Next step", 1), ctx);- const statuses = fetchMock.mock.calls.map(- ([, init]) => parseSlackRequestBody(init as RequestInit).status,+ expect(slackStatuses(fetchMock)).toEqual([+ "Building 1 of 3 packages",+ "Building 3 of 3 packages",+ "Built 3 packages",+ ]);+ });++ it("says it is writing a reply once streamed text runs longer than narration", async () => {+ const adapter = withState(+ getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),+ THREAD_STATE,);- expect(statuses).toEqual(["First block", "Second block", "Next step"]);+ const ctx = buildAdapterContext(adapter, stubAccessor());+ const appended = (messageDelta: string) =>+ makeEvent("message.appended", { messageDelta, sequence: 0, stepIndex: 0, turnId: "t1" });++ await callEvent(adapter, appended("a".repeat(200)), ctx);+ expect(fetchMock).not.toHaveBeenCalled();+ await callEvent(adapter, appended("b".repeat(100)), ctx);+ await callEvent(adapter, appended("c".repeat(100)), ctx);++ expect(slackStatuses(fetchMock)).toEqual(["Writing a reply..."]);});- it("turn.started resets reasoning status throttling", async () => {- vi.useFakeTimers();- vi.setSystemTime(new Date("2026-06-18T12:00:00Z"));+ it("clears the status while a turn waits on a person, and shows it again when the turn resumes", async () => {const adapter = withState(getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),THREAD_STATE,@@ -1618,36 +1697,67 @@ describe("slackChannel() default event handlers", () => {await callEvent(adapter,- makeEvent("reasoning.appended", {- reasoningDelta: "Need to inspect the repo.",+ makeEvent("actions.requested", {+ actions: [{ callId: "call_1", input: {}, kind: "tool-call", toolName: "deploy_preview" }],sequence: 0,stepIndex: 0,turnId: "t1",}),ctx,);- vi.setSystemTime(new Date("2026-06-18T12:00:01Z"));await callEvent(adapter,- makeEvent("turn.started", { sequence: 0, stepIndex: 0, turnId: "t2" }),+ makeEvent("turn.waiting", { on: "input", sequence: 0, turnId: "t1" }),ctx,);await callEvent(adapter,- makeEvent("reasoning.appended", {- reasoningDelta: "Fresh turn reasoning.",- sequence: 1,+ makeEvent("step.started", { modelId: "test", sequence: 0, stepIndex: 1, turnId: "t1" }),+ ctx,+ );++ expect(slackStatuses(fetchMock)).toEqual(["Deploy preview", "", "Deploy preview"]);+ });++ it("shows the status again after posting a new task card, which Slack clears it for", async () => {+ const adapter = withState(+ getAdapter(slackChannel({ credentials: { botToken: "xoxb-test" } })),+ THREAD_STATE,+ );+ const ctx = buildAdapterContext(adapter, stubAccessor());++ await callEvent(+ adapter,+ makeEvent("actions.requested", {+ actions: [{ callId: "c1", input: {}, kind: "tool-call", toolName: "researcher" }],+ presentation: { c1: { label: "Researcher: Find the March incidents" } },+ sequence: 0,stepIndex: 0,- turnId: "t2",+ turnId: "t1",}),ctx,);-- expect(fetchMock).toHaveBeenCalledTimes(3);- const statuses = fetchMock.mock.calls.map(- ([, init]) => parseSlackRequestBody(init as RequestInit).status,+ await callEvent(+ adapter,+ makeEvent("task.started", {+ callId: "c1",+ kind: "agent",+ name: "researcher",+ taskId: "researcher-1",+ turnId: "t1",+ }),+ ctx,);- expect(statuses).toEqual(["Need to inspect the repo.", "Working...", "Fresh turn reasoning."]);++ expect(slackOperations(fetchMock)).toEqual([+ "assistant.threads.setStatus",+ "chat.postMessage",+ "assistant.threads.setStatus",+ ]);+ expect(slackStatuses(fetchMock)).toEqual([+ "Researcher: Find the March incidents",+ "Researcher: Find the March incidents",+ ]);});it("turn.failed posts a semantic error's remediation hint", async () => {diff --git a/packages/eve/src/public/channels/slack/slackChannel.ts b/packages/eve/src/public/channels/slack/slackChannel.tsindex 6bc565e81..bcb14ca6d 100644--- a/packages/eve/src/public/channels/slack/slackChannel.ts+++ b/packages/eve/src/public/channels/slack/slackChannel.ts@@ -63,6 +63,7 @@ import {type SlackTaskCardState,withTaskCards,} from "#public/channels/slack/task-card.js";+import type { SlackThreadStatus } from "#public/channels/slack/thread-status.js";import {parseMessageEvent,type SlackEvent,@@ -238,12 +239,10 @@ export interface SlackChannelState {*/pendingToolCallMessage?: string | null;/**- * Last reasoning-derived typing indicator sent by the default- * `reasoning.appended` handler. Used to surface substantial progressive- * extensions immediately while throttling smaller streamed deltas.+ * The thread status the default renderer last set. A later model step shows+ * it again, as does a new task card, which Slack clears the status for.*/- lastReasoningTypingAtMs?: number | null;- lastReasoningTypingStatus?: string | null;+ threadStatus?: SlackThreadStatus | null;/*** Connection name to Slack message ts. Each entry is the public* link-free status post created by the default@@ -259,11 +258,14 @@ export interface SlackChannelState {*/taskCards?: Record<string, SlackTaskCardState> | null;/**- * The turn with a task that settled since its last model step. The default- * `step.started` handler shows `Reviewing results...` for the step that reads- * the results.+ * Tasks that settled since the turn's last model step: each named agent, or+ * `null` for another task. The default `step.started` handler shows+ * `Reviewing results...` for the step that reads them.*/- pendingTaskResultsTurnId?: string | null;+ pendingTaskResults?: {+ readonly names: readonly (string | null)[];+ readonly turnId: string;+ } | null;/*** Principal id to Slack user id, recorded as each message or input response* is delivered. Default handlers use it to address the principal named on@@ -870,8 +872,6 @@ export function slackChannel(config: SlackChannelConfig = {}): SlackChannel {triggeringUserId: null,triggeringMessageTs: null,pendingToolCallMessage: null,- lastReasoningTypingAtMs: null,- lastReasoningTypingStatus: null,pendingAuthMessageTs: {},pendingApprovalCards: {},slackUsersByPrincipal: {},diff --git a/packages/eve/src/public/channels/slack/task-card.ts b/packages/eve/src/public/channels/slack/task-card.tsindex 67b8d59a2..a1be16d0d 100644--- a/packages/eve/src/public/channels/slack/task-card.ts+++ b/packages/eve/src/public/channels/slack/task-card.ts@@ -17,6 +17,7 @@ import type { SlackHandle } from "#public/channels/slack/api.js";import type { BlockKitBlock } from "#public/channels/slack/blocks.js";import { truncateMessageText } from "#public/channels/slack/limits.js";import type { SlackTaskCard } from "#public/channels/slack/renderers.js";+import { restoreStatus } from "#public/channels/slack/thread-status.js";import type {SlackChannelInternalEvents,SlackChannelState,@@ -406,6 +407,8 @@ async function writeTaskCard(...channel.state.taskCards,[turnId]: { fingerprint, ts, turn: current.turn },};+ // Slack clears the thread status when the app posts, but the turn works on.+ if (ts !== current.ts && view.state === "working") await restoreStatus(channel);}}if (view.state === "finished") forgetTurn(channel.state, turnId);diff --git a/packages/eve/src/public/channels/slack/thread-status.ts b/packages/eve/src/public/channels/slack/thread-status.tsnew file mode 100644index 000000000..f893aaf53--- /dev/null+++ b/packages/eve/src/public/channels/slack/thread-status.ts@@ -0,0 +1,103 @@+/**+ * The thread status eve's default renderer shows while a turn works. It keeps+ * the last status it set, so a later model step, or a task card post that+ * Slack clears the status for, can show it again instead of a generic line.+ */+import {+ SLACK_TYPING_STATUS_MAX_LENGTH,+ truncateTypingStatus,+} from "#public/channels/slack/limits.js";+import type { SlackEventContext } from "#public/channels/slack/slackChannel.js";++/**+ * Slack drops a status two minutes after it was set. One with the same text+ * set more recently than this is still showing, so it isn't written again.+ */+const STATUS_REFRESH_MS = 30_000;+/** Shorter reasoning sentences, such as `Okay.`, say nothing about the work. */+const MIN_REASONING_PIECE_LENGTH = 12;++/** The status eve's default renderer last set in the thread. */+export interface SlackThreadStatus {+ readonly atMs: number;+ readonly text: string;+}++/**+ * Sets the thread status, unless the same text is already showing. `force`+ * writes it anyway, for moments Slack may have cleared it, and so a long turn+ * keeps it from timing out.+ */+export async function showStatus(+ channel: SlackEventContext,+ text: string,+ options?: { readonly force?: boolean },+): Promise<void> {+ const status = truncateTypingStatus(text);+ const now = Date.now();+ const current = channel.state.threadStatus;+ const showing =+ current?.text === status && now - current.atMs >= 0 && now - current.atMs < STATUS_REFRESH_MS;+ if (showing && options?.force !== true) return;+ await channel.thread.startTyping(status);+ channel.state.threadStatus = { atMs: now, text: status };+}++/** Shows the last status again, if any. */+export async function restoreStatus(channel: SlackEventContext): Promise<void> {+ const current = channel.state.threadStatus;+ if (current) await showStatus(channel, current.text, { force: true });+}++/**+ * Clears the thread status but keeps its text, so the turn shows it again when+ * it resumes. It is no longer showing, so the next write always goes out.+ */+export async function hideStatus(channel: SlackEventContext): Promise<void> {+ const current = channel.state.threadStatus;+ if (current) channel.state.threadStatus = { ...current, atMs: 0 };+ await channel.thread.startTyping();+}++/** Clears the thread status and forgets it: the turn has nothing more to show. */+export async function clearStatus(channel: SlackEventContext): Promise<void> {+ channel.state.threadStatus = null;+ await channel.thread.startTyping();+}++const HEADING = /(?:^|\n)[ \t]*\*\*([^*\n]+)\*\*/gu;+// Same boundary as `firstSentence`: `e.g. the` and `No. 4035` stay whole.+const SENTENCE_BOUNDARY = /(?<=[.!?])(?<!(?:^|\s)\d{1,2}\.)\s+(?=[\p{Lu}"'`(])/u;+const LIST_MARKER = /^(?:[-*+]|\d{1,2}[.)])\s+/u;++/**+ * The newest readable piece of a reasoning block so far: its latest heading+ * when the model titles its reasoning, as reasoning summaries do, otherwise+ * its latest finished sentence. A sentence still streaming counts once it+ * fills the status, so the status never shows half a short sentence. A+ * `complete` block has nothing streaming: its last sentence is finished.+ */+export function reasoningStatus(+ reasoning: string,+ options?: { readonly complete?: boolean },+): string | undefined {+ const heading = [...reasoning.matchAll(HEADING)].findLast((match) => match[1]!.trim() !== "");+ if (heading) return heading[1]!.trim();++ const pieces = reasoning+ .split(/\r?\n/u)+ .flatMap((line) => line.split(SENTENCE_BOUNDARY))+ .map((piece) => piece.trim().replace(LIST_MARKER, ""));+ const streaming = options?.complete === true ? -1 : pieces.length - 1;+ for (let index = pieces.length - 1; index >= 0; index -= 1) {+ const piece = pieces[index]!;+ const minLength =+ index === streaming ? SLACK_TYPING_STATUS_MAX_LENGTH : MIN_REASONING_PIECE_LENGTH;+ if (piece.length >= minLength && isProse(piece)) return piece;+ }+ return undefined;+}++function isProse(piece: string): boolean {+ return !piece.startsWith("```") && /\p{L}/u.test(piece);+}diff --git a/packages/eve/test/tui-client/tui-subagents-weather.ts b/packages/eve/test/tui-client/tui-subagents-weather.tsindex 0e7f25d09..71342e5b4 100644--- a/packages/eve/test/tui-client/tui-subagents-weather.ts+++ b/packages/eve/test/tui-client/tui-subagents-weather.ts@@ -17,13 +17,13 @@ import { theme } from "./lib/theme.ts";* landing under `stepIndex: 0` and collapsing into one box.** Pass conditions:- * 1. A `Delegate subagent(stock-price)` start line exists.+ * 1. A `Delegate subagent(stock price)` start line exists.* 2. The task panel asks for approval of the child's `get_stock_price`* call, and the approval prompt accepts it.* 3. NO parent-level `get_stock_price` tool row exists (proves the* parent-tool suppression for child tool calls removes the stale* block, not just blocks future renders).- * 4. The task ends on a `✓ stock-price` line.+ * 4. The task ends on a `✓ subagent(stock price)` line.* 5. The parent's final assistant reply (a top-level `▲` section)* contains the price.*/@@ -70,7 +70,7 @@ run(WEATHER_SMOKE_TARGET, async (target) => {input.enter();// The task's start line appears once the parent delegates.- await waitForCondition(() => screen.snapshot().includes("Delegate subagent(stock-price)"), {+ await waitForCondition(() => screen.snapshot().includes("Delegate subagent(stock price)"), {timeoutMs: 120_000,label: "task start line",onTimeout: () => screen.snapshot(),@@ -94,7 +94,7 @@ run(WEATHER_SMOKE_TARGET, async (target) => {input.emit("data", Buffer.from("y"));console.log(theme.muted("[tui-weather] approved get_stock_price"));- await waitForCondition(() => screen.snapshot().includes("✓ subagent(stock-price)"), {+ await waitForCondition(() => screen.snapshot().includes("✓ subagent(stock price)"), {timeoutMs: 120_000,label: "task end line",onTimeout: () => screen.snapshot(),diff --git a/packages/eve/test/tui-client/tui-subagents.ts b/packages/eve/test/tui-client/tui-subagents.tsindex c79733780..4c66367da 100644--- a/packages/eve/test/tui-client/tui-subagents.ts+++ b/packages/eve/test/tui-client/tui-subagents.ts@@ -19,8 +19,8 @@ import { theme } from "./lib/theme.ts";* 1. Start the apps/fixtures/agent-tui-client server.* 2. Boot an `EveTUIRunner` with a mock terminal.* 3. Type the same delegation prompt the non-TUI subagent smoke uses.- * 4. Wait for the `Delegate subagent(echo-marker)` start line to appear.- * 5. Wait for the `✓ subagent(echo-marker)` end line once the task settles.+ * 4. Wait for the `Delegate subagent(echo marker)` start line to appear.+ * 5. Wait for the `✓ subagent(echo marker)` end line once the task settles.* 6. Verify the parent assistant message contains the token. The* rendering side-channel must not have broken the harness path.*/@@ -53,10 +53,10 @@ run({ app: "agent-tui-client", kind: "local-build" }, async (target) => {);input.enter();- await screen.waitForText("Delegate subagent(echo-marker)", 90_000);+ await screen.waitForText("Delegate subagent(echo marker)", 90_000);console.log(theme.muted("[tui-subagents] task start line appeared"));- await screen.waitForText("✓ subagent(echo-marker)", 90_000);+ await screen.waitForText("✓ subagent(echo marker)", 90_000);console.log(theme.muted("[tui-subagents] task end line appeared"));// The verbatim echo must land in a top-level `▲`-prefixed assistant