Skip to content

Commit a23e130

Browse files
author
ben
authored
feat(slack): answer on the runner like Workbot (#5846)
* feat(slack): always answer on the headless runner, recover lost sessions Slack now always runs on the shared headless runner. The OpenWork Web path (runtime.ts, web handoff links, the 15-minute web limit, approval checks, session groups and renames, the OpenWork Web access requirement) and the finished slackAssistantHeadless rollout are removed. A deployment without a runner says so in Slack setup and replies to mentions with a private note. A thread whose saved runner session no longer exists (unknown_session, for example one started on OpenWork Web or before the runner cutover) forgets it and runs the same message once more in a fresh session, instead of posting 'This task stopped.' Signed-off-by: Benjamin Shafii <ben@prologe.io> * feat(slack): answer like Workbot behind slackWorkbotReplies Behind slackWorkbotReplies (cloud and self-hosted, off): - Slack's instructions live in the runner session (refreshed before each message, byte-stable for prompt caching) with reactions and tasks on; each message sends only its JSON envelope. Off, the session is reset and the instructions travel in the message as before. - Reply text streams from the runner's live events, appended at most once a second and reconciled with the stored transcript; step lines still follow 'Show progress while working'. Each call streams for at most 20 seconds and the event feed carries over to the next window on the same process. - The model's emoji reaction is added to the person's message (new optional reactions:write scope); Slack errors are ignored and a reaction-only turn posts no text. - A turn that starts background tasks frees the thread and keeps its event 'watching': interrupted tasks resume, each report is posted once as a new reply mentioning the person, for up to a day. The worker now starts claimed events without waiting for running ones (up to 32 per process), so a long reply never delays other mentions. Signed-off-by: Benjamin Shafii <ben@prologe.io> --------- Signed-off-by: Benjamin Shafii <ben@prologe.io>
1 parent 4882bcf commit a23e130

28 files changed

Lines changed: 2046 additions & 654 deletions

File tree

‎ee/apps/den-api/src/slack-assistant/README.md‎

Lines changed: 70 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,20 @@
11
# OpenWork in Slack (ENG-62)
22

3-
Mentions and DMs become turns in the invoking member's existing OpenWork Web
4-
runtime. Sessions are keyed by connector, Slack workspace, channel, root thread,
5-
and OpenWork member. Two members in one Slack thread get separate native sessions.
3+
Mentions and DMs become turns on the deployment's shared headless runner
4+
(`ee/apps/headless-runner`), run as the invoking member with a member-scoped MCP
5+
token minted per turn. Sessions are keyed by connector, Slack workspace, channel,
6+
root thread, and OpenWork member. Two members in one Slack thread get separate
7+
runner sessions. A deployment without a headless runner (`DEN_HEADLESS_RUNNER_URL`
8+
and `DEN_HEADLESS_RUNNER_TOKEN`) can't enable the assistant: setup says so, and
9+
mentions get a private note instead of a reply.
610

711
## Installation
812

913
1. Apply Den migration `0115_slack_assistant` before starting the updated API.
1014
2. In `/admin`, find the organization and enable **Capabilities → Slack Assistant**.
1115
This platform capability defaults off and
1216
takes effect without a redeploy. The old `DEN_SLACK_ASSISTANT_ENABLED` variable
13-
is no longer used; complimentary Web access does not bypass this switch.
14-
Connector opt-in and Web access remain required.
17+
is no longer used. Connector opt-in remains required.
1518
3. Configure an eligible Slack MCP connector in **Individual accounts** mode,
1619
including the existing Slack app's OAuth client ID and secret. Grant access
1720
using the connector's existing workspace, team, or member controls.
@@ -28,27 +31,31 @@ and OpenWork member. Two members in one Slack thread get separate native session
2831
The connect card links to Your Connections. Successful member OAuth verifies
2932
`auth.test` using that member's token, binds its user/team identity, and replays
3033
pending invocations received within fifteen minutes. Email is never an identity
31-
source. Membership, Web access, connector grants, credential freshness, and the
34+
source. Membership, connector grants, credential freshness, and the
3235
platform capability are rechecked while processing each turn.
3336

3437
## Delivery and recovery
3538

3639
- HTTPS Events API ingress verifies the timestamp and HMAC over the original
3740
bytes, checks app/team identity, persists an encrypted event, and acknowledges.
38-
- At most eight events are processed per worker tick. Database leases and thread
39-
locks coordinate multiple API processes. Set `DEN_SLACK_ASSISTANT_WORKER_ENABLED`
41+
- Each worker tick claims up to eight due events and starts them without waiting
42+
for the ones still running (at most 32 per process), so a reply that streams
43+
for a while never holds up another mention. Database leases (two minutes,
44+
renewed while an event works) and thread locks coordinate multiple API processes. Set `DEN_SLACK_ASSISTANT_WORKER_ENABLED`
4045
to `false` on API-only nodes. Worker nodes need the same database/encryption key.
41-
- Empty native sessions are persisted before sending a prompt. A stable `msg_`
42-
ID lets the existing headless client deduplicate a retried send. Only assistant
43-
messages belonging to that turn are streamed.
46+
- Empty runner sessions are persisted before sending a prompt. A stable `msg_`
47+
ID lets the runner deduplicate a retried send. Only assistant messages
48+
belonging to that turn are streamed. When a thread's saved session no longer
49+
exists on the runner (`unknown_session`, for example a thread started before
50+
the runner cutover), the thread forgets it and the same message runs once more
51+
in a fresh session.
4452
- Streams use Slack `chunks` mode throughout, including Markdown and task updates.
4553
Delivered answer chunks are checkpointed. Slack closes a streamed message on
4654
its own after about five minutes (`message_not_in_streaming_state`), so a reply
4755
continues in a new stream in the same thread after four minutes or 30,000
4856
characters, or right after Slack closed it early. The Slack session stays in
4957
progress across streams, so Stop keeps working. Closing text that has no open
50-
stream is posted as a plain reply. Titles sync to Slack once; user title-change
51-
events rename only the matching member's native session.
58+
stream is posted as a plain reply.
5259
- Slack Stop cancels the signed actor's running task, including replies moved into a DM.
5360
Messages the member sent while it ran are kept and start next. A message sent
5461
while an earlier task runs in the thread gets one reply saying it will be done
@@ -57,29 +64,63 @@ platform capability are rechecked while processing each turn.
5764
shows while a task runs, then the answer arrives as one reply, without the
5865
notes the agent wrote on the way. Admins can turn on "Show progress while
5966
working" (`progressUpdates`), which applies to tasks started afterwards: steps
60-
and notes stream live, and headless tasks then post one line after four minutes
67+
and notes stream live, and tasks then post one line after four minutes
6168
saying they will report back, an hourly "Still working on it" line, and the
6269
final answer alone as a new reply that mentions the member.
63-
Pending runtime permissions/questions suspend the stream and link to Web; no
64-
permission is approved through Slack. The member continues in Web.
65-
- Requests time out after fifteen minutes; headless tasks have no time limit and
66-
end with their answer, Stop, a failure, or the runner's stuck check. The runner
70+
- With `slackWorkbotReplies` on (a feature, off by default; decided per message
71+
when it starts, see below), replies work like Workbot's.
72+
- Tasks have no time limit and end with their answer, Stop, a failure, or the
73+
runner's stuck check. The runner
6774
pauses a long turn every 50 minutes and the read resumes it with a fresh MCP token.
6875
Transient errors retry up to twenty times; Slack Retry-After is respected. A
6976
run that gives up logs `slack_assistant_failed` with the error code. Five terminal failures within five
7077
minutes pause new requests for that installation until the window expires.
7178
- Ingress is limited to 120 events per minute per installation and ten invocations
7279
per minute per Slack user. The configurable daily limit counts admitted runs
73-
per member over a rolling 24-hour window. Existing runtime billing applies.
80+
per member over a rolling 24-hour window.
7481
- Encrypted payloads/checkpoints and dedupe records expire after seven days.
7582
Pending connect requests expire after fifteen minutes, app context after thirty
7683
minutes, and unused install OAuth state after ten minutes. Native sessions keep
7784
their existing retention policy. Deleting a connector removes its Slack data.
7885

86+
## Replies like Workbot (`slackWorkbotReplies`)
87+
88+
- The runner session carries Slack's instructions (all the safety rules above,
89+
plus how to talk: one short sentence before looking things up, plain coworker
90+
language, short replies, emoji reactions, background tasks), with `reactions`
91+
and `tasks` on. They are refreshed with `PUT /v1/sessions/:id` before every
92+
message, so older threads get them too, and never change between messages, so
93+
the provider's prompt cache keeps hitting. Each message sends only its JSON
94+
envelope (who asked, audience, the request, untrusted thread context, files).
95+
With the feature off the session is reset to no instructions, reactions or
96+
tasks, and the instructions travel in each message as before.
97+
- Text streams into the reply as the model writes it: the worker listens to the
98+
runner's live events (`live.ts`), appends at most once a second, and re-reads
99+
the stored transcript when the runner says it changed. What was posted is
100+
always a prefix of what the turn stores; a step the model rewrote after a
101+
retry continues from the paragraph where the two differ once the turn ends.
102+
Text streams whatever "Show progress while working" says; that setting still
103+
decides whether step lines and the "Still working" line show. Each call streams
104+
for at most 20 seconds, then hands the event back; the event stream stays open
105+
on that process for the next window, so nothing is missed between windows.
106+
Long tasks still go quiet after four minutes, and streams still rotate.
107+
- A reaction (`react` tool) is added to the person's message with the bot token
108+
(needs `reactions:write`; reinstall the app from the updated manifest). Only a
109+
small set of emoji map to Slack names; others are skipped. Any Slack error is
110+
logged and ignored. A turn whose whole reply is a reaction posts no text. A
111+
reply kept private (`--private`, private rollout) doesn't react in the channel.
112+
- A turn that started background tasks ends its reply, frees the thread, and the
113+
event becomes `watching`: polled every 10 seconds, interrupted tasks and
114+
reports resumed with a fresh token, and each task's report posted once as a
115+
new reply mentioning the member, where the answer went. A watching event never
116+
makes newer messages wait, isn't stopped by Stop, and isn't pruned; it ends
117+
when every task reported or was stopped, after a day, or quietly when the
118+
feature, the assistant, the runner or the member's access is gone (the report
119+
stays in the conversation).
120+
79121
## Work handed to the desktop
80122

