Skip to content

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

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

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

Conversation

@CrysisDeu

@CrysisDeu CrysisDeu commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

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

Slack tokens and the owner ID are read exactly once, in GatewayOrchestrator.__init__. Saving new credentials 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 was "restart the gateway". POST /api/restart execvs the whole process and tears down every in-flight agent run just to re-run one websocket handshake.

Two details made a lighter fix non-trivial:

  • init_socket_mode early-returns when _slack_enabled is False, and its own failure paths set it False. Re-calling it after any earlier failure (a typo'd token at boot, say) is a silent no-op unless the flag is recomputed from the tokens now on disk.
  • WSSocketModeClient.__init__ needs a current event loop in the constructing thread, so the handshake has to be awaited on the gateway loop, not offloaded.

Why it matters

The first-run Slack setup path is exactly where a token typo happens. Today the recovery is "fix it, restart everything, wait, look again". With Reconnect it is one click and the outcome is on the same screen.

Not a goal

  • Changing POST /api/restart or the schema restart_required badge on the slash command (that field still needs a restart; the config watcher does not watch .env).
  • Hot-reloading Slack credentials automatically on save. Reconnect is explicit so a half-typed token is never applied to a working connection by accident.
  • Registry channels (Discord, Telegram, ...). Slack is host-managed; they reconnect through their own lifecycle.

What changed (motivation → approach → change)

Backend

  • GatewayOrchestrator.reconnect_slack() (src/kiro_crew/slack/gateway.py): re-reads cfg.load_credentials() off-loop FIRST (an unreadable store leaves the live connection untouched and raises), closes the old _socket_client (bounded 2 s, best-effort) and clears the dashboard's slack_client mirror with it, reassigns _app_token / _bot_token / _owner_id / _allowed_users and moves DashboardState.owner_id (the owner-only handlers' authorization subject, otherwise set once at boot) to the saved owner, recomputes _slack_enabled = bool(app and bot), rebuilds the Web API client, then awaits init_socket_mode + _connect_slack on the current loop. The Web API client is published to the dashboard ONLY behind a connected socket: a workspace the enterprise gate rejected, a missing owner, a policy deny or a failed handshake all leave the mirror None, so no dashboard sender (chat_slack, send_message, hooks) can use a workspace that was not admitted. Records slack_socket_connected / slack_connect_error where GET /api/slack/config already reads them, and on a connected socket fires the same deferred warn_unreadable_tracked_channels probe boot runs after its connect (a tracked private channel the install cannot read is warned about whether the operator restarted or reconnected). Concurrent callers share ONE in-flight task via asyncio.shield, so a double-click never races two handshakes; a cancelled HTTP request does not cancel the shared attempt. The shared attempt runs under the dashboard's _get_config_lock() — the lock the PUT holds across its .env write — so a reconnect landing mid-save cannot snapshot the credentials being replaced and hoist them after the save commits (the former owner would stay authorized on the live socket). The lock is taken INSIDE the shared task, not by the HTTP handler: a handler-held lock would serialize two concurrent clicks into two full attempts, the second tearing down the socket the first had just established. It stays held until the attempt ends even when every caller has been cancelled. The boot-time SeenCache is kept across reconnects so redelivered envelopes are still dropped.
  • Declines get a named connect_error the panel can explain: tokens_missing, owner_id_missing, enterprise_validation_failed, denied_by_policy; Slack API errors (e.g. invalid_auth) pass through as before.
  • POST /api/slack/reconnect (dashboard/handlers/messaging.py, registered in dashboard/routes/messaging.py): same guards as the sibling PUT (token auth + CSRF middleware, is_direct_local_request → 403), 503 when no gateway owns a socket (API-only server, DashboardState._slack_reconnect is None), 500 when the store cannot be read; every denial carries a machine-readable code (remote_read_only, slack_reconnect_unavailable, credential_store_unreadable) per the error-code contract. Returns {connected, connect_error} — the pair the GET already documents (no configured: the panel reads it from the GET). SEL access log entry slack.reconnect.
  • PUT /api/slack/config now returns reconnect_required (true when a token/owner was written) and narrows restart_required to config-schema fields. Docstrings that said "restart" now name the reconnect route.
  • Queued Slack turns answer through the client that received them (slack/events.py): the listener init_socket_mode installs captures the socket's own Web API client once, beside the socket it builds, and passes it to _route_message(slack_client=…); all three queue writers there bind THAT client into the entry (not orch.slack sampled at the enqueue line — routing suspends on the governance gate, users.info and file downloads, and a Reconnect in that gap swaps orch.slack to another workspace), and _dispatch_queued uses the bound client for the ⏳ reaction and the turn. Without it a Reconnect to a different workspace would carry a workspace-A reply onto workspace B's client (lost on an unknown channel id, misrouted on a colliding one). Callers without a socket (tests) fall back to orch.slack as it is on entry; entries without the key fall back to the live client.
  • The orchestrator wires dashboard_state._slack_reconnect = self.reconnect_slack right after dashboard init, the same seam the MCP-gateway handlers use.
  • Workspace identity (slack/gateway.py, session_map.py, slack/enterprise.py). Persisted Slack destinations (session-map thread / channel links) name no workspace, so the gateway now records the auth.test team_id they were written under in a NEW small state file beside the session map, slack_workspace.json (SLACK_WORKSPACE_STATE_FILENAME, atomic write), and on every connected handshake — boot and reconnect alike, _adopt_slack_workspace via _bind_slack_workspace — compares it with the workspace just validated. A different one is a SWITCH: every persisted Slack link is swept (SessionManager.clear_all_slack_links), the sweep is awaited to disk (aflush) BEFORE the client is published, and the new identity is persisted and only then adopted in memory. When NO workspace is recorded — every existing install, on its first boot after upgrading — the links are KEPT and the workspace is only recorded (a sweep there would end every live mirror on installs whose workspace never changed). A record that exists but cannot be read is not taken for absent: the attempt is refused with workspace_record_unreadable until the file is repaired or removed, re-read on the next Reconnect (no restart). A handshake that connects but establishes no identity while a workspace is recorded is refused with workspace_identity_unverified (socket torn down again); a record that cannot be written, or a sweep whose flush raises, with workspace_identity_unrecorded — in every refusal the freshly built socket is retired, never left live behind an error.
  • Link generation fence (session_map.py, slack/events.py, slack/handler.py, slack/transport_dispatch.py): a sweep advances SessionMap.slack_links_generation(); a Slack turn captures it when its event is received and presents it to every set_slack_link / set_channel it performs (carried with the queued-turn entry and into both dispatch paths); a stale value is refused, so a turn received under the former workspace and resumed after a switch cannot re-persist its thread.
  • Client affinity (slack/affinity.py): the listener binds the Web API client an envelope arrived through to that envelope's task context (client_scope; _dispatch_queued binds the queue entry's), and GatewayOrchestrator.slack is now a property that resolves to the bound client inside it. Every orch.slack read an interaction, slash command, message turn or the tasks they spawn make keeps answering through the workspace whose destinations it holds; code outside any envelope (routes, boot, cron) sees the live client. The registered listener (_on_envelope) is a synchronous binding around _on_event, whose reserve-before-ack contract is unchanged.

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

  • A Reconnect button (labelled, with lucide's RefreshCw glyph — a plug glyph was tried and read as a padlock, a locked/switched-off control, to a cold reader) in the panel header next to the status pill. Pending: label "Reconnecting…", button disabled. Success: "Connected to Slack." beside the button and the pill flips to Connected (the GET is invalidated). Failure: the notice reads "Reconnect failed: ", the reason coming from one describeConnectError mapper shared with the startup connect_error, so a boot failure and a click failure never describe the same thing in different words — and the prefix shows that the click ran even when the reason is the same text as before the click. A refusal the gateway itself answered — recognised by its own {error, code} JSON body, whatever the status: 403 remote, 500 credential store unreadable, 503 no socket owner — shows the gateway's reason and remedy; only a request that never got the gateway's answer (network error, or an unstructured 5xx such as a proxy body) is the one plain question, "Reconnect failed. Is the gateway running?". No notice in the panel is closable: like the save's own error, each clears when the next click gets an answer, so the two kinds of failure behave as one kind of warning.
  • After a credential save the confirmation reads "Saved. Click Reconnect to apply." instead of pointing at a restart, and the Reconnect button is rendered right beside it (the header may be scrolled off above the long form); it stays until a reconnect succeeds — including across a later save that touched only config fields, which must not hide the reminder that the earlier credentials are still not live. The row's buttons never wrap; a long confirmation wraps in its own column. Slash-command saves keep the restart wording; a save that changed a token AND the slash command names both steps ("Click Reconnect to apply the tokens; the slash command still needs a gateway restart").
  • One notice at a time: while the transport-failure notice is on screen, the connect error the gateway recorded earlier steps aside (two stacked notices read as two problems), and while a click is in flight the previous failure steps aside too ("Reconnecting…" beside a red "failed" reads as the retry having failed already); the recorded reading returns when the next click gets an answer.
  • Hidden on read-only remote sessions, like Save.
  • i18n: new keys in en.manual.json, all 12 locale catalogs and en-XA; en.context.json entries.

Docs: docs/system-specs/modules/messaging.md and docs/feature-map/README.md describe the route and the reconnect flow.

Backwards compatibility

  • Additive: one new POST route, one new response field (reconnect_required) on the PUT. The reconnect response carries only connected / connect_error. Existing clients that only read restart_required see it become false for pure credential saves — the restart they would have offered is no longer necessary, and the button they would have hidden is now the panel's Reconnect.
  • POST /api/restart is untouched and still works as the fallback.
  • Storage: ONE new state file beside the session map, slack_workspace.json ({"team_id": ...}), written on the first connected handshake and rewritten only on a workspace switch. No config-file or schema change. Existing installs: the first boot on this code finds no record, KEEPS every persisted Slack link and only records the workspace — nothing is swept on upgrade; from then on a switch to another workspace sweeps the former workspace's links. A pre-record switch (credentials replaced while the gateway was stopped, before this file existed) is not detected retroactively — the status-quo exposure, unchanged.
  • Fail-closed trade, deliberate: once an identity is recorded, a handshake that connects without establishing one (auth.test failed — the enterprise gate alone tolerated that) is refused and Slack stays down until Reconnect or a restart; a damaged slack_workspace.json is refused the same way until repaired or removed. Both are named in the panel with their remedy.
  • GatewayOrchestrator.slack becomes a property (context-bound inside a Slack envelope, the live client elsewhere); assignment semantics are unchanged.

Tests

Backend — test/test_slack_reconnect.py (83 tests) and 1 added to test/test_slack_config_handlers.py:

  • recomputes _slack_enabled and hoists the new credentials (red on base: base has no reconnect_slack)

  • awaits init_socket_mode on the running loop (asserts asyncio.get_running_loop() identity inside the fake)

  • load failure leaves the live connection untouched (old client still set, no close())

  • missing tokens disable Slack without a handshake; missing owner ID is named for the badge; connect failure reason surfaced

  • old client close() raising does not block the new handshake

  • a rejected workspace leaves no client in the dashboard (the mirror is already None while init_socket_mode runs, and stays None); a failed handshake publishes no client; an owner change moves DashboardState.owner_id; a cleared owner clears it

  • a connected reconnect schedules the tracked-channel probe with the new client and the dashboard notifier; a failed one does not

  • concurrent callers share one handshake (3 awaits → 1 init_socket_mode call); cancelled caller does not cancel the shared attempt

  • the shared attempt waits for _get_config_lock() while a save holds it (no load_credentials call until the lock is released) and keeps the lock until it ends after its caller is cancelled; two concurrent POSTs both reach the orchestrator before either finishes (a handler-held lock would serialize them: red with the lock in the handler)

  • gateway wires the callback onto DashboardState

  • route: answers the GET shape; denies remote sessions like the PUT (403); 503 without a socket owner; 500 when the store cannot be read; registered as POST beside the PUT

  • PUT: a credential change flags reconnect_required, not restart_required

  • route denials carry their code (403 / 503 / 500)

  • queued turn answers through the client bound at enqueue, not the post-reconnect orch.slack (reaction removal and handle_message first arg); an entry without the key uses the live client; all three _route_message enqueue sites bind slack_client (red on base: 2 of 3 fail without the binding); a Reconnect that swaps orch.slack while routing is suspended (inside the governance gate) still leaves the socket's own client in the queue entry and on the ⏳ reaction (red when the enqueue line samples orch.slack); the listener passes its captured client to _route_message

  • workspace identity: a switch sweeps + flushes before publishing and the identity moves last; a flush failure refuses (workspace_identity_unrecorded), retires the new socket and keeps the former identity (no exception, no live listener); the first recorded identity keeps existing links and sweeps nothing; same workspace keeps links; unknown identity with nothing recorded is accepted; unverified with a recorded workspace refuses and tears down; boot binds through the same refusing step; a missing record reads as nothing recorded, a damaged or unreadable one as damaged (never absent); a damaged record refuses (workspace_record_unreadable), sweeps nothing and leaves the file alone; a repaired or removed record recovers on the next reconnect without a restart (removed → first record, same → no switch, former → the switch is caught); construction keeps the damaged reading; an unwritable record refuses and keeps the former identity; the record is on disk before it is adopted in memory

  • generation fence and affinity: stale generation refused; receipt generation carried to both dispatch paths and all three enqueue sites; every envelope kind is dispatched inside the binding by the registered wrapper, which adds no suspension ahead of _on_event (the reserve-before-ack contract in test_update_check_install_aware.py reads _on_event)

Mutation checks (each reverted in turn, test went red, restored): dropping the _slack_enabled recompute → test_reconnect_recomputes_enabled_and_hoists_new_credentials fails; dropping the shared-task coalescing → test_concurrent_callers_share_one_handshake fails; publishing the mirror before validation (and not clearing it at teardown) → 2 tests fail; not moving DashboardState.owner_id → 3 tests fail; dropping the queue-entry client binding → 2 tests fail; sampling orch.slack at the enqueue line → 1 test fails; moving the config lock back into the handler → 1 test fails; dropping the lock from the shared attempt → 2 tests fail; sweeping on the first recorded identity → 2 tests fail; letting an adoption exception out of _bind_slack_workspace → 1 test fails; reading a damaged record as absent → 10 tests fail.

Frontend — website/src/test/SettingsSlackPanelCoverage.test.tsx, new Reconnect block: success shows "Connected to Slack."; pending label + disabled; the previous failure is off screen while a retry is in flight and the outcome replaces it (red without the change); a rejected reconnect is labelled "Reconnect failed: …" in the same words as a startup failure; the gateway-side decline codes; the gateway's own 403, 500 and 503 refusals are shown as-is (red with the old status < 500 gate); a network error and an unstructured 5xx (a proxy body) both become the one plain question; the workspace_record_unreadable code names the file and the remedy; with a recorded connect error on screen, a transport failure leaves exactly one notice, it has no close button, and the next click's answer replaces it; hidden on read-only; a saved credential change points at Reconnect and renders the button beside the confirmation; a save that changed a token and the slash command names both steps; the save-row button survives a later config-only save (red without the change), goes after a successful reconnect and stays after a failed one.

Run by path only (pytest -n0 <file>, npx vitest run <file>); static gates (black, isort, flake8, mypy; tsc -b --force, eslint, i18n gates) green on the changed files. Full suites run in CI.

Manual verification

Dev stack (gateway + Vite) with deliberately invalid Slack tokens in the credential store, so the gateway booted with connect_error: invalid_auth:

  1. Panel shows "Not connected" with the invalid_auth explanation and the Reconnect button (shot 1).
  2. Click Reconnect → "Reconnecting…", button disabled, the recorded failure off screen while it runs (shot 2).
  3. Slack rejects the tokens → "Reconnect failed: Slack rejected the stored tokens (invalid_auth) …" inline, pill stays Not connected (shot 3).
  4. Save a new owner ID → confirmation reads "Saved. Click Reconnect to apply." with the Reconnect button beside it (shot 4).
  5. Clear the owner ID and Reconnect → owner_id_missing explained in plain language (shot 5).
  6. Stop the gateway process (Vite still serving the SPA), click Reconnect → "Reconnect failed. Is the gateway running?" as the only notice, no close button; the recorded invalid_auth reading steps aside (shot 6).
  7. Change the owner ID and the slash command in one save → "Saved. Click Reconnect to apply the tokens; the slash command still needs a gateway restart." with the Reconnect button beside it; Save and Reconnect stay on one line (measured: button height ≤ 40 px) and the message wraps (shot 7).
  8. Three simultaneous POST /api/slack/reconnect (curl) → one real handshake, all three responses identical.
  9. The connected outcome: the build host has no Slack workspace that admits a handshake, so for shots 8 and 9 only the click's answer is stubbed at the network layer (POST /api/slack/reconnect → {connected: true}, and the GET the panel refetches reports the same), armed after the panel rendered the gateway's real recorded state. Header Reconnect → "Connected to Slack." beside the button, pill Connected, the failure notice gone (shot 8); save an owner ID, click the save-row Reconnect → the save-row button retires (shot 9). The real handshake path is pinned by the vitest re-runs the handshake in place and confirms the connection and reuses the existing Connected pill unchanged.

Every screenshot was retaken at this head (the Reconnect glyph in each is asserted to be RefreshCw, no Plug, before the frame is written).

Screenshots / video

Committed under .github/screenshots/ (this account cannot use --attach, cli/cli#14302).

Not connected at startup, Reconnect available:

Slack panel: Not connected after an invalid_auth boot, Reconnect button in the header

Pending state while the handshake runs:

Slack panel: Reconnecting… label, button disabled

Reconnect ran and Slack rejected the tokens — labelled as the click's outcome:

Slack panel: "Reconnect failed: Slack rejected the stored tokens (invalid_auth) …" inside the panel

More states

Saved credentials point at Reconnect instead of a restart, with the button beside the confirmation:

Slack panel: Saved. Click Reconnect to apply., Reconnect button beside it

Reconnect declined because the owner ID is missing:

Slack panel: owner ID missing explained after Reconnect

The request never reached a gateway (process stopped) — one plain question, the only notice on screen:

Slack panel: Reconnect failed. Is the gateway running?

A save that changed a credential AND the slash command names both steps:

Slack panel: Saved. Click Reconnect to apply the tokens; the slash command still needs a gateway restart.

Connected outcome (handshake answer stubbed, see Manual verification 9): "Connected to Slack." beside the header button, pill Connected:

Slack panel: Connected to Slack. beside the Reconnect button, Connected pill

Saved owner ID, then the save-row Reconnect succeeds and retires:

Slack panel: Saved confirmation, Connected to Slack., no save-row Reconnect

Related Issues

Closes #10306

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

@CrysisDeu
CrysisDeu requested a review from a team September 28, 2026 00:07
@CrysisDeu
CrysisDeu requested a review from a team as a code owner September 28, 2026 00:07
@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 Sep 28, 2026
@github-actions

github-actions Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Fable 5) — 🟡 CONCERNS

Design-level review of 3b345ef78c970cdd5c133656c60dbd208e1e4821 — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

Design-Verdict: CONCERNS

Fail-closed workspace machinery now gates boot's previously unconditional Slack publication, and the new versionless strict-schema state file adds ways Slack stays down.

Watch

  • Boot availability narrowing: the Web API client is published "ONLY on a connected socket whose workspace is adopted" — boot and reconnect alike — where _init_services previously set self.slack unconditionally. A boot whose Socket Mode handshake fails (websocket-hostile proxy, Slack outage at boot) or whose edition gate reports no validated_team_id now withholds the client, so cron and dashboard posts that previously flowed over a working Web API are silently skipped until an operator clicks Reconnect. Deliberate and spec'd, but it is a regression for outbound-only configurations.
    Clears when: a maintainer confirms losing Web-API-only posting (socket down, API up) is accepted, or the bind publishes the client on a validated identity even when the socket connect fails.
  • slack_workspace.json is validated closed-world (unknown field(s) at either level → damaged) with no version field, and a damaged record refuses Slack entirely (workspace_record_unreadable) until the file is hand-repaired or removed. Any future additive field — or a newer install's file seen by an older binary after a downgrade — turns into a full Slack refusal rather than a tolerated unknown.
    Clears when: the record carries a version (or the validator preserves bounded unknown fields) with a stated evolution rule, or the spec records that additive evolution of this file is forbidden.

[DESIGN-REVIEWED] 3b345ef

Description read

[DESCRIPTION-READ] e35c91d2782ba159ddcb0a66f6704c9eba2e8a33f9efb350d1dfa4a92d337fde

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 Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Fable 5) — 🟡 CONCERNS

