Skip to content

feat(slack): add a Reconnect action so saved credentials apply without a restart - #25780

Closed
CrysisDeu wants to merge 2 commits into
mainfrom
fix/slack-reconnect-10306
Closed

CrysisDeu wants to merge 2 commits into
mainfrom
fix/slack-reconnect-10306

Conversation

@CrysisDeu

@CrysisDeu CrysisDeu commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: Slack credentials saved from Settings take effect with one click, without restarting the gateway.

Slack's tokens and owner ID are read once, when the gateway orchestrator is built. Saving new ones from Settings → Slack (PUT /api/slack/config) writes them to the credential store, but the running Socket Mode client keeps the old ones, and the panel's only advice is "restart the gateway". POST /api/restart execvs the whole process, so every in-flight agent run, task-runner step and cron is torn down to redo one websocket handshake.

Why it matters

First-run Slack setup is where a token typo or a missing owner ID happens. The issue's reporter ran for hours with no Socket Mode client because the owner ID was missing at boot; re-entering it in Settings reported success and changed nothing. With Reconnect, the fix is one click and the outcome shows on the same screen.

Not a goal

  • Changing POST /api/restart, or the slash command's restart requirement (it is registered in the Slack app manifest).
  • Applying credentials automatically on save. Reconnect is an explicit click, so a half-typed token is never applied by accident.
  • Switching Slack workspaces in place. A saved bot token for a different workspace is refused with "restart the gateway to switch workspaces" (see What changed).
  • Registry channels (Discord, Telegram, ...). They already restart in place through restart_channel.

Intended? / Repro

Intended? No. Nothing documents a restart as the required way to apply a Slack credential. Every registry channel already restarts in place on a config change (src/kiro_crew/slack/gateway_runtime/channel_lifecycle.py restart_channel); Slack is the one channel left out. The _connect_slack docstring (channel_lifecycle.py:251) records "no background retry of the initial connect" as a known gap, not a design decision.

Repro (read on current main, a29bae7df7):

  • src/kiro_crew/slack/gateway_runtime/orchestrator_init.py:86 and :103 assign _owner_id and _slack_enabled once, in the constructor. Nothing reassigns them later.
  • src/kiro_crew/slack/events.py:183 returns early when _slack_enabled is false, and :188 / :217 set it false on a missing owner or a refused workspace. So once boot failed, no in-process retry could ever connect.
  • src/kiro_crew/dashboard/routes/messaging.py:23-25 registers only GET/PUT /api/slack/config and GET /api/slack/manifest. There is no reconnect route.
  • src/kiro_crew/dashboard/messaging_api/slack_settings.py:350 returns restart_required for every credential write (channel_folders.py:98), and website/src/pages/settings/SlackPanel.tsx:83 tells the user to restart the gateway.
  • What the user sees: boot with KIROCREW_OWNER_ID unset logs KIROCREW_OWNER_ID is not set — Slack disabled for security. Saving the owner ID in Settings answers "Saved. Restart the gateway to apply.", and Slack stays down until a restart (before frames below).

What changed (motivation → approach → change)

Symptom: a saved Slack credential needs a full gateway restart. Cause: the credentials are hoisted once, and the socket init returns early on a sticky flag. Change: one route that redoes the Slack part of a restart, in place.

