Repository navigation
feat(slack): add a Reconnect action so saved credentials apply without a restart - #16332
iamwhatever wants to merge 2 commits into
Conversation
45deb5f to
2085daa
Compare
UX Review (Opus 5.5) — 🟡 CONCERNSUX-level review of UX-Verdict: CONCERNS There are three ways to "start again" (Reconnect, "restart", "gateway restart") and only one has a button. The reader couldn't tell them apart and saw no way to do a restart. Watch
Suggestions
[UX-REVIEWED] e177d3d Description read[DESCRIPTION-READ] 9e6e465550aec656abedebf3abbf223e9e37e460dd79bc8c47a22b0fc3d6f508 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 |
First Principles Review (Opus 5.5) — 🔴 BLOCKPremise-level review of First-Principles-Verdict: BLOCK Boot now refuses Slack whenever the enterprise gate reports no workspace id. That turns a fail-open channel into a fail-closed one for a Goal about one-click Reconnect. Not justified as shipped
What this change shipsInventory (10 items) — 5 justifiedIntent: apply saved Slack credentials without restarting the gateway — ADDITION
Blockers
[FIRST-PRINCIPLES-REVIEWED] e177d3d Description read[DESCRIPTION-READ] 0126897def6c5509d1e65c699887effa2a78df05beaaee08e935d7b2261bba02 That sha256 names the PR description this verdict read. Recompute it with |
GPT 6.1 Review — 🔴 changes requested (blocking)GPT 6.1 found at least one blocking issue that must be resolved before merging This comment is updated in place on each push. BLOCKING -- src/kiro_crew/slack/gateway.py:5851 -- Cron delivery can restore a swept workspace destination
BLOCKING -- src/kiro_crew/slack/gateway.py:13560 -- In-flight cron creation escapes the workspace sweep
BLOCKING -- src/kiro_crew/snapshot.py:889 -- Snapshot pairing excludes workspace-bound cron destinations
[BLOCK-MERGE] e177d3d Adjudication (Opus 5.5) — is blocking on each finding proportionate?F1 (fenced). Harm is cross-workspace delivery, a security-class rung. Conditions confirmed: the post awaits at F2 (fenced). Same harm rung. The cron sweep in F3 (fenced). Same harm rung. The pairing re-check at False positive or not applicable? A repository writer can comment: |
Design Review (Opus 5.5) — 🟡 CONCERNSDesign-level review of Design-Verdict: CONCERNS Supporting a cross-workspace switch through Reconnect makes a one-click credential refresh rewrite persisted session-map links and cron destinations, with a two-phase marker and undo protocol. Watch
Suggestions
[DESIGN-REVIEWED] e177d3d Description read[DESCRIPTION-READ] c407eec102d0c07c9bd1bd3d4c55e3bc0bdc36adeb88885d8e5c853f5994063c 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 |
2085daa to
67b5849
Compare
Opus 5.5 Review — ✅ no blocking findingsReviewed Review detailsNo findings that block the merge; 2 advisory findings. FINDING — src/kiro_crew/slack/gateway.py:13502 — On a workspace switch, the sweep clears the FINDING — src/kiro_crew/slack/gateway.py:13737 — [OPUS-REVIEWED] e177d3d Verdict parsed from the review's SHA-scoped output markers for commit False positive or not applicable? A repository writer can comment: |
67b5849 to
d9f7c0c
Compare
d9f7c0c to
322ac25
Compare
322ac25 to
98cad69
Compare
a520e04 to
b19f98b
Compare
033a519 to
346019f
Compare
346019f to
a779359
Compare
a779359 to
c6a0d03
Compare
…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. - First workspace adoption is deferred to the socket connect through the same prepare/commit/undo lifecycle a switch uses, so a failed first connect never durably records a workspace it did not reach (GPT 6.1 data-loss finding, gateway.py:_adopt_slack_workspace). - Cron Slack delivery binds the settled client across DM resolution and send (slack_affinity.client_scope) and resolves the destination from the current cron record, so a workspace Reconnect between a cron's ack/edit and its delivery no longer opens the DM through the former workspace's client or posts a stale channel/thread, which consumed a one-shot without its Slack notification (GPT 6.1 F1/F2). - Every workspace-record write stamps a fresh non-reusable `rev`, so a write-then-rollback to the same team_id is never byte-identical and the snapshot pairing probe recopies the session map rather than accepting a backup whose map was staged while the Slack links were swept (GPT 6.1). The cron destination re-read is guarded to a real CronJob so a degraded store read falls back to the captured job. Co-authored-by: cixuuz <26782336+cixuuz@users.noreply.github.com>
c6a0d03 to
e177d3d
Compare
|
Closing this rebase replacement. The rebase onto main is done and all the real bugs found along the way are fixed on branch |
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/restartexecvs 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_modeearly-returns when_slack_enabledisFalse, and its own failure paths set itFalse. 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
POST /api/restartor the schemarestart_requiredbadge on the slash command (that field still needs a restart; the config watcher does not watch.env).What changed (motivation → approach → change)
Backend
GatewayOrchestrator.reconnect_slack()(src/kiro_crew/slack/gateway.py): re-readscfg.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'sslack_clientmirror with it, reassigns_app_token/_bot_token/_owner_id/_allowed_usersand movesDashboardState.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 awaitsinit_socket_mode+_connect_slackon 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 mirrorNone, so no dashboard sender (chat_slack,send_message, hooks) can use a workspace that was not admitted. Recordsslack_socket_connected/slack_connect_errorwhereGET /api/slack/configalready reads them, and on a connected socket fires the same deferredwarn_unreadable_tracked_channelsprobe 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 viaasyncio.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.envwrite — 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-timeSeenCacheis kept across reconnects so redelivered envelopes are still dropped.connect_errorthe 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 indashboard/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-readablecode(remote_read_only,slack_reconnect_unavailable,credential_store_unreadable) per the error-code contract. Returns{connected, connect_error}— the pair the GET already documents (noconfigured: the panel reads it from the GET). SEL access log entryslack.reconnect.PUT /api/slack/confignow returnsreconnect_required(true when a token/owner was written) and narrowsrestart_requiredto config-schema fields. Docstrings that said "restart" now name the reconnect route.slack/events.py): the listenerinit_socket_modeinstalls 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 (notorch.slacksampled at the enqueue line — routing suspends on the governance gate,users.infoand file downloads, and a Reconnect in that gap swapsorch.slackto another workspace), and_dispatch_queueduses 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 toorch.slackas it is on entry; entries without the key fall back to the live client.dashboard_state._slack_reconnect = self.reconnect_slackright after dashboard init, the same seam the MCP-gateway handlers use.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 theauth.testteam_idthey 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_workspacevia_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 withworkspace_record_unreadableuntil 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 withworkspace_identity_unverified(socket torn down again); a record that cannot be written, or a sweep whose flush raises, withworkspace_identity_unrecorded— in every refusal the freshly built socket is retired, never left live behind an error.session_map.py,slack/events.py,slack/handler.py,slack/transport_dispatch.py): a sweep advancesSessionMap.slack_links_generation(); a Slack turn captures it when its event is received and presents it to everyset_slack_link/set_channelit 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.slack/affinity.py): the listener binds the Web API client an envelope arrived through to that envelope's task context (client_scope;_dispatch_queuedbinds the queue entry's), andGatewayOrchestrator.slackis now a property that resolves to the bound client inside it. Everyorch.slackread 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)RefreshCwglyph — 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 onedescribeConnectErrormapper shared with the startupconnect_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.en.manual.json, all 12 locale catalogs anden-XA;en.context.jsonentries.Docs:
docs/system-specs/modules/messaging.mdanddocs/feature-map/README.mddescribe the route and the reconnect flow.Backwards compatibility
reconnect_required) on the PUT. The reconnect response carries onlyconnected/connect_error. Existing clients that only readrestart_requiredsee it becomefalsefor 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/restartis untouched and still works as the fallback.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.auth.testfailed — the enterprise gate alone tolerated that) is refused and Slack stays down until Reconnect or a restart; a damagedslack_workspace.jsonis refused the same way until repaired or removed. Both are named in the panel with their remedy.GatewayOrchestrator.slackbecomes 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 totest/test_slack_config_handlers.py:recomputes
_slack_enabledand hoists the new credentials (red on base: base has noreconnect_slack)awaits
init_socket_modeon the running loop (assertsasyncio.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 handshakea rejected workspace leaves no client in the dashboard (the mirror is already
Nonewhileinit_socket_moderuns, and staysNone); a failed handshake publishes no client; an owner change movesDashboardState.owner_id; a cleared owner clears ita 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_modecall); cancelled caller does not cancel the shared attemptthe shared attempt waits for
_get_config_lock()while a save holds it (noload_credentialscall 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
DashboardStateroute: 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, notrestart_requiredroute denials carry their
code(403 / 503 / 500)queued turn answers through the client bound at enqueue, not the post-reconnect
orch.slack(reaction removal andhandle_messagefirst arg); an entry without the key uses the live client; all three_route_messageenqueue sites bindslack_client(red on base: 2 of 3 fail without the binding); a Reconnect that swapsorch.slackwhile 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 samplesorch.slack); the listener passes its captured client to_route_messageworkspace 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 memorygeneration 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 intest_update_check_install_aware.pyreads_on_event)Mutation checks (each reverted in turn, test went red, restored): dropping the
_slack_enabledrecompute →test_reconnect_recomputes_enabled_and_hoists_new_credentialsfails; dropping the shared-task coalescing →test_concurrent_callers_share_one_handshakefails; publishing the mirror before validation (and not clearing it at teardown) → 2 tests fail; not movingDashboardState.owner_id→ 3 tests fail; dropping the queue-entry client binding → 2 tests fail; samplingorch.slackat 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, newReconnectblock: 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 oldstatus < 500gate); a network error and an unstructured 5xx (a proxy body) both become the one plain question; theworkspace_record_unreadablecode 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:owner_id_missingexplained in plain language (shot 5).POST /api/slack/reconnect(curl) → one real handshake, all three responses identical.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 vitestre-runs the handshake in place and confirms the connectionand reuses the existing Connected pill unchanged.Every screenshot was retaken at this head (the Reconnect glyph in each is asserted to be
RefreshCw, noPlug, 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:
Pending state while the handshake runs:
Reconnect ran and Slack rejected the tokens — labelled as the click's outcome:
More states
Saved credentials point at Reconnect instead of a restart, with the button beside the confirmation:
Reconnect declined because the owner ID is missing:
The request never reached a gateway (process stopped) — one plain question, the only notice on screen:
A save that changed a credential AND the slash command names both steps:
Connected outcome (handshake answer stubbed, see Manual verification 9): "Connected to Slack." beside the header button, pill Connected:
Saved owner ID, then the save-row Reconnect succeeds and retires:
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
feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)