Premise-level review of 3b345ef78c970cdd5c133656c60dbd208e1e4821 — 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/CONCERNS are advisory.

First-Principles-Verdict: CONCERNS

The one-click credential fix carries a full workspace-switch auto-migration — marker, freeze, undo, cron compare-and-swap, snapshot pairing — whose refuse-and-unlink alternative the PR itself already ships for large switches.

Not justified as shipped

  • Item 5 — oversized: the Goal is "Saved Slack credentials take effect from Settings with one click", yet a switch ships _PreparedSlackSwitch, a pending marker with row copies, freeze_slack_links, CronDestinationMismatch/DESTINATION_ANY (2 consumers, both this sweep — grepped expect_destination), _stage_slack_pairing_stable, and restore/undo paths; the diff already refuses switches above SLACK_SWITCH_MARKER_MAX_ROWS with "disconnect conversations you no longer need, then Reconnect" — a remedy that works at any row count.
    Subtraction: shrink _adopt_slack_workspace's switch branch to that existing refusal (adopt only when no links survive), deleting the marker/freeze/undo, the cron CAS surface, and the snapshot pairing loop.
    Clears when: the switch branch is reduced to the refusal, or a human amends the Goal to cover automatic workspace migration.
  • Item 6 — oversized: boot now fails closed — the spec's own words: "a transient auth.test failure at boot — which the enterprise gate alone would have tolerated — now leaves Slack down"; the Goal is reconnect-without-restart, and the stopped-gateway switch is, per the diff, "a pre-existing exposure".
    Clears when: the boot-time bind is dropped (Reconnect-only), or a human amends the Goal to cover it.

