Repository navigation
refactor(dashboard): compose the chat handlers from chat_api owners - #16427
Conversation
Design Review (Opus 5.5) — ✅ PASSDesign-level review of Design-Verdict: PASS Make sure the bytecode-sweep contract test runs in the required CI lane: owner modules' own imports are inert, so only that test catches an unbound name. [DESIGN-REVIEWED] 68549f5 Description read[DESCRIPTION-READ] 55bd2ae13a8b14b72c13cadc37fe14a193267baaa1235c6d26e64abe70aebf0c 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 |
First Principles Review (Opus 5.5) — 🟡 CONCERNSPremise-level review of First-Principles-Verdict: CONCERNS
Not justified as shipped
What this change shipsInventory (6 items) — 5 justifiedIntent: make the chat API endpoints easier to review and change by splitting the 15,900-line handlers file, with no behaviour change. This is a refactor (neither FIX nor ADDITION).
[FIRST-PRINCIPLES-REVIEWED] 68549f5 Description read[DESCRIPTION-READ] 2de91264df25c456d71387a730bfc96d28cf8d7d447e706745d7c3b2b863c51e That sha256 names the PR description this verdict read. Recompute it with |
Opus 5.5 Review — ✅ no blocking findingsReviewed Verdict parsed from the review's SHA-scoped output markers for commit False positive or not applicable? A repository writer can comment: |
GPT 6.1 Review — ✅ no blocking findingsGPT 6.1 completed its review of This comment is updated in place on each push. Review detailsNo findings. False positive or not applicable? A repository writer can comment: |
|
dashboard/chat_handlers.py held the core chat HTTP endpoints and their helpers in one 15,900-line module. Four endpoint families move into owners under dashboard/chat_api/: source links (list and unlink), slot detail (the slot list, the bounded transcript page and the context meter), resume from History, and the slot lifecycle after create (close and delete, the cleanup sweep, the conversation reset). The bodies move unchanged apart from comment and docstring rewords the comment-history gate requires and two mypy pragmas in resume_slot_from_history. chat_handlers.py stays the only import path and the only patch surface. It imports every moved name back, and chat_api.compose runs each owner function on its globals, so a patch of chat_handlers.<name> still reaches moved code, logs keep the chat_handlers logger, and module state stays on the facade. The send path, slot create and reload, stop/continue/interrupt, the selection transactions, mode and approval, context and note, and summary stay in the facade, as does the code that read-only guards pin to that file by path or function name. The guards that read the moved code by path now read chat_handlers.py plus its chat_api owners, with unchanged thresholds, and the source-corpus blocking-on-loop ceiling is re-pinned to its true value. The error-code baseline, the non-egress redaction registry and the dashboard module list in learn-cron-dashboard.md name the owners.
3563d38 to
68549f5
Compare
|
buluoray
left a comment
There was a problem hiding this comment.
Verdict: APPROVE
Reviewed at head 68549f5c8e647e573fb5fe4840341be1626d98bc (diff base 44ea05c0ed). I did not run the full suite. CI on this head, latest run per check: 83 success, 12 skipped, 0 failure. The two earlier Issue Gate failures and the cancelled GPT 6.1 Review were superseded by green re-runs. Auto-merge is ON and no human review has been posted yet.
Blocking
None.
Non-blocking follow-ups
- Third
composecopy.chat_api/__init__.py:composeis the same aschat_turn/__init__.py:composeexcept for the docstring (the first-principles bot raised this, and I checked it). The author deferred it to #16231 with a stated reason (thechat_turnimport fence). Behaviour is correct, so this does not gate. #16231 should hoist it into one neutral module. - Log record location changes. Records emitted by moved code keep the
kiro_crew.dashboard.chat_handlerslogger name. Theirmodule,filenameandlinenonow name the owner file. The PR discloses this. Anything that greps logs byfilename=chat_handlers.pywill stop matching those records. - Class
__module__changes._DurablePrefixMismatchand_NudgeRetireFailednow report__module__as their owner module, notchat_handlers. Identity is unchanged, soexcept chat_handlers._Xstill catches them. Only reprs and pickling by reference differ. The PR body says "every name … the same object" (true), and thechat_apidocstring states the class caveat. - Reference cycle in
compose._swapcalls itself recursively through its own closure cell, so therebounddict (the pre-rebind originals) is reference-cyclic. It lives until the next GC pass and is then collected (verified: zero stale originals aftergc.collect()). This happens once at import and is harmless. Adel _swapor an iterative unwrap would make it collect immediately. - Stale doc cites. The PR body lists the docs that still cite
chat_handlers.pyfor moved symbols (feature-map rows 68/74/95/117,learn-cron-dashboard.md:2439, several RFCs,session_memory.py:239). They should land in the planned docs-sync follow-up.
What I verified
#16020 priority-queue wiring (merge 1423dfbf17):
1423dfbf17is an ancestor of this head. The PR does not touchchat_runner.py,chat_threads.py,request_priority.pyorstart_priority.py.- I replayed all 291 distinct added lines of #16020 across those files plus
chat_handlers.pyagainst the head (facade +chat_turn/*+chat_api/*). Zero lines are missing. - The wiring is intact at head:
chat_runner.py:5707(_turn_start_priority),:7487(_turn_priority),:9145,:17259,:17832;chat_handlers.py:2576,:6125,:8521(schedule_eager_spawn(..., start_priority=owner_start_priority(request)));chat_threads.py:727,:965.
- Counts in base
chat_handlers.pyvs head (facade + owners) are equal:schedule_eager_spawn5/5,owner_start_priority4/4,_eager_spawn7/7. test/test_start_priority.pyand the contract file: 222 passed.
Nothing dropped or altered:
- AST inventory of base
chat_handlers.pyvs head facade + 4 owners, with docstrings stripped and comments not in the AST:- all 178 top-level defs, classes and name assignments are present;
- 0 bodies differ in code. Three moved definitions (
_same_persisted_body,_is_answered_permission,api_chat_slot_reset_conversation) differ only in docstring/comment wording ("no longer" -> "does not"), confirmed by diffing their source segments; - 0 names are defined twice;
- the only new defs are
compose,_functions_ofand_rebind.
- No module-level side-effect statement was lost: the base has one (
if TYPE_CHECKING:), and the head adds only thecompose(...)call. No import was dropped from the facade. - Owners have no non-constant default args. The only decorator is
@contextlib.asynccontextmanageron a nested function created at call time, which therefore runs on rebound globals. - Same inventory on
git merge-tree origin/main HEAD: the merge is clean, again 0 missing and 0 changed against currentorigin/main. Four main commits since the base touchedchat_handlers.py; none changed a moved body. - Runtime probe (file under scratch) importing the composed facade:
- all 43 owner functions and methods have
__globals__ is chat_handlers.__dict__; - every
LOAD_GLOBALthey read (including nested code objects) is bound on the facade or in builtins; - every top-level facade binding of a moved name is the rebound object;
- after
gc.collect()no un-rebound original survives anywhere, so no registry or container captured a stale copy.
- all 43 owner functions and methods have
Auth, owner, app-isolation and CSRF:
- The moved bodies are AST-identical, so the in-handler checks are unchanged. That covers
api_chat_slot_deleteapp-ownership (slot_lifecycle.py:1003) and_check_slot_app_ownership/_reauthorize_after_awaitin the source-link unlink (source_links.py:267,391,451,713). It also coversis_owner_dashboard_requestin the slot list (slot_detail.py:68). - Symbol counts base → head:
is_owner_dashboard_request18/18,app_isolation30/30. The +1 on_check_slot_app_ownershipand_reauthorize_after_awaitcomes from owner import lines. - CSRF and token auth are middleware-level.
routes/,chat.py,origin.pyandtoken_auth.pyare untouched by the diff. security_posture.NON_EGRESS_REDACTION_MODULESaddschat_api/resume.pyandchat_api/slot_detail.py, the two owners that call a redactor. Theerror-code-baseline.jsontotal is conserved (45 → 41 + 1 + 3).
Mutations (each reverted; git status --short clean after each). All were run against test/test_chat_handlers_composition_contract.py:
| Mutation | Result | Tests that went red |
|---|---|---|
compose made a no-op |
11 red | test_every_owner_function_runs_on_the_facade_globals, test_a_patch_of_the_facade_reaches_an_owner_function, test_compose_rebinds_functions_and_class_members, test_a_second_facade_import_recomposes_the_owners_onto_it, test_every_global_an_owner_function_reads_is_bound_on_the_facade, test_an_app_cannot_delete_a_slot_it_does_not_own[foreign/unscoped], test_resume_* ×2, test_the_handover_exit_wakes_the_conductor_* ×2 |
Owner function reads a name bound only in its owner (_OWNER_ONLY_FLAG in _slot_still_ours) |
1 red | test_every_global_an_owner_function_reads_is_bound_on_the_facade |
App-ownership check in api_chat_slot_delete neutered (slot_lifecycle.py:1003 → if False and …) |
2 red | test_an_app_cannot_delete_a_slot_it_does_not_own[foreign], [unscoped] |
Fail-open / fail-closed:
- The one new runtime mechanism is
compose. If it is wrong, an owner function reads its own module's globals. That fails open for test reach (a patch would miss the moved code) and for unbound names (a NameError at request time). Both are pinned by the contract tests above. - No new error path or refusal was added to production logic.
Serialise both favourite writes under one lock. Each is a read-modify-write of one file on a worker thread, so two dashboard tabs writing at once would each write back the snapshot they read and one change would be lost. Resolve the path off the event loop. realpath and the sensitivity check both walk the filesystem, and on a stalled network mount either would freeze every request and the heartbeat; the add handler now hands all three probes to one worker-thread call. Drop the 100-entry cap and its 409. Both write verbs are owner-gated, so the bound had no caller to defend against, and a list curated by hand should not refuse an entry. This also removes a raw `favorites_full` code the write notice could have shown. Give the write-failure notice the same agent hand-off decision as its sibling read notices: on when the mount opts in through errorHandoff, closing the popover as it hands off. Move the Browse pane's favourite toggle out of the Back / Select row onto a row of its own, with its action as visible text, so the row keeps two controls and the toggle explains itself without a tooltip. Make the remove test portable: a bare "/a" exists on GitHub Windows runners, whose workspace root is D:\a. Replace the capture fixtures' home-directory paths with a neutral /home/dev tree, and add a Browse scene to the capture. A favourites file that exists but cannot be read -- a hand edit with a trailing comma, a permission change -- read as an empty list on every path, so the next star click wrote back that empty snapshot plus one entry and replaced the user's whole list. Unlike the recents window it cannot be rebuilt. The write paths now load strictly: an unreadable file raises, both write verbs answer 409 favorites_unreadable naming the file, and nothing on disk is touched. The display read stays tolerant. An opening favourites read that answers after a star write landed no longer publishes its older list over the write's; it still settles the landing tab, which waits on it. Register the three favourites routes in the route-composition contract that kirodotdev#16427 added after this branch was cut. Add capture scenes for the favourites read failure, a refused write, and Browse on a directory that is already a favourite.
Serialise both favourite writes under one lock. Each is a read-modify-write of one file on a worker thread, so two dashboard tabs writing at once would each write back the snapshot they read and one change would be lost. Resolve the path off the event loop. realpath and the sensitivity check both walk the filesystem, and on a stalled network mount either would freeze every request and the heartbeat; the add handler now hands all three probes to one worker-thread call. Drop the 100-entry cap and its 409. Both write verbs are owner-gated, so the bound had no caller to defend against, and a list curated by hand should not refuse an entry. This also removes a raw `favorites_full` code the write notice could have shown. Give the write-failure notice the same agent hand-off decision as its sibling read notices: on when the mount opts in through errorHandoff, closing the popover as it hands off. Move the Browse pane's favourite toggle out of the Back / Select row onto a row of its own, with its action as visible text, so the row keeps two controls and the toggle explains itself without a tooltip. Make the remove test portable: a bare "/a" exists on GitHub Windows runners, whose workspace root is D:\a. Replace the capture fixtures' home-directory paths with a neutral /home/dev tree, and add a Browse scene to the capture. A favourites file that exists but cannot be read -- a hand edit with a trailing comma, a permission change -- read as an empty list on every path, so the next star click wrote back that empty snapshot plus one entry and replaced the user's whole list. Unlike the recents window it cannot be rebuilt. The write paths now load strictly: an unreadable file raises, both write verbs answer 409 favorites_unreadable naming the file, and nothing on disk is touched. The display read stays tolerant. An opening favourites read that answers after a star write landed no longer publishes its older list over the write's; it still settles the landing tab, which waits on it. Register the three favourites routes in the route-composition contract that kirodotdev#16427 added after this branch was cut. Add capture scenes for the favourites read failure, a refused write, and Browse on a directory that is already a favourite. Reword the favourites read-failure notices: "Pick a project from Recent or Browse" could be read as an instruction to star a folder or switch tabs. They now say "Use Recent or Browse.", which can only mean the tabs.
Problem / Motivation
Goal: Make the dashboard chat API easier to read and change safely by moving four endpoint families out of the 15,900-line
chat_handlers.pyintodashboard/chat_api/owners, with no change in behaviour.src/kiro_crew/dashboard/chat_handlers.pyheld the core chat HTTP endpoints and their helpers in one 840 KB module. A change to resume, close or the slot detail read meant opening and reviewing a file that also holds the send path, every selection transaction and the approval routes.Why it matters
chat_handlers.pyis one of the most edited backend files: more than 60 open PRs touch it. Each of the four families moved here is a cohesive state machine with its own locks and races (the source-link unlink transaction, the bounded transcript page, the resume transaction, the close path). Each can now be read, reviewed and changed on its own, while every caller, route and test seam keeps working unchanged.Not a goal
api_chat), slot create and reload, stop/continue/interrupt and the queue routes, the selection transactions (agent, model, effort, workspace, bulk model), mode and approval, context and note, or summary. Read-only tests or the session-summary spec (R3) pin each of these tochat_handlers.py; the reload route stays beside itsreload_slot_sessioncore. See "Follow-up candidates".composehelper. Slack,chat_turnandchat_apieach keep a copy; hoisting it is tracked in Hoist one shared facade compose helper for the refactor facades (chat_turn, slack, chat_api, messaging_api, file_api, agent_admin, hook_runtime, handler_runtime, server_runtime) #16231.What changed (motivation → approach → change)
Four endpoint families leave the 15,900-line
chat_handlers.pyso each can be read and changed on its own; nothing a caller, route or test sees changes.dashboard/chat_api/)source_links.pyslot_detail.pyresume.pyresume_slot_from_history(materialise, hydrate, reconcile) and the resume routeslot_lifecycle.pyclose_slotand delete, the cleanup sweep, the conversation reset__init__.pycompose, which runs every owner function on the facade's globalsThe four families move as whole function bodies. The only edits are comment and docstring rewords the comment-history gate requires on added lines, plus two
type: ignore[arg-type]pragmas and their comment inresume_slot_from_history. mypy checks the owner beforeDashboardState's inferred attributes, so a closure there loses the narrowing ofhistory_keytostr. A block-by-block comparison against the base found 44 identical blocks apart from those edits.chat_handlers.pystays the only import path and the only patch surface. It imports every moved name back, andchat_api.compose(the techniquechat_turnuses) rebinds each owner function onto its globals. A patch ofkiro_crew.dashboard.chat_handlers.<name>therefore still reaches moved code, records keep that module's logger, and module state (_test_interleave, the lock registries, the in-flight unlink tasks) stays on the facade. Owners import the facade only underTYPE_CHECKING, and never importkiro_crew.acp,kiro_crew.providersorchat_turn.Read-only tests that pinned moved code by path were widened under coordinator grants to read
chat_handlers.pyplus the owners, with unchanged thresholds (table below). The error-code baseline and the non-egress redaction registry name the owners, andlearn-cron-dashboard.mdlists the owners, what stays and where new code goes.Integration-owner edits. Each widened file is proven by planting a violation in an owner (red) and reverting (green); the re-pinned ceiling fails at 910 and passes at 911:
test/test_json_object_body_guard.pytest/test_pending_boundary_consumer_semantics.pytest/test_transcript_derivation_seam.pytest/test_incomplete_archive_fails_closed.py,test/test_mid_chain_read_failure_fails_closed.pytest/test_ws_event_scoping.pytest/test_dashboard_source_link_unlink.py("resume", ...)test/test_truncating_save_recreate_order.pytest/test_ask_question_roundtrip.pytest/test_queued_prompt_durability.py"durable":absence check covers ownerstest/test_dashboard_chat.pytest/test_source_corpus.pyblocking-on-loopceiling re-pinned to the true value: 911 (kept 910, the fourchat_apiowners that holdasyncincluded)error-code-baseline.jsonchat_handlers.py45 → 41,chat_api/slot_detail.py1,chat_api/slot_lifecycle.py3; total unchangedsrc/kiro_crew/security_posture.pyNON_EGRESS_REDACTION_MODULES+ the two owners that call a redactor (resume,slot_detail)Backwards compatibility
Compatible: every module-level name
chat_handlersbound before this change still resolves there as the same object, every route dispatches to the same handler objects, andkiro_crew.dashboard.chatre-exports them unchanged.Reader: src/kiro_crew/dashboard/chat.py:api_chat_slot_detail -- chat -- re-exports the facade object (test_the_chat_facade_reexports_the_handler_objects)
Reader: src/kiro_crew/dashboard/routes/chat.py:register -- chat -- binds chat., the facade objects (test_every_route_still_dispatches_to_the_facade_handler)
Reader: src/kiro_crew/dashboard/session_control.py:resume_slot_from_history -- chat -- imported from chat_handlers at call time (test_session_control_revive.py)
Reader: src/kiro_crew/dashboard/session_control.py:close_slot -- chat -- imported from chat_handlers at call time (test_session_control.py)
Reader: src/kiro_crew/dashboard/session_transfer.py:_materialise_slot_from_history -- chat -- imported from chat_handlers at call time (test_session_transfer.py)
Reader: src/kiro_crew/dashboard/session_transfer.py:_redact_history_rows -- chat -- imported from chat_handlers at call time (test_session_transfer.py)
Reader: src/kiro_crew/dashboard/chat_threads.py:_reconcile_slot_window -- chat -- imported from chat_handlers at call time (test_chat_handlers_composition_contract.py)
Reader: src/kiro_crew/dashboard/chat.py:api_chat_slots_cleanup -- chat -- re-exports the facade object (test_truncating_save_recreate_order.py)
Tests
test/test_chat_handlers_composition_contract.py(new). Contracts no other test pinned, written before the move and green on the base:no_conversation_logrefusal on the route and in the core;Composition checks: every base name and every route still resolves to the facade object; each moved name keeps its base kind and signature; owner functions run on the facade's globals and read no unbound name; a facade patch reaches moved code; the import edges hold. A corpus-derived scan shows no owner captures a name tests rebind. A pinned list of constructs and calls that guards read only in
chat_handlers.py(the turn dispatch, the peer calls and their gate, the pick chokepoint, the permission-resolution and approval-mode sites, the queue clear, the three baselined imports) appears in the facade and in no owner, and no owner reads a harness identity. Every other test that readschat_handlers.pyby path or source was swept for reach, and each one that lost reach is widened above.24 mutation proofs, one per widened guard plus the new contract checks: planted in an owner → red, reverted → green.
Manifest at the first base (
fae38c3c4, 170 files: 10,187 passed) and at this head (manifest + guards: 11,606 passed, 1 skipped, 5 xfailed, 0 failed).local-gate.py --dry-runselects 1,334 backend and 374 frontend files, so the targeted manifest ran instead (SD14).Per-file line coverage on the manifest:
resume82.3%,slot_detail81.1%,slot_lifecycle88.5%,source_links93.9%,__init__98.3% (floor 80).Manual verification
N/A — no user-visible change. A wheel built from this tree ships
kiro_crew/dashboard/chat_api/*. An installed-mode import composes the owners and registers the same handler objects.Related Issues
Part of #16536
Campaign refactor scope D02; follows #16224 (chat runner, merged as 139de6e). Duplicated
composehelper: #16231.Follow-up candidates (stay in the facade; the pin that holds each):
api_chat—test_crew_log_emitandtest_queued_prompt_durabilityread the facade module source;test_chat_turn_timeout_consistency,test_remote_crew_docandtest_decisions_model_route_app_actorread the facade by path.test_remote_crew_executioncounts four pick calls in the facade source;test_decisions_model_route_applyslicesapi_chat_slot_modelfrom the facade file;test_ask_question_roundtripcounts reset call sites.test_session_control_doc,test_remote_crew_execution,test_stop_turn_boundary_mirror.test_approval_modes_enforcementWRITERS, theapproval_resolvedproducer count intest_ws_event_scoping.session-summary.mdnames its routes in this file (R3).test_start_priorityreadsapi_chat_slot_createandreload_slot_sessionby function name in this file; the reload route stays beside its core.Docs that still cite
chat_handlers.pyfor a moved symbol (owner in brackets), for one docs-sync follow-up:docs/feature-map/README.mdrows 68 and 74 (the slot list,chat_api/slot_detail.py), 95 (source links,chat_api/source_links.py) and 117 (api_chat_slot_detail,chat_api/slot_detail.py);docs/system-specs/modules/learn-cron-dashboard.md:2439(AutoNudge row, the nudge restore after a failed close,chat_api/slot_lifecycle.py);rfc-session-tag-change-event.md:288,303(the tag restore,chat_api/resume.py) andrfc-issue-radar-crews.md:537,621(the idle cleanup threshold,chat_api/slot_lifecycle.py);rfc-transcript-section-markers.md:72,80,89,605,621(the conversation reset) andrfc-perpetual-agent.md:526(the close path's question release), bothchat_api/slot_lifecycle.py;rfc-resumable-subagent-sessions.md:107(the resume route,chat_api/resume.py);src/kiro_crew/dashboard/session_memory.py:239andtest/test_session_memory.py:88(chat_api/resume.py).Dotted cites that still resolve through the facade:
learn-cron-dashboard.md:3525(chat_handlers._hydrate_slot_from_history),history.md:1658(chat_handlers._reconcile_slot_window),instances.md:1935(chat_handlers._slot_still_ours),session-control.md:1507(chat_handlers.resume_slot_from_history),rfc-crew-log-wake.md:94and:177(chat_handlers.close_slot).Checklist
feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...)