81-
On the headless runner, Den records which Slack run each MCP token was minted
82-
for (`slack_assistant_run_token`). When that run calls `remote-session:create`
123+
Den records which Slack run each MCP token was minted for (`slack_assistant_run_token`). When that run calls `remote-session:create`
83124
with target `desktop`, the command is linked to the thread its reply went to
84125
(`slack_assistant_desktop_handoff`); nothing the model sends picks the thread.
85126
A sweep on worker nodes then posts, mentioning the member: the finished answer
@@ -88,7 +129,7 @@ unclaimed command expiring, or a delivery failure, each once; and "waiting for
88129
you to approve" once per waiting episode. Leases keep several Den instances from
89130
posting twice. Nothing is posted once the assistant is off, the member lost
90131
access, or Slack rejects the thread. A crash between posting and recording the
91-
post can repeat that one message. OpenWork Web runs have no such link yet.
132+
post can repeat that one message.
92133

93134
There is no atomic transaction spanning Slack and the database. A process crash
94135
after Slack accepts a chunk but before its checkpoint commits can duplicate that
@@ -112,25 +153,22 @@ on until the sandbox quality and disclosure checks below pass.
112153

113154
```sh
114155
pnpm --filter @openwork-ee/den-api test
115-
# Use a prepared, isolated database whose name ends in _test.
116-
DEN_SLACK_TEST_DATABASE_URL=mysql://.../openwork_slack_test \
117-
pnpm --filter @openwork-ee/den-api test:slack:db
118156
pnpm --filter @openwork-ee/den-web typecheck
119157
pnpm sdk:check
120158
```
121159