What this change ships

Inventory (10 items) — 8 justified

Intent: let a user apply saved Slack credentials from Settings with one click, without restarting the gateway — an ADDITION. More than 10 observable differences; the 10 most noticeable kept.

  1. Reconnect button in Settings → Slack re-runs the handshake in place (POST /api/slack/reconnect) — justified
  2. Saving tokens/owner now says "Reconnect" instead of "restart the gateway" (reconnect_required; copy relabeled in all locales) — justified
  3. Failed connects show named, actionable reasons in the panel — justified
  4. Every install records its Slack workspace id in a new slack_workspace.json on first connected boot — justified
  5. Changing to a different workspace auto-sweeps every saved Slack link (sessions, slots, cron destinations) under crash-safe marker/freeze/undo machinery — oversized (see above)
  6. With a workspace recorded, a handshake naming none leaves Slack down at boot (fail-closed, bounded retries) — oversized (see above)
  7. The client is withheld until verified; cron and dashboard turns wait out that window instead of silently skipping Slack — justified
  8. In-flight and queued turns keep answering through the client and owner that received them, across reconnects — justified
  9. Snapshots taken mid-switch, and old bundles carrying Slack links with no workspace record, are refused — justified
  10. Enterprise gates gain validated_team_id() so editions report the workspace they admitted — justified