Backend

  • src/kiro_crew/slack/reconnect.py (new), reconnect_slack(orch):
    1. Reads the credential store off the loop, under the dashboard config lock the Slack save holds across its .env write. A store that cannot be read raises CredentialStoreUnreadable, and the running connection is left alone.
    2. Closes the current socket client (bounded at 2 s, best effort) and unpublishes its Web API client from the dashboard. The saved credentials are what must be live, so a connection built from the previous ones (a previous owner, say) does not stay up behind a failure.
    3. Hoists the tokens and owner, including the handler owner allowlist and DashboardState.owner_id (owner notices DM this owner). It then recomputes _slack_enabled from the tokens and re-awaits init_socket_mode + _connect_slack on the gateway loop. The socket client must be built on a thread with a running loop. The boot SeenCache is reused, so redelivered envelopes are still dropped.
    4. Publishes the Web API client to the dashboard only behind a connected socket, records slack_socket_connected / slack_connect_error where GET /api/slack/config reads them, and runs the same tracked-channel probe boot runs after connecting.
    • The declines have names the panel explains: tokens_missing, owner_id_missing, enterprise_validation_failed, denied_by_policy, workspace_switch_needs_restart. Slack API codes such as invalid_auth pass through. An unexpected exception leaves Slack down with its class name. It never leaves a half-built socket.
    • Concurrent callers share one attempt (asyncio.shield), so a double click never races two handshakes, and a caller that goes away does not cancel the attempt.
    • No in-place workspace switch. Queued turns, in-flight replies and persisted thread links name the current workspace's channels. A restart drops the in-process part of that; a reconnect would not. So the gateway records the auth.test team of the Web API client it published (boot: pin_boot_workspace → record_connected_workspace, fire-and-forget). Boot counts as having published a client when either orch.slack or the dashboard's slack_client copy is set, since init_socket_mode can clear orch.slack alone while dashboard senders keep the copy; a boot that published neither, such as a leftover bot token without its app token, pins nothing. If a later reconnect's bot token belongs to another team, or that team could not be confirmed, Slack stays off with workspace_switch_needs_restart. A gateway that never connected adopts whatever workspace the saved token names. While a reconnect runs with no client published, the three Slack queue drains (_on_done, _on_transport_done, _drain_slack_queue) and _route_message keep their entries queued instead of dispatching them into the cleared client (events_queue.hold_if_slack_down), and a connected reconnect starts the held keys again (resume_held_slack_drains). A reconnect that retires a published client and fails keeps that hold (_slack_client_lost) for the next reconnect, the retry, for HELD_WORK_GIVE_UP_SECS (300 s). If that window ends with no client, the hold gives up (events_queue.give_up_held_slack_work): each held message leaves its queue, its deferred temp files are unlinked, and the owner gets one dashboard notification (dashboard_state.notify, "Slack: message not delivered") that names the channel in words (a tracked channel's saved name, "a direct message", else "a Slack channel") and quotes the first 80 characters of the message, or says it was a voice memo or an attachment. Raw Slack ids, timestamps and user ids stay out of the body (they are in the notice's meta). Then the hold is released. A gateway no reconnect took a client from (no reconnect, or one on a gateway that never published a client) handles a missing client exactly as on main; test/test_events_forward.py is unchanged. A drain that does dispatch passes _dispatch_queued the client it read in the same step as the dequeue (slack= keyword), so a reconnect that clears orch.slack during the reaction removal cannot hand the turn a None client. The closed predecessor ran into a design conflict on exactly this subsystem (a workspace-switch sweep vs. thread-eviction safety); refusing the switch avoids that conflict and needs no new state file.
  • POST /api/slack/reconnect (dashboard/messaging_api/slack_settings.py api_slack_reconnect, registered beside the PUT in dashboard/routes/messaging.py). It sits behind the same dashboard token auth + CSRF as the PUT and is direct-local only (is_direct_local_request, remote → 403 remote_read_only). 503 slack_reconnect_unavailable when no gateway owns the socket (API-only server); 500 credential_store_unreadable. Answers {connected, connect_error}, the pair the GET already reports. SEL access log slack.reconnect.
  • PUT /api/slack/config now returns reconnect_required for a token/owner write and keeps restart_required for command only.
  • Wiring: service_boot.py keeps the boot SeenCache on the orchestrator and sets DashboardState.slack_reconnect after dashboard init. orchestrator_init.py / gateway.py initialize and declare the four reconnect fields. handlers/messaging.py and handlers/__init__.py export the route.

Frontend (website/src/pages/settings/SlackPanel.tsx, api/client/messaging.ts)

  • A Reconnect button (lucide RefreshCw) in the panel header beside the status pill, hidden on read-only remote sessions like Save. Pending: "Reconnecting…", disabled. Success: "Connected to Slack." and the pill flips (the GET is refetched). Decline: "Reconnect failed: ", where the reason comes from one describeConnectError mapper shared with the recorded boot failure, so the same failure reads the same way either way. A gateway refusal shows its own reason. A request that never reached a gateway is "Reconnect failed. Is the gateway running?".
  • One notice at a time: while a click is in flight or has answered, the recorded reading steps aside.
  • After a credential save the confirmation reads "Saved. Click Reconnect to apply." with a Reconnect button beside it, since the header may be scrolled off above the long form. It stays until a reconnect succeeds, including across a later config-only save. A save that also changed the slash command adds "The slash command applies after a gateway restart." The save row now wraps instead of overflowing.
  • i18n: 18 new slackPanel keys in en.manual.json, the 11 translated catalogs and the regenerated en-XA, plus two en.context.json entries. Four restart-only keys that nothing reads any more are removed from every catalog.

Docs: docs/system-specs/modules/messaging.md (Slack settings API) and docs/feature-map/README.md.

Supersedes #14574, which was 3292 commits behind main after the messaging handlers moved into messaging_api/*. This is a smaller redo for the current layout. It drops the predecessor's workspace-switch machinery (state file, link sweep, generation fence, client affinity), which its own review left as an open design question.

Security

The new route changes which credentials the gateway's Slack connection uses, so it takes the PUT's exact guards: dashboard token auth, the CSRF middleware, and the direct-local check (loopback peer, no forwarding headers). It is registered in the dashboard route block, not the token-less API-only route set. The dashboard listener is unchanged (loopback bind). The reconnect never widens access: a declined attempt clears the previous owner from the handler allowlist and from DashboardState, and no Web API client is published without a connected, gate-admitted socket. The response carries only a short reason code, never a token.

Backwards compatibility

  • Additive: one new POST route, one new response field (reconnect_required) on the PUT. An existing client that reads only restart_required sees false for a pure credential save; the restart it would have offered is no longer needed.
  • POST /api/restart is untouched and still works.
  • No config, schema or storage change; no new file on disk.
  • Removes nothing a user relies on: the four removed catalog keys were the restart-wording strings this change replaces.

Tests

Backend, test/test_slack_reconnect.py (new, 49 tests):

  • recomputes _slack_enabled and hoists the new tokens/owner (also handler owner + DashboardState.owner_id); red on main, which has no reconnect_slack
  • closes the old socket first; nothing published while the new one is built; client published only when connected
  • awaits init_socket_mode on the running loop with the boot SeenCache
  • unreadable store raises and leaves the old socket, client and handshake untouched
  • tokens_missing, owner_id_missing (previous owner cleared), Slack invalid_auth passthrough, enterprise_validation_failed, denied_by_policy, failed handshake (socket retired), close that raises, unexpected exception
  • workspace switch refused, unconfirmed workspace refused, a never-connected gateway adopts the saved workspace
  • tracked-channel probe runs with the new client; three concurrent callers share one handshake; a cancelled caller does not cancel the attempt
  • record_connected_workspace reads the socket's client, and leaves the team unknown on failure
  • a boot that published no client pins nothing and a reconnect adopts the configured workspace; a boot that published one pins it
  • a drain while Slack is down keeps the entry queued and dispatches it with the new client on resume; a connected reconnect resumes held drains, a failed one keeps them held
  • a client published only to the dashboard still pins the boot workspace; a dispatch keeps the client its drain read when orch.slack is cleared mid-dispatch
  • a message queued across a failed reconnect (tokens_missing) is held by the turn-end drain and delivered once, with the new client, when the retry connects
  • a reconnect that never recovers: after the give-up window each held message (session queue and pre-session stash) gets one "Slack: message not delivered" notice, the queues are empty and the hold is released
  • the undelivered notice wording: tracked channel name / "a direct message" / "a Slack channel", the message's first 80 characters with Slack markup rendered, "a voice memo", "an attachment", and no raw Slack id or timestamp in the body
  • a failed reconnect on a gateway that never published a client holds nothing
  • route: answers the GET shape, 403 remote, 503 no socket owner, 500 unreadable store, registered as POST

test/test_slack_config_handlers.py: a credential save flags reconnect_required, not restart_required; a command change still flags restart_required. test/test_handlers_messaging_composition_contract.py: package re-export count 59 → 60. test/test_slack_events_coverage_route_flow.py and test/test_stop_clears_only_its_own_sender_slack.py: their _dispatch_queued fakes accept the new slack= keyword.

Frontend, website/src/test/SettingsSlackPanelCoverage.test.tsx: existing wording assertions updated, and a new Reconnect block covering success, pending (disabled, recorded failure off screen), a decline worded like the recorded failure as the only notice, each named decline, the gateway's 503/500 refusals, a network error and an unstructured 5xx, the save-row button surviving a config-only save and a failed reconnect and retiring on success, the slash-command restart line, and the button hidden on read-only. ApiClient.refactor.surface.test.ts lists reconnectSlack.

Known unrelated: website/src/test/kiroUsageRefetchInterval.test.ts:92 fails on main too. It expects 'api-key' for reason 'api_key_auth', and website/src/api/kiroUsage.ts has no branch for it (from #22387 and #25434). This backend-only change does not touch either file.

Proof: not provable -- other: this host runs no local tests; CI runs them

Manual verification

Static gates run locally on the changed files: black 26.10.1, isort, flake8, mypy 1.14.1; tsc -p tsconfig.app.json, eslint, I18N_BASE_REF=origin/main node scripts/i18n-check.mjs, gen-ui-index --check, the theme/phantom-class/restyle lints; scripts/check_comment_history.py, check_feature_map.py, check_file_line_cap.py, check_sync_io_in_async.py, check_loop_bound_locks.py. Tests run in CI.

Screenshots come from an isolated capture page (real SlackPanel and stylesheet, api Slack seams stubbed, vite on 127.0.0.1). Before frames use the same page on a detached main worktree. Not committed.

Screenshots / video

Before (main): the recorded failure says to restart the gateway, and there is no Reconnect.

Before: invalid_auth recorded, notice says restart the gateway, no Reconnect button

Before (main): a credential save answers "Saved. Restart the gateway to apply."

Before: credential save answers Saved. Restart the gateway to apply.

After: the recorded failure points at the header Reconnect button.

After: invalid_auth recorded, Reconnect button beside the status pill, notice says click Reconnect

After, light theme: same state

After: pending, the button reads Reconnecting… and is disabled, and the recorded failure steps aside.

After: Reconnecting… disabled, no stacked notice

After: the click's decline, labelled as its outcome.

After: Reconnect failed: Slack rejected the stored tokens (invalid_auth)…

After: connected, the pill flips and "Connected to Slack." shows.

After: Connected pill and Connected to Slack.

After: a credential save points at Reconnect, with the button beside the confirmation.

After: Saved. Click Reconnect to apply. with a Reconnect button in the save row

Related Issues

Fixes #10306

Supersedes #14574

Sibling sweep

Swept: git grep -n "_slack_enabled = |restart_required|init_socket_mode" -- src/kiro_crew/slack src/kiro_crew/dashboard/messaging_api
Sibling: src/kiro_crew/slack/gateway_runtime/channel_lifecycle.py restart_channel -- not affected (registry channels already restart in place)
Sibling: src/kiro_crew/dashboard/messaging_api/discord_settings.py and the other channel savers -- not affected (their credential writes restart the channel through the config applier)
Sibling: src/kiro_crew/slack/gateway_runtime/service_boot.py -- changed here (boot keeps the SeenCache and records the connected workspace)

Pattern harvest

Rule candidate: review-prompt
Pattern: a "retry" entry point that re-calls an init routine guarded by a sticky enabled/failed flag must recompute the flag from current inputs first, or the retry is a silent no-op.

Checklist

  • At most two commits (one is the norm), with a Conventional Commits title (feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

Contribution License Agreement

Contributed under the project's Apache-2.0 license.

@CrysisDeu
CrysisDeu requested review from a team and KiroCrewCaptain as code owners October 29, 2026 13:25
@CrysisDeu
CrysisDeu requested a review from buluoray October 29, 2026 13:25
@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Oct 29, 2026
@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5) — ✅ PASS

Premise-level review of dc9ded5103799f1b3ee95639fcd082c195b4d490 — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS does not.

First-Principles-Verdict: PASS

Nothing blocks: Reconnect is added beside restart, and no default changes. The 300 s held-work give-up and its notices go further than the Goal, which is only to apply saved credentials.

Notes

  • Item 6 — oversized: "the hold gives up (events_queue.give_up_held_slack_work)… the owner gets one dashboard notification". The only in-place sibling, restart_channel (channel_lifecycle.py:418), has 0 hold, give-up or notice mechanisms (grepped _pending_queue|hold|give_up). A restart, today's path, drops queued work silently. Subtraction: delete HELD_WORK_GIVE_UP_SECS, _give_up_after, _schedule_give_up, _cancel_give_up, _slack_client_lost, client_lost_to_reconnect, give_up_held_slack_work, and the failed-reconnect paths of notify_slack_undelivered and the _deliver_result heartbeat. Keep only the in-window hold (_slack_reconnecting). Clears when: the mechanism is removed, or a human amends the Goal.

What this change ships

Inventory (10 items) — 9 justified

Intent: let an owner apply newly saved Slack credentials with one click instead of restarting the gateway. This is an ADDITION.

  1. Reconnect button in the Slack panel header, and beside Save after a credential save — justified
  2. POST /api/slack/reconnect, direct-local only — justified
  3. Saving tokens or the owner ID now says "click Reconnect"; restart_required is set only for command — justified
  4. A reconnect to a different workspace is refused (workspace_switch_needs_restart) — justified
  5. Queue drains and inbound routing hold their work while a reconnect is running — justified
  6. After a failed reconnect, held work waits 300 s, then the owner gets "message not delivered" notices — oversized
  7. Attachments and background results wait for an in-progress reconnect — justified
  8. init_socket_mode(declared_yolo=False) keeps !yolo off across a reconnect — justified
  9. The agent-session driver and the tracked-channel probe re-run on the new client — justified
  10. SettingsPage bundle budget raised to 527 KB — justified

[FIRST-PRINCIPLES-REVIEWED] dc9ded5

Description read

[DESCRIPTION-READ] 9162f90bafc2d02e7e4506fed06884b491e5cf10fe699b03bd39573403686651

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5) — ✅ PASS

Design-level review of dc9ded5103799f1b3ee95639fcd082c195b4d490 — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS does not.

Design-Verdict: PASS

No design-level blocker. The route fixes the stated cause in place: credentials are read once at boot and a flag stays false after a failed connect. It stays out of /api/restart and refuses to switch workspaces.

Notes

  • The description and the new connect_error_workspace_switch_needs_restart string both say Slack stays off when the pinned team "could not be confirmed". The code does the opposite. _switches_workspace returns False when _slack_team_id is empty, so a different token goes through whenever the re-probe of the boot token also fails. Make the text match the code, or make the code refuse.
  • The give-up machinery (_slack_client_lost, hold_if_slack_down, give_up_held_slack_work, the 300 s timer) puts reconnect state into the queue, egress, voice and file paths. Refusing a reconnect while _slack_work_admitted(orch) is true would remove most of it. Say in the PR why that simpler option was rejected.

[DESIGN-REVIEWED] dc9ded5

Description read

[DESCRIPTION-READ] b9733635fabd014e456576e8394b6cb6ffa1ef09514983dcf10b564ab227a621

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5) — ✅ PASS (a BLOCK with no Trigger and no Outcome does not block)

