8000 feat(slack): offer background tasks in channels by geminixiang · Pull Request #193 · geminixiang/mikan · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/adr/0021-tasks-as-background-child-conversations.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ The restart rows ran against a local daemon on a test Slack workspace with a rea
8. **Status and stop come from pi-durable state.** Task membership, acknowledgements, and run state are read from pi-durable since the change after 1.2.2; the current step still comes from the runtime while this process runs the task. `task_status` reads each child's live run instead of the office log. Stop aborts the child. Steering stays as it is: Jev classifies a reply, and a steer is a `whenBusy: "steer"` submission to the child.
9. **Tasks open in three steps**, each after the previous one is stable:
- Top-level Slack DMs, as today.
- Top-level Slack channel messages, which start a task thread as in DMs.
- Top-level Slack channel messages, which start a task thread as in DMs. Opened after 1.5.1: a mention in the task thread is routed like a DM task thread reply, and only the requester steers the task.
- Threads, where the task runs in the same thread with its own child conversation and queue, so the thread keeps answering while the task works. Replies are routed by Jev as in DMs, and task messages carry a label so they stand apart from the thread's conversation.

## Considered Options
Expand Down
14 changes: 9 additions & 5 deletions src/adapters/slack/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,11 @@ This directory implements the Slack platform adapter and Slack-specific session/
- Rotation revokes the previous access token, so the new pair is saved before any other call, and two installs sharing one token revoke each other's.
- Slack sets some fields itself and ignores what is sent for them: `features.app_home.agent_tasks_enabled` is on for apps created after Slack added it and absent on older ones. The comparison skips these fields; otherwise every start would update the app.

## DM tasks
## Tasks