[FIRST-PRINCIPLES-REVIEWED] 3b345ef

Description read

[DESCRIPTION-READ] 7b4ea0d3e415a17ffead0212e50bddbd27d32730be15b3c19a605b32c26b79a9

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 Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Fable 5) — 🟡 CONCERNS

UX-level review of 3b345ef78c970cdd5c133656c60dbd208e1e4821 — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS/CONCERNS are advisory.

UX-Verdict: CONCERNS

"Reconnect failed. Is the gateway running?" strands a first-time user — nothing on the page says what the gateway is or how to start it.

Watch

  • Dead-end error: when the request never reaches the gateway, reconnect_failed_is_the_gateway_running renders with no remedy; the blind reader said "I don't know what 'the gateway' is or where I would check or start it — nothing on this page points to it. I would be stuck here." Rare event, but a hard stop every time it fires. Smallest fix: name the thing and the action — e.g. "No answer from the {{productName}} gateway (the local server running {{productName}}). Check it is running, then click Reconnect."
  • Duplicate Reconnect buttons (header slack-reconnect and save-row slack-reconnect-after-save): the reader "cannot tell if they do anything different," and guessed at why the bottom one vanishes in shot 9. Harmless either way since both fire one request, but a title on the save-row instance saying it is the same action as the one above would settle it.