UX-level review of dc9ded5103799f1b3ee95639fcd082c195b4d490 — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS does not.

UX-Verdict: PASS

cannot evaluate: missing the "Slack: message not delivered" dashboard notification and the "slash command applies after a gateway restart" save-row line. No supplied screenshot shows either one.

Evidence gaps

  • The "Slack: message not delivered" notification. It is posted by notify_slack_undelivered when a held message is dropped, and its body reads "Slack did not reconnect, so … was not delivered to the agent. Reconnect Slack in Settings, then send it again." None of shot-01…08 shows it. To close this, attach a screenshot of the notification as it renders in the dashboard's notification surface, with a channel name and a quoted message filled in.
  • The slash_command_needs_restart line. It reads "The slash command applies after a gateway restart." and appears beside "Saved. Click Reconnect to apply." when a save needs both a reconnect and a restart. shot-08 shows only the version that needs just a reconnect. To close this, attach a screenshot of the save row after a save that changes both the credentials and the slash command.

Notes

  • Reconnect while connected (shot-07). The blind reader said "probably no, because it's already working and I wouldn't want to break it." Either hide or demote the header Reconnect while connected is true and no reconnect is pending, or give it a tooltip saying it reapplies the saved credentials.
  • Badge during a reconnect (shot-05). The badge still says "Not connected" next to "Reconnecting…", and the reader was unsure whether the error box had been cleared or just hidden. Show a "Connecting…" state on StatusBadge while reconnectMut.isPending is true.