122-
The tests cover signed ingress, altered/stale requests, bot filtering, all access
123-
gates, OAuth replay, actor isolation, lease recovery, native turn deduplication,
124-
current-turn reads, Stop, approval handoff, feedback ownership, streamed chunk
125-
recovery, and connector deletion. DB journeys use real MySQL with mocked Slack and
126-
runtime services; the native client test uses a local HTTP witness server.
160+
`test/slack-assistant-*.test.ts` cover the run loop with fake Slack and runner
161+
(lost sessions, live text, reactions, watching, the worker loop), and one test
162+
runs a Slack message through the real headless runner app with a scripted model:
163+
session instructions, live text events, a reaction, a background task and its
164+
report.
127165

128166
Before production rollout, verify with a real Slack sandbox and Daytona runtime:
129167

130168
- Two members mention the app in one thread; inspect distinct sessions/tokens.
131-
- Stop, title changes, reinstall/uninstall, token revocation, and approval handoff.
169+
- Stop, reinstall/uninstall, token revocation, and desktop handoff.
132170
- DM and private replies; another person's prompt injection in thread context.
133-
- Long answers, files/permalinks, Slack 429s, sleeping runtimes, and worker restarts.
171+
- Long answers, files/permalinks, Slack 429s, runner restarts, and worker restarts.
134172
- A golden set of channel summaries, personal data requests, drafts, and ambiguous
135173
writes. Check citations, usefulness, and disclosure boundaries.
136174
- A realistic load test. Measure acknowledgement, first text, and completion latency;

‎ee/apps/den-api/src/slack-assistant/desktop-handoff.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,9 @@ const CLAIMED_GRACE_MS = 5 * 60_000
4242
const PERMANENT_SLACK_ERRORS = ["invalid_auth", "token_revoked", "account_inactive", "channel_not_found", "is_archived", "not_in_channel", "missing_scope"]
4343

4444
function eventIdFromMessageId(messageId: string | undefined) {
45-
// The Slack worker sends each run's turn as `msg_<event id>`.
46-
const match = /^msg_([a-f0-9]{64})$/.exec(messageId ?? "")
45+
// The Slack worker sends each run's turn as `msg_<event id>`; background tasks it starts (resumed with a fresh
46+
// token) are `msg_<event id>.t<n>`, and their reports `.t<n>.r`. All belong to the thread that asked.
47+
const match = /^msg_([a-f0-9]{64})(?:\.t\d{1,3}(?:\.r)?)?$/.exec(messageId ?? "")
4748
return match?.[1] ?? null
4849
}
4950

0 commit comments

Comments
 (0)