Suggestions

  • reconnect_failed_is_the_gateway_running ends on a question the user cannot answer; rephrase as statement + action per the two Watch fixes above.

[UX-REVIEWED] 3b345ef

Description read

[DESCRIPTION-READ] 8ad9f0a905c6e4ba1617863e53ea74547c3b96b2a7a5cca2980ad99a95c2ee5b

That sha256 names everything this verdict read: the PR description, plus the 12 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 Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

GPT 5.6 Review — ✅ no blocking findings

GPT 5.6 completed its review of 3b345ef78c970cdd5c133656c60dbd208e1e4821 and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 3b345ef

False positive or not applicable? A repository writer can comment:
/ai-review override gpt 3b345ef78c970cdd5c133656c60dbd208e1e4821: <one-sentence reason>

@github-actions

github-actions Bot commented Sep 28, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5 Review — ✅ no blocking findings

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

Review details

No findings.

FINDING — src/kiro_crew/dashboard/state.py:7611 — forget_slack_links's docstring says it is "called by the gateway once a Slack WORKSPACE SWITCH is durable (the persisted rows are swept and the new identity recorded)" and asserts "the former workspace is not reachable through the new client", but its only call site (src/kiro_crew/slack/gateway.py:15296) runs while the switch is merely PREPARED — before the socket connects and before the adopting record write — so on every undo path the install stays bound to the former workspace and the dropped copies have to be rebuilt by rehydrate_slack_links (gateway.py:15364, 15417) → Fix: restate the precondition as a PREPARED switch whose adopting write is still pending, and name rehydrate_slack_links as the undo counterpart instead of claiming the drop is one-way.