[UX-REVIEWED] dc9ded5

Description read

[DESCRIPTION-READ] 90748dcc276afb163cd26aba68030c865e3b234146ffd46ac8183d17c6c1bf46

That sha256 names everything this verdict read: the PR description, plus the 11 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review — ✅ no blocking findings

Reviewed dc9ded5103799f1b3ee95639fcd082c195b4d490 — this comment is updated in place on each push.

Review details

No findings.

Notes:

  • The new SettingsPage budget comment in website/scripts/check-bundle-size.mjs:334 says the chunk measured 526.07 kB and also "about 1.2 KB under the 500 KB default". Those two numbers can't both be true, so the measured baseline should be corrected.

[OPUS-REVIEWED] dc9ded5

Verdict parsed from the review's SHA-scoped output markers for commit dc9ded5103799f1b3ee95639fcd082c195b4d490.

False positive or not applicable? A repository writer can comment:
/ai-review override fable dc9ded5103799f1b3ee95639fcd082c195b4d490 false-positive: <reason, 20 to 500 characters>

@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review — 🔴 changes requested (blocking)

GPT 6.1 found at least one blocking issue that must be resolved before merging dc9ded5103799f1b3ee95639fcd082c195b4d490. 2 of 2 blocking finding(s) are security-class and were withheld from adjudication, so the blocking verdict stands.