Top-level DM responders expose `startTask(message, task)`. Admission posts a
Top-level responders, in DMs and channels, expose `startTask(message, task)`. Admission posts a
persistent acknowledgement, creates the task's session as a child conversation
owned by a background task of the DM session whose input holds the
owned by a background task of the requesting session whose input holds the
acknowledgement (`SessionStore.openTask`, ADR 0021), and queues a self-contained task plus
the original attachments under that root. Task output uses the thread responder; it does not
replace the acknowledgement. Ordinary event scheduling is unchanged.
Expand All @@ -54,8 +54,12 @@ stop first; top-level attachments are a normal turn.
Without Jev the regex status shortcut decides `status`, thread text is tried as
steering, and top-level text is a normal turn — the pre-Jev behavior. Idle
threads use normal prompt execution (including explicit continuation after
stop). Stop keeps its magic-word path. Shared channels and non-task threads
retain their existing trigger/queue policy. Which threads are tasks, their
stop). Stop keeps its magic-word path. In a channel, only a mention in a task
thread takes this path, because other people talk there too: unmentioned thread
replies and top-level mentions keep the channel's trigger/queue policy, and a
top-level questio 8000 n about a task is a normal turn that can call `task_status`.
Steering accepts only the task's requester (`steerRun`); anyone in the channel can
ask for status. Non-task threads retain their existing trigger/queue policy. Which threads are tasks, their
acknowledgements, and their run state come from pi-durable (`SessionStore.listTasks`
and `isTask`), not from the office log, so they survive a restart or a lost log.
Task threads started before 1.1.0 were ordinary thread sessions and are not
Expand Down
35 changes: 19 additions & 16 deletions src/adapters/slack/bot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -300,20 +300,18 @@ export class SlackMessagingBot implements MessagingBot {
const context = createSlackAdapters(event, this, {
replyMode: this.resolveReplyMode(event.address),
});
if (event.conversationKind === "direct") {
context.responder.getTaskStatus = (key) =>
querySlackTasks(
this.office(event.channel),
event.channel,
this.handler
.getRunningSessions()
.filter(
(s) => s.address.platform === "slack" && s.address.conversationId === event.channel,
),
key,
);
}
if (event.conversationKind === "direct" && event.thread_ts) {
context.responder.getTaskStatus = (key) =>
querySlackTasks(
this.office(event.channel),
event.channel,
this.handler
.getRunningSessions()
.filter(
(s) => s.address.platform === "slack" && s.address.conversationId === event.channel,
),
key,
);
if (event.thread_ts) {
const threadTs = event.thread_ts;
let notified = false;
context.responder.notifyCompletion = async () => {
Expand All @@ -324,7 +322,7 @@ export class SlackMessagingBot implements MessagingBot {
this.logBotResponse(event.channel, text, ts, threadTs);
};
}
if (event.conversationKind === "direct" && !event.thread_ts) {
if (!event.thread_ts) {
context.responder.startTask = async (message, task) => {
if (this.stopped) throw new Error("Slack is shutting down; task was not started.");
await context.responder.deleteResponse();
Expand Down Expand Up @@ -1341,14 +1339,19 @@ export class SlackMessagingBot implements MessagingBot {
return;
}

const taskControl = !!e.thread_ts && (await this.isTaskThread(e.channel, e.thread_ts));
if (taskControl) {
ack();
if (await this.deliverTaskUpdate(slackEvent, attachmentsPromise)) return;
}
const intake = this.processSlackMessageIntake({
event: slackEvent,
attachmentsPromise,
queueKey: await this.resolveQueueKey(e.channel, sessionKey),
addressed: true,
});

ack();
if (!taskControl) ack();
await intake;
}

Expand Down
7 changes: 4 additions & 3 deletions src/harness/README.md
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -273,7 +273,7 @@ runtimes must use distinct names where separate browsers are desired.
- Session file naming, chat synchronization, and thread lineage stay
in `src/sessions/`.

## DM task handoff
## Task handoff

`start_task` is offered only when the active responder supports task admission. The native
`before_tool` hook blocks every call in a mixed handoff/effect batch; a successful
Expand All @@ -297,8 +297,9 @@ The marker deliberately precedes the checks; do not move it after them:
- A rejected steer is not lost silently. Every rejection is posted back telling
the user to send again or stop first, so syncing the original as well would
show the model the same instruction twice.
- The current-actor check is defensive. Only Slack one-to-one DMs (`im`) reach
steering, so a different person cannot steer someone else's task there.
- The current-actor check keeps a channel task to its requester: anyone in the
channel can mention the bot in the task thread, and only the requester's text
steers it. Others get the rejection notice.

`task_status` is a responder-bound read-only query, advertised only when supported. It exposes no cross-office task lookup.
`SessionStore.inspectExecution` reads the live run and mikan's run record from a
4 changes: 2 additions & 2 deletions src/harness/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,9 +207,9 @@ function buildContextPrompt(input: BuildSystemPromptOptions, paths: RuntimePromp
platform.name === "slack"
? `
## Slack Tasks
- In top-level Slack DMs, use start_task for multi-step investigations, changes/tests, or long waits so the user can keep chatting. Write a short, casual acknowledgement like a helpful colleague (e.g. 好,我來整理一下,弄好再通知你), not a formal restatement of the task. Do not invent an ETA. Separately provide a self-contained task with constraints and attachment paths. Call it alone before executing the work.
- In top-level Slack messages, in DMs and channels alike, use start_task for multi-step investigations, changes/tests, or long waits so the user can keep chatting. Write a short, casual acknowledgement like a helpful colleague (e.g. 好,我來整理一下,弄好再通知你), not a formal restatement of the task. Do not invent an ETA. Separately provide a self-contained task with constraints and attachment paths. Call it alone before executing the work.
- For questions about task progress, always call task_status before answering. Its observations are the only authority for current task status. Never infer progress, completion, or an ETA from elapsed time or your earlier promises. acknowledgement is only the original task description, NOT live progress. Only currentTool describes a current operation; if absent, say it is still running without inventing a phase. If multiple tasks match, ask which one. If status is unknown, say so. For status-only questions, report the task_status observation directly; do not search history, run shell probes, or repeat the investigation just to reconfirm it. Only inspect the result content when the user asks for that content.
- In a thread, continue the task directly; do not hand it off again. Other platforms and shared channels do not support start_task yet.
- In a thread, continue the task directly; do not hand it off again. Other platforms do not support start_task yet.

## Slack Rendering
- The Slack adapter renders responses natively from standard Markdown. Answer in normal Markdown/GFM.
Expand Down
2 changes: 1 addition & 1 deletion src/harness/tools/task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ export function createTaskTool() {
name: START_TASK_TOOL,
parameters,
description:
"Hand off multi-step or time-consuming work to an independent task thread so the user can keep chatting. Call ALONE, before doing that work. Ends this turn on success. Only available in top-level Slack DMs.",
"Hand off multi-step or time-consuming work to an independent task thread so the user can keep chatting. Call ALONE, before doing that work. Ends this turn on success. Only available for top-level Slack messages.",
execute: async (args, _api, { abortSignal: signal }) => {
signal?.throwIfAborted();
if (!start)
Expand Down
40 changes: 40 additions & 0 deletions src/test/slack-task.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,9 @@ async function startTask() {
.find((s) => s.sessionKey.startsWith("D123:"))!.sessionKey;
return key.slice(5);
}
async function mention(user: string, text: string, thread_ts?: string) {
await socket.deliver("app_mention", { text, channel: "C123", user, ts: eventTs(), thread_ts });
}
const handoff = () =>
fauxAssistantMessage(
fauxToolCall("start_task", { message: "On it, continuing here.", task: "LONG TASK CONTEXT" }),
Expand Down Expand Up @@ -255,6 +258,43 @@ test("DM handoff preserves acknowledgement, answers other chat, and steers activ
expect(vi.mocked(bot.postMessage).mock.calls.some((c) => c[2] === root)).toBe(true);
});

test("channel handoff keeps the channel answering and lets its requester steer the task thread", async () => {
faux.setResponses([
handoff(),
callHold(),
fauxAssistantMessage("quick answer"),
(context) => {
expect(JSON.stringify(context.messages)).toContain("CHANNEL_UPDATE");
return fauxAssistantMessage("task adjusted");
},
]);
await mention("U1", "investigate this");
await vi.waitFor(() => expect(trace).toContain("tool:start"));
const key = runtime
.getRunningSessions()
.find((s) => s.sessionKey.startsWith("C123:"))!.sessionKey;
const root = key.slice(5);
await mention("U2", "independent quick question");
await vi.waitFor(() =>
expect(vi.mocked(bot.updateMessage).mock.calls.some((c) => c[2].includes("quick answer"))).toBe(
true,
),
);
expect(trace).not.toContain("tool:end");
await mention("U2", "OTHER_PERSON_UPDATE", root);
await vi.waitFor(() =>
expect(trace.some((t) => t.includes("Only the task's current actor"))).toBe(true),
);
await mention("U1", "CHANNEL_UPDATE", root);
expect(faux.state.callCount).toBe(3);
hold.resolve();
await vi.waitFor(() => expect(runtime.getRunningSessions()).toHaveLength(0));
expect(faux.state.callCount).toBe(4);
expect(vi.mocked(bot.postMessage).mock.calls.some((c) => c[0] === "C123" && c[2] === root)).toBe(
true,
);
});

test("stop discards pending steering and history sync cannot resurrect it on continuation", async () => {
faux.setResponses([handoff(), callHold()]);
const root = await startTask();
Expand Down
Loading
0