[OPUS-REVIEWED] 3b345ef

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

False positive or not applicable? A repository writer can comment:
/ai-review override fable 3b345ef78c970cdd5c133656c60dbd208e1e4821: <one-sentence reason>

@CrysisDeu
CrysisDeu force-pushed the fix/slack-reconnect-route-10306 branch from b1416b3 to a656deb Compare September 28, 2026 02:30
@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 Sep 28, 2026
@CrysisDeu
CrysisDeu force-pushed the fix/slack-reconnect-route-10306 branch from a656deb to 57f79cd Compare September 28, 2026 05:11
@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 Sep 28, 2026
@CrysisDeu
CrysisDeu force-pushed the fix/slack-reconnect-route-10306 branch from 57f79cd to 334712d Compare September 28, 2026 07:12
@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 Sep 28, 2026
@CrysisDeu
CrysisDeu force-pushed the fix/slack-reconnect-route-10306 branch from 334712d to 25d54f8 Compare September 28, 2026 09:12
@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 readiness: checking Automated validation is still running labels Sep 28, 2026
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention and removed merge conflict Branch has merge conflicts with its base — author must resolve before merge readiness: checking Automated validation is still running labels Sep 28, 2026
@CrysisDeu
CrysisDeu force-pushed the fix/slack-reconnect-route-10306 branch from 3f6619d to 1b42c17 Compare September 28, 2026 18:13
@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 Sep 28, 2026
@CrysisDeu
CrysisDeu force-pushed the fix/slack-reconnect-route-10306 branch from 1b42c17 to d9f1571 Compare September 28, 2026 19:33
@github-actions github-actions Bot added the merge conflict Branch has merge conflicts with its base — author must resolve before merge label Sep 28, 2026
@CrysisDeu
CrysisDeu force-pushed the fix/slack-reconnect-route-10306 branch from d9f1571 to 02deca8 Compare September 28, 2026 20:16
@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 merge conflict Branch has merge conflicts with its base — author must resolve before merge readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running labels Sep 28, 2026
@CrysisDeu
CrysisDeu force-pushed the fix/slack-reconnect-route-10306 branch from 02deca8 to 73bbbe6 Compare September 28, 2026 22:07
@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 readiness: checking Automated validation is still running labels Sep 28, 2026
…t a restart