This comment is updated in place on each push.

BLOCKING -- src/kiro_crew/slack/reconnect.py:428 -- An unconfirmed workspace pin permits switching with queued work

orch._slack_workspace_pinned and orch._slack_team_id and team_id != orch._slack_team_id
Trigger: Workspace A has queued messages, its boot workspace probe failed, and its token is subsequently revoked. Reconnect with workspace B’s credentials reaches _check_workspace; probing A fails again, so both workspace checks admit B and _bring_up resumes queued work.
Outcome: A’s entries are dequeued using B’s client with A’s channel/thread IDs. Replies fail with channel_not_found; the entries are neither restored nor passed through the undelivered-message notification path.
Anchor: residual/crash-data-loss-corruption
Fix: Refuse a changed bot token before teardown when the pinned workspace remains unconfirmed; preserve recovery with the same token.
Sites: src/kiro_crew/slack/reconnect.py:459, src/kiro_crew/slack/reconnect.py:492

BLOCKING -- website/src/pages/settings/SlackPanel.tsx:349 -- A refused workspace switch is displayed as successful

if (res.connected) {
setReconnectOutcome({ connected: true })
Trigger: With workspace A connected, save workspace B’s credentials and click Reconnect. _check_workspace preserves A’s connection and returns {connected: true, connect_error: "workspace_switch_needs_restart"} through api_slack_reconnect to this callback.
Outcome: The panel displays success, clears the pending-credentials reminder, and suppresses the refusal and required restart. B’s saved credentials remain unapplied while A stays active.
Anchor: errors-use-error-notice
Fix: Require an empty connect_error before treating the attempt as successful; otherwise render the refusal through ErrorNotice and retain the reminder.
Sites: src/kiro_crew/dashboard/messaging_api/slack_settings.py:459 also records the refused attempt as successful solely from connected.

[BLOCK-MERGE] dc9ded5
[GPT-REVIEWED] dc9ded5

Adjudication (Opus 5.5) — is blocking on each finding proportionate?

F1 (src/kiro_crew/slack/reconnect.py:428). The failure needs four things to happen together:

  • the boot probe failed and left workspace A pinned but unnamed (reconnect.py:256-262; the pin is released only on invalid_auth when no work was admitted);
  • A's token was then revoked;
  • the operator saved workspace B's credentials and clicked Reconnect;
  • the second probe of A also failed (reconnect.py:455-458).

Only then does _switches_workspace (:428) let B through at :459 and :492. In that state A's token is already revoked, so A's queued replies could not have been delivered through A anyway. Slack channel IDs are globally unique, so sending them through B's client fails with channel_not_found and nothing leaks to the other workspace. I did not trace the recovery path for the dequeued entries, so I have no evidence that they are restored.

F2 (website/src/pages/settings/SlackPanel.tsx:349). Nothing rare is needed: the operator saves B's credentials while A is connected and clicks Reconnect. _check_workspace returns {connected: true, connect_error: WORKSPACE_SWITCH_NEEDS_RESTART} (reconnect.py:469-470). slack_settings.py:459-470 passes both fields through and logs the attempt as ok. The panel looks only at res.connected (SlackPanel.tsx:349-351), so it shows success and clears the reminder. Switching workspaces is an ordinary operator action, so there is no rarity argument for a FLAG.

[ADJUDICATION] dc9ded5103799f1b3ee95639fcd082c195b4d490 total=0 uphold=0 downgrade=0
[GPT-ADJUDICATED] dc9ded5103799f1b3ee95639fcd082c195b4d490

[ADJUDICATION-FENCED] dc9ded5103799f1b3ee95639fcd082c195b4d490 fenced=2 flagged=1
FLAG F1 src/kiro_crew/slack/reconnect.py:428 -- Reaching this needs a boot probe failure that kept the pin (reconnect.py:256-262), then A's token being revoked, then a deliberate switch to B with work still queued, then a second failed probe of A (:455-458); the replies lost were already undeliverable because A's token is revoked, and globally unique channel IDs mean nothing crosses into B's workspace.
UPHOLD-FENCED F2 website/src/pages/settings/SlackPanel.tsx:349 -- A routine workspace switch triggers it: _check_workspace returns connected=true with WORKSPACE_SWITCH_NEEDS_RESTART (reconnect.py:469-470), slack_settings.py:459-470 records it as ok, and the panel reports success at :349-351.
[GPT-ADJUDICATED-FENCED] dc9ded5103799f1b3ee95639fcd082c195b4d490

🏷️ Fenced finding(s) machine-flagged as likely edge case

The security fence keeps these findings blocking regardless of adjudication; the only clearance path is a human override. The annotate-only pass judged the condition combination each one requires extreme, and pre-drafted the override rationale below. A repository writer must independently verify a rationale before posting it — it is machine-authored, and a wrong override on a security-class finding ships exactly the class the fence exists to stop.

  • F1 src/kiro_crew/slack/reconnect.py:428 — Reaching this needs a boot probe failure that kept the pin (reconnect.py:256-262), then A's token being revoked, then a deliberate switch to B with work still queued, then a second failed probe of A (:455-458); the replies lost were already undeliverable because A's token is revoked, and globally unique channel IDs mean nothing crosses into B's workspace.

    /ai-review override gpt dc9ded5103799f1b3ee95639fcd082c195b4d490 <class>: Reaching this needs a boot probe failure that kept the pin (reconnect.py:256-262), then A's token being revoked, then a deliberate switch to B with work still queued, then a second failed probe of A (:455-458); the replies lost were already undeliverable because A's token is revoked, and globally unique channel IDs mean nothing crosses into B's workspace.
    

Replace <class> with the class that records what you did. These findings are real, so for an accepted risk use owner-decision (link the decision comment in the reason) or deferred #<N> (a tracked follow-up issue); false-positive only if you verified the finding is wrong. Not not-applicable: that class files the override as a rule mismatch in the audit.

False positive or not applicable? A repository writer can comment:
/ai-review override gpt dc9ded5103799f1b3ee95639fcd082c195b4d490 false-positive: <reason, 20 to 500 characters>

@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Oct 29, 2026
@CrysisDeu
CrysisDeu force-pushed the fix/slack-reconnect-10306 branch from c78441a to e6a6dda Compare October 29, 2026 14:17
@CrysisDeu

Copy link
Copy Markdown
Contributor Author

Review round on c78441a7c addressed in e6a6ddaf16ba0d82da69b57587aafb557fa6717e (rebased onto current main):

  • Opus BLOCKING / GPT F2, boot race (service_boot.py): fixed. DashboardState.slack_reconnect is now published after boot's own init_socket_mode + _connect_slack have returned, not in _init_dashboard. Until then the route answers 503 slack_reconnect_unavailable, so a reconnect cannot open a socket that boot then replaces without closing. The API-only server still leaves it unset.
  • GPT F1, YOLO re-grant (reconnect.py): fixed. init_socket_mode takes declared_yolo (default True); the reconnect passes False, so the start-up declared grant is not re-applied and an owner's !yolo off stays off. The dashboard start-up path (safety_grants.py) still grants the declared YOLO once, and reconnect is only wired in dashboard mode. Test: test_reconnect_skips_the_start_up_yolo_grant.
  • GPT F3, vault failure reads as tokens_missing: fixed. When a Slack credential is missing after load_credentials, _read_credentials reads the raw .env line. A secret:// reference that did not resolve, or an .env that could not be read, raises CredentialStoreUnreadable before the socket is closed. Tests: test_an_unresolved_vault_reference_leaves_the_connection_alone, test_unresolved_reference_reads_the_raw_env_line.
  • GPT F4, stale reconnect clears a newer save's reminder (SlackPanel.tsx): fixed. Credential saves are counted. A successful reconnect clears the reminder only when no credential save landed after it started. Test: keeps the reminder for a credential save that lands while an earlier reconnect runs.

Gates: the comment-history markers are reworded, the Semgrep logger message no longer says "token", and the two fixed sleeps in the tests are now until_parked barriers.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 29, 2026
@CrysisDeu
CrysisDeu force-pushed the fix/slack-reconnect-10306 branch from e6a6dda to 1b41bae Compare October 29, 2026 15:05
@CrysisDeu

Copy link
Copy Markdown
Contributor Author

GPT 6.1 Review on e6a6ddaf1, plus the Backend Lint (mypy) red, addressed in 1b41bae3ca4b0d8829a06daab4ab84840748fb51:

  • F1, client published before workspace admission (reconnect.py): fixed. _bring_up builds the RealSlackClient but leaves orch.slack at None (it was cleared by the close) until init_socket_mode's enterprise gate and _connect_slack's channels-policy check have both admitted the socket. No sender can reach an unchecked workspace while auth.test is in flight. The test now asserts that orch.slack is None inside both init_socket_mode and _connect_slack.
  • F2, environment-supplied secret:// references: fixed. _unresolved_reference reads each missing key with the loader's precedence: a non-empty os.environ value first, then the .env line. Test: test_unresolved_reference_reads_the_environment_first.
  • mypy to_thread arg-type: the bool result is now bound to an annotated variable.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 29, 2026
@CrysisDeu
CrysisDeu force-pushed the fix/slack-reconnect-10306 branch from 1b41bae to 987e540 Compare October 29, 2026 16:15
@CrysisDeu

Copy link
Copy Markdown
Contributor Author

GPT 6.1 Review on 1b41bae3c, plus the facade-mirror guard red (Backend Tests 3.12 shard 2 and Windows shard 2), addressed in 987e540ed6a50ceea29ee2c806d8901f85766075:

  • F1, failed boot socket skips the workspace guard (reconnect.py): fixed. Boot publishes the bot token's Web API client whether or not the socket connects, so the workspace is now pinned at boot whenever a bot token is present, not only after a connected handshake (the flag is renamed _slack_workspace_pinned). record_connected_workspace names the workspace with auth.test on the bot token itself, not on the socket's client. If Slack rejects the token as invalid_auth or similar, the pin is released, because a client built from that token cannot have bound any work. Any other probe failure leaves the workspace unconfirmed, and a reconnect then asks for a restart. Tests: test_a_failed_boot_socket_still_pins_the_published_workspace, test_a_bot_token_slack_rejects_at_boot_releases_the_pin.
  • test_facade_mirror_guards: the new .env tests now patch env_path through the kiro_crew.config.loader facade.

@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 29, 2026
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: checking Automated validation is still running labels Oct 30, 2026
@CrysisDeu
CrysisDeu force-pushed the fix/slack-reconnect-10306 branch from 3224902 to 4926e11 Compare October 30, 2026 03:36
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention merge conflict Branch has merge conflicts with its base — author must resolve before merge and removed readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Oct 30, 2026
@CrysisDeu
CrysisDeu force-pushed the fix/slack-reconnect-10306 branch from 4926e11 to bdccd57 Compare October 30, 2026 19:56
@github-actions github-actions Bot added readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention and removed readiness: action required A blocking check or review needs attention merge conflict Branch has merge conflicts with its base — author must resolve before merge readiness: checking Automated validation is still running labels Oct 30, 2026
@CrysisDeu
CrysisDeu force-pushed the fix/slack-reconnect-10306 branch from bdccd57 to c9ac806 Compare October 30, 2026 21:23
@github-actions github-actions Bot added readiness: checking Automated validation is still running and removed readiness: action required A blocking check or review needs attention labels Oct 30, 2026
…t a restart

POST /api/slack/reconnect re-reads the saved Slack credentials and re-runs the Socket Mode handshake on the gateway loop, recomputing _slack_enabled first. Settings > Slack gets a Reconnect button, and a credential save points at it instead of a gateway restart. A reconnect never switches workspaces in place.
@CrysisDeu

Copy link
Copy Markdown
Contributor Author

Head ad82bf2: (1) GPT 6.1 F1 (failed reconnect drops attachments): when a reconnect fails and no client can fetch the files, the router no longer delivers the caption alone or returns silently; the owner gets the same 'message not delivered' notice the held-work give-up sends (events_queue.notify_slack_undelivered). Test: test_attachments_a_failed_reconnect_cannot_fetch_are_noticed (caption and file-only). (2) Bundle Size Gate: the Reconnect UI took SettingsPage from ~498.8 KB on main to 501.0 KB (500 KB default); added a measured SettingsPage entry in CHUNK_BUDGETS, 527 KB (~5% headroom), with attribution in the comment.

@CrysisDeu

Copy link
Copy Markdown
Contributor Author

Head 855366f: GPT 6.1 F1 (heartbeat result dropped during a reconnect) is the same class as the attachment finding, so it is fixed the same way: _deliver_result waits for a running reconnect before Slack-bound delivery and reads the published client once; if the attempt fails, a Slack-only result becomes a dashboard notification instead of vanishing (the slack: and default arms already notify). Test: test_slack_only_arm_waits_out_a_reconnect (connected and failed). Also adds notify_slack_undelivered to the slack.events facade manifest (the facade tests that went red on ad82bf2).

@CrysisDeu

Copy link
Copy Markdown
Contributor Author

Holding this head (855366f): two fix rounds are spent, and the two new blocks are new findings, not regressions of the earlier fixes. Both look valid and both sit in this PR's own Reconnect path: (1) GPT 6.1: the replacement RealSlackClient never gets agent_sessions.status.configure(orch), so native session status and Stop buttons go quiet after a reconnect until restart. (2) Opus 5.5: a boot pin left unconfirmed by a transient probe failure (_slack_team_id empty) makes every same-token reconnect fail as workspace_switch_needs_restart, after _close_socket has already torn the socket down. Next round should take both together.

…the boot pin

Boot pins its workspace only when it published a Web API client, either
as orch.slack or as the dashboard's copy (init_socket_mode can clear
orch.slack alone). A leftover bot token without its app token pins
nothing, so a reconnect can adopt the workspace the user saves. The boot
workspace probe releases the pin only for a token that never
authenticated (invalid_auth, not_authed) with no Slack work admitted; a
revoked or expired token keeps it.

While a reconnect runs with no client published, the Slack queue drains
and the inbound route keep their entries queued instead of dispatching
them, and a connected reconnect starts them again. A reconnect that
retires a published client and fails keeps that hold for the next
reconnect (the retry) for HELD_WORK_GIVE_UP_SECS; when the window ends
with no client, each held message leaves its queue and the owner gets one
dashboard notification naming its channel and timestamp, and the hold is
released. A gateway no reconnect took a client from handles a missing
client as on main.

A drain that does dispatch hands _dispatch_queued the client it read in
the same step as the dequeue. An inbound message with attachments waits
for a reconnect in progress and ingests with one client read before
ingestion (process_slack_files and _transcribe_files take slack=).
@CrysisDeu

Copy link
Copy Markdown
Contributor Author

Handing this to a maintainer at head dc9ded5. That was our last fix round: it attaches the agent-session driver on reconnect and moves the workspace check ahead of the socket teardown, and Opus 5.5 now passes. CI is green. GPT 6.1 still blocks, and both findings are open:

  1. reconnect.py: if the pin is unconfirmed and the boot token cannot name its workspace again (revoked), a different token is admitted, and queued work for workspace A is sent through B's client. GPT asks to refuse a changed bot token while the pin stays unconfirmed, and to let the same token recover. That reverses the rule this round used: only a known, different team is a switch.
  2. SlackPanel.tsx: a refusal before teardown returns {connected: true, connect_error: workspace_switch_needs_restart}, and the panel shows that as success. The panel should check connect_error before connected (or the route should answer connected: false for a refusal).
    No more pushes from us.

@bolichen97

Copy link
Copy Markdown
Contributor

[operator: bolichen97] Continuing this in #32304; thanks for the start.

@iamwhatever

Copy link
Copy Markdown
Contributor

Thanks for this work. The same feature has landed in #32304 (#32304), which closed issue #10306 on 2026-11-10. Closing this one as superseded. Please reopen if something here is still missing on main.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

merge conflict Branch has merge conflicts with its base — author must resolve before merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Slack: add a Reconnect action so saved credentials take effect without restarting the gateway

3 participants