Slack credentials were hoisted once, in GatewayOrchestrator.__init__, and
nothing reassigned them afterwards, so a token or owner ID saved from the
dashboard could take effect only through POST /api/restart, which execv's
the gateway and tears down every in-flight run.

GatewayOrchestrator.reconnect_slack re-runs the Socket Mode handshake in
place: it re-reads the credential store first (an unreadable store leaves
the live socket untouched), closes the old socket client, reassigns the
boot-hoisted tokens and owner, recomputes _slack_enabled from the tokens
now on disk (init_socket_mode early-returns on a stale False and its own
failure paths set it False), rebuilds the Web API client and awaits
init_socket_mode + _connect_slack on the gateway loop. Concurrent callers
share one in-flight attempt. POST /api/slack/reconnect exposes it behind
the PUT's direct-local gate and answers the connected / connect_error pair
GET /api/slack/config already reports; the PUT now returns
reconnect_required for credential writes, leaving restart_required to the
slash command.

The Slack settings panel gains a Reconnect button beside the status pill
with a pending label, renders the outcome through the panel's existing
error notice (one mapper for startup and reconnect failures), and every
"restart the gateway" hint now points at Reconnect instead.

Closes #10306
…ials

Round-3 review fixes for the Reconnect route (#10306):

- A queued Slack turn now answers through the client that received it
  (`slack_client` in the queue entry) instead of whatever `orch.slack` is
  when the queue drains: a Reconnect to another workspace between enqueue
  and drain no longer carries a workspace-A reply onto workspace B's
  client (GPT F1). All three `_route_message` queue writers bind it;
  entries without the key fall back to the live client.
- `POST /api/slack/reconnect` denials carry a machine-readable `code`
  (`remote_read_only`, `slack_reconnect_unavailable`,
  `credential_store_unreadable`) -- the error-code contract gate
  (test_error_code_contract.py) counted the new site as a regression.
- Slack panel: one notice at a time -- while a transport failure is on
  screen the connect error the gateway recorded earlier steps aside, and
  returns when the next click gets an answer (UX watch item).
- Screenshots: shot 6 re-taken with the single notice; shot 7 added for
  the owner-id + slash-command save (combined confirmation).

Round-4 review fixes:

- A reconnect whose old socket client fails (or times out) to close now
  ABORTS instead of continuing: the old listener may still be receiving
  envelopes, and a reconnect that then stops at `tokens_missing` or
  `owner_id_missing` would have left it up under the credentials the
  operator just replaced, with the handler module still bound to the
  former owner (GPT F1, security). The client stays referenced for the
  next attempt or shutdown to close again, nothing from the store is
  hoisted, the handler module's owner / allowlist are cleared, and the
  outcome is `previous_client_close_failed` (mapped in the panel).
- Step 3 rebinds the handler module's owner / allowlist to the saved owner
  on every reconnect, not only on the path that reaches a handshake.
- Screenshots 8 and 9 show the connected state (header
  reconnect; save-row reconnect retiring), with the Slack handshake
  answer stubbed at the network layer as the UX lane asked.

Round-5 review fixes:

- The credential read runs under the config lock the Slack save holds,
  so a reconnect landing mid-save cannot hoist the credentials being
  replaced after the save commits (GPT security finding, round 4). The
  lock is taken INSIDE the shared attempt, not by the HTTP handler: a
  handler-held lock serialized two concurrent clicks into two full
  attempts, the second tearing down the socket the first had just
  established (GPT finding, round 5).
- The socket listener captures its own Web API client once and passes it
  to `_route_message(slack_client=)`; the queue writers bind THAT client,
  not `orch.slack` sampled at the enqueue line -- routing suspends on the
  governance gate, `users.info` and file downloads, and a Reconnect in
  that gap swapped `orch.slack` to another workspace (GPT blocking
  finding, round 5).
- Slack panel: the Reconnect glyph is RefreshCw again -- the plug read as
  a padlock to a cold reader (UX blocker); the previous failure is off
  screen while a retry is in flight; no notice is closable (the two
  notices behaved as two kinds of warning); the save row's buttons never
  wrap; a later config-only save keeps the pending Reconnect reminder
  (GPT finding). Every screenshot retaken at this head.
@iamwhatever

Copy link
Copy Markdown
Contributor

Hi @CrysisDeu — thanks for this PR. I rebased it onto current main and drove it through CI/review. The rebase is done on branch rebase/14574-slack-reconnect (head e177d3daed26d51bff3d975a79326a22cab356c1), which you're welcome to reuse. Your two commits are preserved and authored by you.

Real bugs fixed along the way (each a genuine finding, now in the branch):

  • First-workspace adoption data loss — adoption wrote the workspace record before the socket connected, so a failed first connect could record workspace B and a later reconnect to A would sweep A's Slack links away. Deferred adoption through the prepare/commit/undo lifecycle; a failed connect leaves the record absent.
  • Cron delivery used the wrong client across a reconnect — the cron timer inherited an envelope binding, so after a workspace switch open_dm resolved through the former workspace while the post went through the new one. Bound the settled client across the whole delivery.
  • Cron delivery posted a stale destination — a CLI schedule edit mid-run left the callback posting the old channel/thread. It now resolves the destination from the current job.
  • Snapshot could back up swept links — a byte-identical workspace-record rollback during the snapshot's map-copy window let the pairing probe accept a backup whose links were already swept. Added a fresh non-reusable rev to every record write so that interleaving is never byte-identical.
  • en.context.json lost 27 live translator-context keys in the merge — restored.
  • Lint/type regressions from the rebase — isort ordering, a duplicate _push_observe_limits, mypy has-type on the gateway facades, a comment-history marker, and a cron-store read-decide-write boundary — all fixed.

Where it needs an author/maintainer call (I stopped here rather than force it):

  • src/kiro_crew/slack/gateway.py:5851 — a genuine design conflict. GPT review wants the cron delivery's thread/channel write to be a generation-fenced set_slack_link (so a workspace switch landing mid-post is refused). But main has since shipped thread-eviction-safety in that same block, whose design and tests require the unfenced set_thread/set_channel pair and explicitly forbid set_slack_link (a cron must never claim a human's inherited thread). The two safety mechanisms are mutually exclusive on that one write — reconciling them is a design decision for you/the maintainers, not something the rebase should force one way.
  • GPT also keeps surfacing further rare-timing workspace-switch data-loss edges (in-flight cron_add escaping the sweep; the snapshot pairing excluding cron destinations), and the First Principles review BLOCKs the workspace-switch subsystem as beyond this PR's stated goal ("saved credentials take effect without a restart").

So the direction question — how the fence and eviction-safety should coexist, and whether the workspace-switch machinery belongs in this PR at all — is yours to make. The rebased branch is a ready starting point either way.

@CrysisDeu

Copy link
Copy Markdown
Contributor Author

Superseded by #25780: a redo of this change on current main. This branch is 3292 commits behind, and the messaging handlers have since moved into messaging_api/*. #25780 keeps the Reconnect route and button, and refuses an in-place workspace switch (restart required). That replaces the workspace-switch sweep and fence machinery that review here left as an open design question. Closing this one; the branch is kept.

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