From afb0d868419f99615615bea9d8c97007fee078d6 Mon Sep 17 00:00:00 2001 From: Bolin Chen Date: Fri, 2 Oct 2026 01:28:44 +0000 Subject: [PATCH] fix(apps): limit an app's send on a user session to the turn permissions.sessionApproval lets an app send a turn to a user-owned session through POST /api/chat. The same request could also change the session around that turn: bind an agent onto an agent-less slot, write the persona fields (color_theme, theme_consent, theme_consent_sha), run a harness slash command from the message text, skip the sub-agent hold with steer, supply its own row id, drive the session's auto-title, or keep streaming the user's own queued follow-ups while suppressing the user's dashboard frames. api_chat now derives the caller's access positively (dashboard, owning app, or grant). On the grant path it refuses an agent binding, the persona fields and a harness slash command with 403 app_session_settings_forbidden and an SEL denial before anything is written or queued, using the same predicates as the write sites. The send ignores steer, has its row id minted by the gateway, is echoed to the user's open tabs, and neither the send nor the reply to it starts, counts toward or feeds the session's auto-title or its refresh; a merge of queued messages stops where the turn actor changes. An SSE stream ends at the app's own turn through a turn_end wire frame pushed at the turn's end before the drain or the cycle's end writes anything else, never before a recovery the ending turn queued for itself; the stream skips rows queued for a later turn, and every other reader skips the frame. The grant path re-checks that the slot is still registered, not closing and still a local user session after its off-loop reads. A queued app entry, or one restored from disk, is never classified as a cron or sub-agent event by its text, and the rehydrate refresh-mark rebase counts turns the way the refresh does. An AST pin classifies every body key api_chat reads as turn-only or settings-bearing, so a new key fails until it is classified. The app platform spec, trust model, manifest reference, history spec and dashboard spec describe the narrowed grant. --- docs/app-kit/manifest-reference.md | 2 +- docs/architecture/app-platform-trust-model.md | 15 +- docs/system-specs/modules/app-kit-platform.md | 39 +- docs/system-specs/modules/history.md | 9 +- .../modules/learn-cron-dashboard.md | 4 +- src/kiro_crew/dashboard/chat_handlers.py | 223 +++- src/kiro_crew/dashboard/chat_runner.py | 110 +- src/kiro_crew/dashboard/chat_title.py | 61 +- .../dashboard/chat_turn/steer_queue.py | 5 +- src/kiro_crew/dashboard/chat_utils.py | 27 +- .../slot_persistence/restored_metadata.py | 17 +- test/test_active_turn_session_key.py | 2 +- test/test_chat_mode_security.py | 1125 ++++++++++++++++- test/test_dashboard_chat.py | 2 +- test/test_steer_requeue.py | 2 +- 15 files changed, 1563 insertions(+), 80 deletions(-) diff --git a/docs/app-kit/manifest-reference.md b/docs/app-kit/manifest-reference.md index a68ef736fc28..02a00988d7bd 100644 --- a/docs/app-kit/manifest-reference.md +++ b/docs/app-kit/manifest-reference.md @@ -821,7 +821,7 @@ packages at all. | `permissions.cron` | boolean | Can create cron jobs | | `permissions.memory` | string | Memory access: `""` (none), `"app-scoped"`, or `"shared"` | | `permissions.network` | boolean | Can make external network requests | -| `permissions.sessionApproval` | boolean | Controls existing local user sessions: send messages (including generated response-option choices), approve or deny pending tool requests, and change approval modes within the limits below | +| `permissions.sessionApproval` | boolean | Controls existing local user sessions: send messages (including generated response-option choices, but not a change to the session's agent binding, persona settings, or a harness slash command), approve or deny pending tool requests, and change approval modes within the limits below | | `permissions.spawn` | boolean | May start a background agent through the host's subagent manager (`ctx.spawn`) | | `permissions.jobs` | boolean | May run durable background work through `ctx.jobs` and the app-owned `_jobs/*` routes | | `permissions.exposeToApps` | string[] | App names (or `"*"`) allowed to request cross-app visibility into this app's slots/subagents | diff --git a/docs/architecture/app-platform-trust-model.md b/docs/architecture/app-platform-trust-model.md index 86c20887adfb..a8fd4232f170 100644 --- a/docs/architecture/app-platform-trust-model.md +++ b/docs/architecture/app-platform-trust-model.md @@ -118,10 +118,17 @@ an existing local user-owned session, choose a generated response option, approve or deny a pending tool request, or change that session's approval mode. The app still needs the matching route in `permissions.api`. Cron, system, remote, member-mode, and other apps' sessions are denied; an app's existing -access to its own slots is unchanged. Mode changes must name a live allowed -slot, which prevents one app call from silently widening every session, and are -limited to Normal, Reads and Trust. YOLO is a process-global override: an app -token can neither arm it nor revoke it, so it stays a dashboard-only decision. +access to its own slots is unchanged. A message the app sends runs as a turn: a +send carrying a change to the session's agent binding, persona settings, or a +harness slash command is refused before anything is written or queued +(`chat_handlers._deny_app_session_settings`, pinned by +`test_chat_mode_security`). The send cannot steer, its row is echoed to the +user's open tabs, it neither starts nor names the session's auto-title (a +queued send restored after a gateway restart has lost that attribution), and +its SSE stream ends with the app's own turn. Mode changes must name a live allowed slot, which +prevents one app call from silently widening every session, and are limited to +Normal, Reads and Trust. YOLO is a process-global override: an app token can +neither arm it nor revoke it, so it stays a dashboard-only decision. The guard reads the live manifest so that removing the flag revokes the grant at once. Live-read is not a grant path for this flag: `update_app` compares the old diff --git a/docs/system-specs/modules/app-kit-platform.md b/docs/system-specs/modules/app-kit-platform.md index f27e46993049..5d89393e5736 100644 --- a/docs/system-specs/modules/app-kit-platform.md +++ b/docs/system-specs/modules/app-kit-platform.md @@ -1492,11 +1492,40 @@ or deny tool requests, or change approval modes require an enabled app whose live manifest declares `permissions.sessionApproval: true`. The route must also be allowed by `permissions.api`. Cron, system, remote, member-mode, and other apps' sessions are denied. An app's existing access to its own slots is -unchanged. Mode changes require an explicit live allowed slot and are limited -to Normal, Reads and Trust; YOLO is global rather than slot-scoped, so app -tokens are refused (``app_yolo_forbidden``) for both arming and revoking it. -Consent is -captured when the user enables the app, so `update_app` disables an enabled app +unchanged. On a user-owned session a `POST /api/chat` from the app sends a +turn: a send carrying a change to the session's agent binding, persona settings, +or a harness slash command (the body's `agent` onto an agent-less slot, its +`color_theme` with `theme_consent` and `theme_consent_sha`, or a first word +`is_harness_slash_command` forwards) is refused with 403 +`app_session_settings_forbidden` and an SEL denial before anything is written or +queued (`chat_handlers._deny_app_session_settings`), the same policy as the +agent route. Naming the agent the slot already runs is a +plain send. On that send the `steer` flag is ignored, so it waits behind running +sub-agents like any queued message; the gateway mints the row id; the row is +echoed to the user's open tabs; it starts no auto-title, does not count as a +user turn for titling or the refresh cadence, and the app's turn, its row and +the reply to it, is left out of the automatic title prompts and their truncated +fallback (`chat_title._titling_messages`; the user's own Regenerate title reads +every row); with `dashboard.merge_queued_messages` on, a queued app send never +merges with the user's queued words (`chat_utils._dequeue_next_message` stops a +run where the stamped actor changes); and an SSE send streams the app's own turn +only, including a recovery that same turn queues to retry it (matched by a +per-turn id the recovery carries, not by actor): the `turn_end` frame +lands before the drain or the cycle's end writes a held note, a drop notice or +the next turn's first row, the stream also stops at any user row that is not +its own gateway-minted row, and it skips `queued` placeholder rows (a +cron notification or MCP-App message queued meanwhile), while the user's tabs +keep receiving the session's rows. A queued +send that a gateway restart restores has lost its attribution, because the +restore drops the actor stamp: it drains alone, never merged with fresh words, +as a user row marked `turnProvenanceRestored`, which titling skips on a slot no +app owns, and never as a cron or sub-agent event. `test_chat_mode_security` +pins this, and `test_every_api_chat_body_key_is_classified` fails on a body +field nobody has classified as turn-only or settings-bearing. Mode changes +require an explicit live allowed slot and are limited to Normal, Reads and +Trust; YOLO is global rather than slot-scoped, so app tokens are refused +(``app_yolo_forbidden``) for both arming and revoking it. Consent is captured +when the user enables the app, so `update_app` disables an enabled app whose new version adds the flag (SEL operation `session_approval_widened`) and returns `notice: "session_approval_reconsent"`; the detail page shows that notice and the user re-enables the app after seeing the grant. `register_external_app` diff --git a/docs/system-specs/modules/history.md b/docs/system-specs/modules/history.md index 235c8b660254..cefc2f8dfcf2 100644 --- a/docs/system-specs/modules/history.md +++ b/docs/system-specs/modules/history.md @@ -976,9 +976,12 @@ no longer destroy older turns. - **Client-supplied row `meta` survives the whole path (the client-meta survival contract).** The `meta` a dashboard send carries (`POST /api/chat` body) rides onto the user row it becomes and reaches every - reader unchanged: ingress drops only `RESERVED_ROW_META_KEYS` (today - `decisions_strip`, the gateway's own receipt carrier -- `chat_handlers.py`), - `_redact_meta` (`chat_utils.py`) redacts credential- and exfiltration-shaped + reader unchanged: ingress drops only `RESERVED_ROW_META_KEYS` + (`chat_handlers.py`: the keys the gateway mints itself -- `decisions_strip`, + its receipt carrier, the human-turn marker and the turn-actor stamp), plus + `mid` on an app's send to a user session through `permissions.sessionApproval`, + where the gateway mints the row id (see + [app-kit-platform](app-kit-platform.md)); `_redact_meta` (`chat_utils.py`) redacts credential- and exfiltration-shaped STRING values recursively and is not a key allowlist, `slot.append` broadcasts the row's `meta` on the WebSocket `chat_message` echo (`include_metadata=True`), `_save_slot_to_history` writes it verbatim on the diff --git a/docs/system-specs/modules/learn-cron-dashboard.md b/docs/system-specs/modules/learn-cron-dashboard.md index cc4c4c356064..dc2f279564cf 100644 --- a/docs/system-specs/modules/learn-cron-dashboard.md +++ b/docs/system-specs/modules/learn-cron-dashboard.md @@ -3179,7 +3179,7 @@ member-store identities produce a named error and never inherit Global V1. See [memory](memory-skills-hooks.md#memory-across-surfaces-and-channels) for canonical identity and selected knowledge copying. -**Chat**: POST `/api/chat` (SSE stream, or JSON with `?ws=1` — chunks via WebSocket), `/api/chat/slots` (CRUD, POST accepts optional `agent` field to set agent at creation, plus optional `agent_kind` (`member` | `template`) naming the catalog namespace the agent was picked from — a stated kind is resolved in that namespace only — before the slot is minted, so `409 agent_choice_unavailable` (it does not resolve there) registers no slot — `400 invalid_agent_kind` for any other value; a template kind pins no member memory store; list responses carry the committed `agent_kind`, `""` for a legacy name-first pick or a restored older slot; list responses include `source_links` extracted from slot messages with cached provider/number/state/CI metadata), resume from history, POST `/api/chat/slots/{slot}/generate-title`, POST `/api/chat/slots/{slot}/agent` (switch agent for slot; body `{agent, agent_kind?}` with the same `agent_kind` contract as create, and the response echoes the committed `agent_kind`), POST `/api/chat/slots/{slot}/fork` (fork session — copies visible messages into new slot, body: `{at_message_index?, prompt?}`, returns `{ok, key, title, messages, prompt}`, new slot has `forked_from` metadata), POST `/api/chat/slots/{slot}/edit-resend` (edit a user message and re-run; a real conversation boundary like `rewind` — discards the native ACP conversation, flushes the cleared resume sid, and persists the truncated window before the live slot adopts the edit. Body: `{index?, ts?, content}`. Refusals: 400 `invalid_content` (a present non-string `content`, which would otherwise reach `.strip()` as a 500) / 400 `content_too_long` (over 32768 chars, the same cap `rewind` and `fork` apply, checked before the destructive boundary), 409 `slot_orchestrating` / `slot_subagents_running` (a plan is mid-stage, or sub-agent children are attached to the session the discard would tear down — the same two guards `reset-conversation` applies), 503 `edit_resend_prepare_failed` (discard or sid flush failed), 409 `edit_resend_session_busy` (a channel turn holds the session), 503 `edit_resend_save_failed`, 503 `edit_resend_slot_rebound` (the slot moved to another transcript mid-persistence). App tokens are gated by `_check_slot_app_ownership`, so an app may edit-resend only a slot it owns whose session and transcript are its own — see [session](session.md) → "Edit rewind context boundary"), POST `/api/chat/slots/{slot}/rewind` (edit any past user message and re-run; fork-and-swap — truncates `slot.messages`, removes the slot's ACP session via `SessionManager.remove`, deletes orphaned kiro-cli session JSONL at `~/.kiro/sessions/cli/.json[l]`, then runs the edited prompt against a fresh ACP session under the same slot key/title/folder. Mirrors kiro-cli `/rewind`. Body: `{at_message_index?, ts?, content}`), PATCH `/api/chat/slots/{slot}/mode` (switch session mode — `_VALID_MODES` holds only `""`, and a request naming the retired `"orchestrator"` mode is coerced to `""`; 404 missing slot, 400 invalid mode, 409 while the session is running) +**Chat**: POST `/api/chat` (SSE stream, or JSON with `?ws=1` — chunks via WebSocket; the SSE stream ends at the queue cycle's `done` row, except that an app sending on a user session through `permissions.sessionApproval` streams its own turn only, skipping `queued` placeholder rows, and stops at the `turn_end` wire frame (`chat_utils.TURN_END_WIRE_CLS`) pushed at the turn's end before the queue drain or `_finish_queue_cycle` writes anything (a held note, a drop notice, a successor turn's first row) — not before a recovery the ending turn queued for itself — which every other reader skips — see [app-kit-platform](app-kit-platform.md)), `/api/chat/slots` (CRUD, POST accepts optional `agent` field to set agent at creation, plus optional `agent_kind` (`member` | `template`) naming the catalog namespace the agent was picked from — a stated kind is resolved in that namespace only — before the slot is minted, so `409 agent_choice_unavailable` (it does not resolve there) registers no slot — `400 invalid_agent_kind` for any other value; a template kind pins no member memory store; list responses carry the committed `agent_kind`, `""` for a legacy name-first pick or a restored older slot; list responses include `source_links` extracted from slot messages with cached provider/number/state/CI metadata), resume from history, POST `/api/chat/slots/{slot}/generate-title`, POST `/api/chat/slots/{slot}/agent` (switch agent for slot; body `{agent, agent_kind?}` with the same `agent_kind` contract as create, and the response echoes the committed `agent_kind`), POST `/api/chat/slots/{slot}/fork` (fork session — copies visible messages into new slot, body: `{at_message_index?, prompt?}`, returns `{ok, key, title, messages, prompt}`, new slot has `forked_from` metadata), POST `/api/chat/slots/{slot}/edit-resend` (edit a user message and re-run; a real conversation boundary like `rewind` — discards the native ACP conversation, flushes the cleared resume sid, and persists the truncated window before the live slot adopts the edit. Body: `{index?, ts?, content}`. Refusals: 400 `invalid_content` (a present non-string `content`, which would otherwise reach `.strip()` as a 500) / 400 `content_too_long` (over 32768 chars, the same cap `rewind` and `fork` apply, checked before the destructive boundary), 409 `slot_orchestrating` / `slot_subagents_running` (a plan is mid-stage, or sub-agent children are attached to the session the discard would tear down — the same two guards `reset-conversation` applies), 503 `edit_resend_prepare_failed` (discard or sid flush failed), 409 `edit_resend_session_busy` (a channel turn holds the session), 503 `edit_resend_save_failed`, 503 `edit_resend_slot_rebound` (the slot moved to another transcript mid-persistence). App tokens are gated by `_check_slot_app_ownership`, so an app may edit-resend only a slot it owns whose session and transcript are its own — see [session](session.md) → "Edit rewind context boundary"), POST `/api/chat/slots/{slot}/rewind` (edit any past user message and re-run; fork-and-swap — truncates `slot.messages`, removes the slot's ACP session via `SessionManager.remove`, deletes orphaned kiro-cli session JSONL at `~/.kiro/sessions/cli/.json[l]`, then runs the edited prompt against a fresh ACP session under the same slot key/title/folder. Mirrors kiro-cli `/rewind`. Body: `{at_message_index?, ts?, content}`), PATCH `/api/chat/slots/{slot}/mode` (switch session mode — `_VALID_MODES` holds only `""`, and a request naming the retired `"orchestrator"` mode is coerced to `""`; 404 missing slot, 400 invalid mode, 409 while the session is running) **Source-link unlink**: DELETE `/api/chat/slots/{slot}/source-links/{identity}` removes one PR/issue/Jira chip from a session's sidebar card. The chips are DERIVED — `SlotProjection.source_links` re-scans the transcript on every revision bump — so nothing is deleted; the endpoint records the chip's identity into the slot's **dismissed set** (`_ChatSlot._dismissed_source_links`, `dismiss_source_link(key)`), which the derivation filters against. Nothing touches a remote provider: this hides a chip, it never closes a pull request or an issue. **Identity, not URL**: `{identity}` is the serialized `SourceRef.identity` that every `source_links` entry carries as `identity` — `source_ref_identity_key()` renders the identity tuple to canonical JSON (fixed member order, no incidental whitespace, `ensure_ascii`) and `is_valid_source_identity_key()` validates an untrusted key against exactly that grammar — so a dismissal suppresses the OBJECT, and a re-mention of the same PR through another URL spelling (trailing slash, sub-path pin) stays gone. aiohttp percent-decodes the path segment once and the handler never `unquote`s again, so two identities that differ only by encoding cannot collapse onto one key. **Permanent by design**: a dismissal has no undo and no re-link, and a later paste of the same object does not resurface the chip; the set only grows within a session and is bounded by `_MAX_DISMISSED_SOURCE_LINKS` = 512, the operative ceiling; an identity is also accepted only when it is currently derived from the transcript or already dismissed (a format-valid but never-mentioned identity is a 404 `source_link_not_found`, so a caller cannot inflate durable state with junk). Refusals: 404 `slot_not_found` (identical to the sibling GET, so the response cannot probe which slots exist); the session-aware app-isolation denial of `_check_slot_app_ownership` (the write lands on the transcript the slot ROUTES to, so an app may unlink only on a slot whose transcript is its own — the same gate `/autocompact`, `/context` and `/note` apply); 400 `invalid_source_identity`; 400 `expected_identity_required` when the required `expect` query param (the session identity `||` the chip was rendered under) is absent — it is mandatory so the identity gate always runs; 409 `session_gone` when the slot was deleted or rebound while the request waited, when the transcript's identity cannot be read, when the guarded write declined, or when `expect` does not match the slot's current identity; 409 `dismissed_source_links_full` when the durable set is already at the `_MAX_DISMISSED_SOURCE_LINKS` = 512 ceiling. A repeat of an already-durable dismissal is an idempotent 200 that broadcasts nothing and writes nothing. Success answers `{ok: true, dismissed: true, source_links_total: }`; the client prefers that authoritative `source_links_total` over a local decrement (falling back to `Math.max(0, …-1)` only when an older gateway sends none) and otherwise reconciles from the slots push the endpoint broadcasts. **Persistence**: the set is the slot-owned metadata key `dismissed_source_links` (sorted, deterministic; in `SLOT_OWNED_META_KEYS`, hence in `ROWS_ONLY_DEFERRED_META_KEYS` so a rows-only handover carries the line's own value back verbatim — the key classes are [session](session.md)'s). The endpoint writes it FIELD-SCOPED through `update_metadata_if` under a per-transcript `_source_link_txn_lock` (alias slots of one transcript serialize together), guarded on the transcript's pinned `created_at` so a delete-and-recreate at the same path is declined rather than written into the replacement session, and the written value is the union of every live alias's set with the on-disk line, so a departed alias's committed tombstone is never dropped. Both full-save branches of `_save_slot_to_history` likewise UNION the in-memory set with the on-disk line: a save can add a tombstone but can never shrink the durable set, whatever a slot's in-memory set happens to hold. Two flags make a save carry the on-disk line forward VERBATIM instead: `_dismissed_hydrated is False` (the slot was bound while the transcript's set could not be read — the binding is kept for routing, only the dismissed write is deferred) and `_dismissed_txn_depth > 0` (an unlink holds a tentative in-memory dismissal whose guarded write may still fail and roll back; a periodic flush must not persist it first). On a failed persist the handler rolls the tentative key out of every slot it added it to; a first write that already committed is NOT compensated (there is no cross-process lock spanning the first write and an undo, so undoing it could erase another gateway's acknowledged unlink). Instead it re-reads the transcript identity off-loop and, when that still matches the pin, ACCEPTS the committed grow-only tombstone as durable (disk holds the dismissal, so a 409 would desync); a changed or unreadable identity falls to the 409 rollback, leaving the replacement transcript untouched. **Hydration**: every path that binds a live slot to a transcript and applies its metadata or rows restores the mirror through `_restore_dismissed_source_links` — `_rehydrate_slot_from_history`, `_apply_recent_session`, `surface_channel_session`, `api_chat_slot_resume`, `_bind_cron_slot` (from the off-loop `prefetch_cron_dismissed` read; an unreadable read binds and marks the slot dismissed-unhydrated) and the deleted-job branch of `api_cron_to_chat`. Hydration is authoritative: a transcript with no key CLEARS a reused slot's set (a rebind never carries tombstones into another conversation), and each restored key is re-validated, a tampered entry being dropped rather than aborting the restore — a malformed key can only ever fail to match a real identity. `test_every_metadata_applying_bind_site_restores_dismissals` discovers the bind sites structurally and fails by name on a new one that skips the mirror; because the saves union, a path that forgets the mirror regresses to a stale chip in that slot, not to erasure. **Audit**: every attempt is a permission-class SEL tool invocation named `source_link_unlink` — `allowed` on success (with `already_dismissed`) and `failed` with the `phase` (`lookup`, `ownership`, `expected_identity`, `validate`, `derive`, `reauth`, `identity_pin`, `identity_pin_reauth`, `identity_pin_rebind`, `cap`) on every refusal. **Frontend**: the affordance lives in the session card's existing shared actions menu (`SessionActionsMenu` ⋮), as a **“Hide a PR or Issue chip”** submenu (`SourceLinksSubmenu`, catalog key `source_link_actions`) listing the chips that carry an `identity` (a chip from an older gateway that sent none is not offered); picking one STAGES it (the entry switches to `unlink_source_link_confirm`, “Select again to permanently hide «label»”) and a second select on that staged entry issues the DELETE — a per-item two-step confirmation, since the removal is permanent — hiding the chip optimistically while the mutation is pending (the strip filters pending identities out) and reconciling from the slots push; the submenu is disabled while the gateway is offline, and a failure renders the shared `ErrorNotice` with the localized `unlink_source_link_failed` catalog string, never a raw server or browser message. When a slot carries more links than the serialized preview, the submenu loads the complete list through GET `/api/chat/slots/{slot}/source-links`. Source-link unlink await boundaries: lock acquisition and the metadata identity @@ -3810,7 +3810,7 @@ App calls each owner hook at the position of the inline block it replaced, becau **Panel toggles — user-rebindable, one id per panel** (`lib/panelToggleShortcuts.ts`): four ids — `left-sidebar`, `session-panel`, `side-panel`, `terminal` — each carrying a `Chord` whose `mod` resolves to Cmd on macOS and Ctrl elsewhere. Defaults: session list `mod+B`, activity/side panel `mod+\`, while the nav rail **and** the docked terminal both ship **unbound** (`null`) for the user to opt into. `localStorage('mc-panel-toggle-shortcuts')` holds **overrides only**, so a code default reaches every user who never touched it, while an explicit `null` is a deliberate "cleared to unbound" the loader must preserve rather than collapse back to the default; a write broadcasts `mc-panel-toggle-shortcuts-changed` so the live keydown handler, the Alt+K reference and the Settings → Shortcuts rows re-read without a reload. An unbound id renders its row with the `unset` ("Not set") state rather than being hidden, so it stays discoverable. The terminal's row is hidden when `dashboard.terminal.enabled` is false, matching the nav rail. **Why the terminal alone has no proposed default**: its chord is on the skip-shell allowlist below, so by construction it is taken from the PTY — meaning any default spends one of the user's shell keystrokes for them. `mod+J`, the natural pick (VS Code's Toggle Panel, which HOSTS its integrated terminal), is `^J` on Windows/Linux, i.e. readline's `accept-line`, so a user pressing it instead of Enter would close the panel mid-command; VS Code's terminal chord proper is literal `Ctrl+`` on every platform, unrepresentable in this `Chord` model (`mod` is Cmd on macOS by definition, and ⌘` is the macOS window cycler). Widening the chord model for one binding was rejected, and so was choosing a shell keystroke on every user's behalf — the binding is left to whoever wants it. **Skip-the-shell allowlist**: these chords otherwise yield to any `.xterm` target, because a keystroke aimed at a shell belongs to the shell — but a terminal toggle that yields would open the panel, focus its own shell, and then be unable to close it. `PANEL_TOGGLES_SKIPPING_SHELL` names the ids exempt from that yield (currently just `terminal`), mirroring VS Code's `terminal.integrated.commandsToSkipShell` as a per-COMMAND allowlist rather than a per-key rule, so a future panel with the same need joins a set instead of adding a second special case. The allowlist is honoured by a **capture-phase** `keydown` listener scoped to terminal targets, not by the bubble-phase dispatch: a control-character chord such as `Ctrl+J` is consumed by xterm, so a bubble listener never runs — the same structural point VS Code makes by consulting its own list inside the terminal's key handler. That listener calls `preventDefault` + `stopPropagation`, so the PTY never receives the keystroke; everywhere outside a terminal the bubble path still owns these chords, leaving `defaultPrevented` deference and handler ordering untouched. A panel whose action is absent — terminal disabled, or a popout/embed with no such panel — is treated as unbound on **both** seams, so the chord falls through untouched instead of being swallowed. -**Session titles** — auto-generated after a few turns via background LLM call in `chat_title.py` (`_maybe_auto_title`), pushed to all clients via `slot_title` WS/SSE event, persisted in chat history JSONL metadata via `ConversationLog.update_metadata()` together with `title_origin` (`auto` = background titler, `user` = manual rename; a legacy title with no stored origin rehydrates as `user`). Title input scans reserve a bounded allowance for the dashboard's 20-file upload limit, remove generated image/file references, and then cap retained user text before prompting or fallback selection. Non-image metadata is validated, length-limited, and stored in token-index order so each generated reference resolves directly without scanning every path. Manual trigger via `POST /api/chat/slots/{slot}/generate-title` — it prompts from the *last* `_TITLE_PROMPT_WINDOW` conversational (user/assistant) messages (the user regenerates because the name no longer fits, so the prompt must reflect the current topic, not the opening turns that initial titling reads; filtering before slicing keeps a tool-heavy tail from starving the window); generation errors use the same sanitized first-user-message fallback, while attachment-only placeholder results remain untitled so a later automatic attempt can retry. Cancellation releases the in-flight guard without starting a pending retry. Max 5 auto-title attempts before falling back to the first usable user message. **Background title refresh** (`chat_title.py:maybe_refresh_title`, fired from `chat_done` for already-titled slots): an `auto`-origin title is re-examined at the user-turn milestones in `_TITLE_REFRESH_MILESTONES` (8 and 24) through the same `_bg` one-liner path, with a `KEEP` reply leaving the name alone; each milestone fires at most once (attempt-counted — KEEP/error consumes it) and the consumed mark is persisted as `title_refresh_mark` so restarts cannot re-spend the budget. `dashboard.title_refresh_every_turns` (default `0`, loader-bounded to `0` or 4-1000) replaces the two built-in milestones with a cadence of N, 2N, 3N, ... user turns (`_title_refresh_due`; the low-signal early milestone still applies). It is read per turn off the event loop through the mtime-cached config load (`_title_refresh_every`, which answers `0` on any read failure so a broken config falls back to the built-in schedule). The turn count is read before that thread hop, so a follow-up message landing during it is not counted, and `_refresh_blocked` runs again after it, so a rename or another refresh landing during it stands the attempt down before it consumes the milestone or spends the call. It is attempt-counted through the same `title_refresh_mark`, so crossing several multiples at once costs one refresh. The turn count is taken over `slot.messages`, the rows held for the session. When a session is reloaded, by a gateway restart (`_rehydrate_slot_from_history`, `_apply_recent_session`) or by reopening it from History (`chat_handlers._hydrate_slot_from_history`, which the transfer import shares), every loader holds the latest 500 rows plus the new ones, reconciles the local-turn marker (`_reconcile_local_turn_marker`, which can re-append an opening row the flush never wrote), and then calls `chat_persistence._rebase_rehydrated_refresh_mark`, so `chat_title._rehydrated_refresh_mark` re-bases a persisted mark above the restored user count down to that count, never below the largest fixed milestone at or below the persisted mark across (`_TITLE_EARLY_REFRESH_MILESTONE`, `*_TITLE_REFRESH_MILESTONES`), or 0 when none, so a spent fixed milestone stays spent, and the cadence continues from the re-based mark, at the next multiple of N above it (a lazy re-base in `maybe_refresh_title` would fire on every dip of the front-trimmed count). When the reload keeps fewer user turns than the largest fixed milestone the session had already reached, that floor holds the mark above the restored count and the cadence resumes after the milestone, not after the restored count: with mark 24, 20 restored user turns and N=4, the next refresh is at turn 28, not 24. Import hydrates the same 500-row window, having written the older rows to the transcript as its frozen prefix, so it re-bases the same way. `_ChatSlot.append` front-trims the window at `_MAX_SLOT_MESSAGES` (10,000), so each new row drops the oldest, the count rises only while the dropped rows are not user turns, and refreshes slow down or stop until the next reload. Each refresh is one background call, which is why the setting is opt-in. A manual rename records origin `user`, which locks the refresh out permanently, and bumps `_title_epoch` so an in-flight generation attempt stands down instead of clobbering the rename (the reveal animation is cosmetic-only and never assigns `slot.title`). The epoch guard covers the FOREGROUND endpoint too, not only the background tasks: `api_chat_slot_generate_title` snapshots `_title_epoch` before its generation await and re-checks it at the two points `maybe_refresh_title` does — after the generation await, before writing `slot.title`, and after its own persist await, before `push_slot_title` — and on a mismatch it writes nothing and answers with the endpoint's empty-title "nothing was applied" shape (`{"ok": true, "title": ""}`), which the dashboard's own title control already treats as a no-op, so the name the user typed stays on screen. Two clients issuing a plain `PATCH …/title` concurrently remain last-writer-wins: a conditional write there needs a client-supplied version and a 409 path, which is an open API-contract decision. The generated name follows the **workspace UI language** (`dashboard.language`) rather than the conversation's: `_ui_language()` resolves the tag via `context.ui_language_tag()` and `_build_title_prompt()` interpolates a language directive outside the delimited transcript, with `""` (auto) omitting it and leaving the prompt byte-identical — see `config.md` § Dashboard UI language for the prose-guard and reveal-animation consequences of naming in an unspaced script. +**Session titles** — auto-generated after a few turns via background LLM call in `chat_title.py` (`_maybe_auto_title`), pushed to all clients via `slot_title` WS/SSE event, persisted in chat history JSONL metadata via `ConversationLog.update_metadata()` together with `title_origin` (`auto` = background titler, `user` = manual rename; a legacy title with no stored origin rehydrates as `user`). Title input scans reserve a bounded allowance for the dashboard's 20-file upload limit, remove generated image/file references, and then cap retained user text before prompting or fallback selection. Non-image metadata is validated, length-limited, and stored in token-index order so each generated reference resolves directly without scanning every path. Manual trigger via `POST /api/chat/slots/{slot}/generate-title` — it prompts from the *last* `_TITLE_PROMPT_WINDOW` conversational (user/assistant) messages (the user regenerates because the name no longer fits, so the prompt must reflect the current topic, not the opening turns that initial titling reads; filtering before slicing keeps a tool-heavy tail from starving the window); generation errors use the same sanitized first-user-message fallback, while attachment-only placeholder results remain untitled so a later automatic attempt can retry. Cancellation releases the in-flight guard without starting a pending retry. Max 5 auto-title attempts before falling back to the first usable user message. **Background title refresh** (`chat_title.py:maybe_refresh_title`, fired from `chat_done` for already-titled slots): an `auto`-origin title is re-examined at the user-turn milestones in `_TITLE_REFRESH_MILESTONES` (8 and 24) through the same `_bg` one-liner path, with a `KEEP` reply leaving the name alone; each milestone fires at most once (attempt-counted — KEEP/error consumes it) and the consumed mark is persisted as `title_refresh_mark` so restarts cannot re-spend the budget. `dashboard.title_refresh_every_turns` (default `0`, loader-bounded to `0` or 4-1000) replaces the two built-in milestones with a cadence of N, 2N, 3N, ... user turns (`_title_refresh_due`; the low-signal early milestone still applies). It is read per turn off the event loop through the mtime-cached config load (`_title_refresh_every`, which answers `0` on any read failure so a broken config falls back to the built-in schedule). The turn count is read before that thread hop, so a follow-up message landing during it is not counted, and `_refresh_blocked` runs again after it, so a rename or another refresh landing during it stands the attempt down before it consumes the milestone or spends the call. It is attempt-counted through the same `title_refresh_mark`, so crossing several multiples at once costs one refresh. The turn count is taken over `slot.messages`, the rows held for the session, and counts a user row with `chat_title._counts_as_user_turn`: a row an app sent through `permissions.sessionApproval` (meta turn actor `app`) counts only on that app's own slot, so on a user's session it neither counts toward the auto-title attempts, the milestones or the cadence nor, together with the rows that answer it up to the next counted user row, reaches the auto-title or refresh prompt, their fallback, the low-signal check or the answered-turn check that locks a fallback (`_titling_messages`; see [app-kit-platform](app-kit-platform.md)). The manual `generate-title` trigger is the user's own request and reads every row. A merge run of queued messages stops where the stamped turn actor changes, so the user's queued words never land in an app-stamped row. When a session is reloaded, by a gateway restart (`_rehydrate_slot_from_history`, `_apply_recent_session`) or by reopening it from History (`chat_handlers._hydrate_slot_from_history`, which the transfer import shares), every loader holds the latest 500 rows plus the new ones, reconciles the local-turn marker (`_reconcile_local_turn_marker`, which can re-append an opening row the flush never wrote), and then calls `chat_persistence._rebase_rehydrated_refresh_mark`, which counts with the same predicate, so `chat_title._rehydrated_refresh_mark` re-bases a persisted mark above the restored user count down to that count, never below the largest fixed milestone at or below the persisted mark across (`_TITLE_EARLY_REFRESH_MILESTONE`, `*_TITLE_REFRESH_MILESTONES`), or 0 when none, so a spent fixed milestone stays spent, and the cadence continues from the re-based mark, at the next multiple of N above it (a lazy re-base in `maybe_refresh_title` would fire on every dip of the front-trimmed count). When the reload keeps fewer user turns than the largest fixed milestone the session had already reached, that floor holds the mark above the restored count and the cadence resumes after the milestone, not after the restored count: with mark 24, 20 restored user turns and N=4, the next refresh is at turn 28, not 24. Import hydrates the same 500-row window, having written the older rows to the transcript as its frozen prefix, so it re-bases the same way. `_ChatSlot.append` front-trims the window at `_MAX_SLOT_MESSAGES` (10,000), so each new row drops the oldest, the count rises only while the dropped rows are not user turns, and refreshes slow down or stop until the next reload. Each refresh is one background call, which is why the setting is opt-in. A manual rename records origin `user`, which locks the refresh out permanently, and bumps `_title_epoch` so an in-flight generation attempt stands down instead of clobbering the rename (the reveal animation is cosmetic-only and never assigns `slot.title`). The epoch guard covers the FOREGROUND endpoint too, not only the background tasks: `api_chat_slot_generate_title` snapshots `_title_epoch` before its generation await and re-checks it at the two points `maybe_refresh_title` does — after the generation await, before writing `slot.title`, and after its own persist await, before `push_slot_title` — and on a mismatch it writes nothing and answers with the endpoint's empty-title "nothing was applied" shape (`{"ok": true, "title": ""}`), which the dashboard's own title control already treats as a no-op, so the name the user typed stays on screen. Two clients issuing a plain `PATCH …/title` concurrently remain last-writer-wins: a conditional write there needs a client-supplied version and a 409 path, which is an open API-contract decision. The generated name follows the **workspace UI language** (`dashboard.language`) rather than the conversation's: `_ui_language()` resolves the tag via `context.ui_language_tag()` and `_build_title_prompt()` interpolates a language directive outside the delimited transcript, with `""` (auto) omitting it and leaving the prompt byte-identical — see `config.md` § Dashboard UI language for the prose-guard and reveal-animation consequences of naming in an unspaced script. **Chat cold-URL deep links** (`pages/chat/useChatPageSessionController.ts`, every param captured once at mount) — `?sid=` activates an existing session, `?new=1` creates a fresh one, and `?new=1&prefill=` creates one **and seeds its composer** with `text`. The prompt is staged through the existing `utils/navIntent::writePrefill` (sessionStorage `kirocrew_prefill`, 30s TTL, consumed by ChatPage's slot-restore effect in `pages/chat/page/composerDrafts.ts`) inside `newSlotMutation.onSuccess` — before the `replace` navigate that drops the query string, since the reader on the other side has nothing to seed from afterwards — and the captured value is cleared on use, so retrying a failed create cannot re-seed a session the user has since typed into. **It seeds only and never sends**: auto-send stays behind the signed `?token=` channel flow, so a link an external launcher (Slack card, bookmarklet, CLI `--open`) can build cannot spend a model turn. `prefill` is read **only** when `new=1` is also present, because a bare `?prefill=` is an in-app SENTINEL here — `?prefill=1` from the file explorer's "Chat about this file" and `?prefill=plan` from a project idea's "Edit in chat", both carrying the real text in Redux `pendingInput` — so honouring one would spawn an empty session and type the marker into it. A landed slot list that omits a requested `sid` starts the 5-second missing-session deadline but does not make that verdict permanent: a later authoritative frame carrying the key clears the banner and activates the session only if the active session has not changed since the deadline; after a change it clears the stale banner without changing the active session. The controller latches every post-deadline active-session change, so an away-and-back sequence still suppresses reactivation. `newSession=1` is a different in-app marker, paired with `autoSend=1` by `ProjectsPage`/`DevFleetPage`/`PromptsTab`, and deliberately does NOT alias `new=1`: tripping the mount create as well as `send()`'s forceNew path would make one click create two sessions. diff --git a/src/kiro_crew/dashboard/chat_handlers.py b/src/kiro_crew/dashboard/chat_handlers.py index b19cd0268e96..0e89f63a1ecd 100644 --- a/src/kiro_crew/dashboard/chat_handlers.py +++ b/src/kiro_crew/dashboard/chat_handlers.py @@ -4,6 +4,7 @@ import asyncio import contextlib +import enum import json import logging import math @@ -164,6 +165,7 @@ SESSION_START_FAILED_KIND, SLOT_DETAIL_MAX_LIMIT, SYNTHETIC_RECOVERY_KIND, + TURN_END_WIRE_CLS, _broadcast_expired_oauth_banners, _build_stream_chunk, _collapse_wire_rows, @@ -182,6 +184,7 @@ drained_to_thread, effective_session_key, history_corpus_unreadable, + is_harness_slash_command, ) from kiro_crew.dashboard.chat_utils import ( replacement_shares_transcript as _replacement_shares_transcript, @@ -386,23 +389,73 @@ def _app_slot_is_local_user_session(slot: Any) -> bool: return effective_session_key(slot).startswith("dashboard:") -async def _app_may_send_to_slot(request_app: str, slot: Any) -> bool: - """Return whether an app may control this slot through session APIs.""" +class SlotAccess(enum.Enum): + """How a session-API caller reaches a slot. + + ``DASHBOARD`` and ``OWNER`` may change the slot's settings; ``GRANT`` is an + app on a user-owned session through ``permissions.sessionApproval`` and may + send a turn and nothing else; ``NONE`` is refused. + """ + + NONE = "none" + DASHBOARD = "dashboard" + OWNER = "owner" + GRANT = "grant" + + +async def _app_slot_access(request_app: str, slot: Any) -> SlotAccess: + """Return how *request_app* reaches *slot* through the session APIs.""" if not request_app: - return True + return SlotAccess.DASHBOARD slot_app = str(getattr(slot, "_app", "") or "") if slot_app: - return slot_app == request_app + return SlotAccess.OWNER if slot_app == request_app else SlotAccess.NONE if not _app_slot_is_local_user_session(slot): - return False + return SlotAccess.NONE granted = await asyncio.to_thread( app_permissions.app_can_manage_session_approvals, request_app, ) # Re-judge the slot AFTER the await: a cron/channel binder can re-link it # while the permission read runs off-loop. - return granted and _app_slot_is_local_user_session(slot) + if granted and _app_slot_is_local_user_session(slot): + return SlotAccess.GRANT + return SlotAccess.NONE + + +async def _app_may_send_to_slot(request_app: str, slot: Any) -> bool: + """Return whether an app may control this slot through session APIs.""" + return await _app_slot_access(request_app, slot) is not SlotAccess.NONE + + +def _send_binds_agent(agent: str, slot: Any) -> bool: + """Whether a ``POST /api/chat`` naming *agent* writes it onto *slot*.""" + return bool(agent) and slot.agent in (None, "") + + +def _send_writes_persona(body: dict) -> bool: + """Whether a ``POST /api/chat`` body writes the slot's persona fields. + + ``color_theme`` carries the write; ``theme_consent`` and + ``theme_consent_sha`` are applied with it and never alone. + """ + return "color_theme" in body + + +async def _send_harness_command(message: str) -> str: + """The harness slash command *message* opens with, or ``""`` for plain text. + + The same predicate the runner forwards on (``is_harness_slash_command``), so + what this refuses is exactly what would reach the harness as a command. The + config is read only for a first word that starts with ``/``. + """ + first_word = message.split()[0] if message.strip() else "" + if not first_word.startswith("/"): + return "" + cfg = await asyncio.to_thread(KiroCrewConfig.load) + cc_provider = is_claude_code(cfg.agent.provider) + return first_word if is_harness_slash_command(first_word, cc_provider=cc_provider) else "" def _deny_app_yolo(request_app: str, operation: str) -> web.Response: @@ -420,6 +473,29 @@ def _deny_app_yolo(request_app: str, operation: str) -> web.Response: ) +def _deny_app_session_settings(request_app: str, slot_key: str, trigger: str) -> web.Response: + """App tokens send turns to a user's session but never change its settings. + + *trigger* names what the send would have changed (``agent=``, + ``field=color_theme`` or ``command=``) and rides the SEL row. + """ + reason = ( + "app cannot change the agent binding or persona settings of a session it " + "does not own, or run a harness slash command there" + ) + sel().log_api_access( + caller=request_app, + operation="chat_send", + outcome="denied", + source="app_isolation", + resources=f"slot={slot_key} {trigger}", + error=reason, + ) + return web.json_response( + {"error": reason, "code": "app_session_settings_forbidden"}, status=403 + ) + + #: Row-meta keys a REQUEST may never supply, because the gateway mints them and a #: surface reads them as the gateway's own claim. ``decisions_strip`` is a Jev #: decision receipt with a verdict control attached (``decisions/points/ @@ -429,8 +505,9 @@ def _deny_app_yolo(request_app: str, operation: str) -> web.Response: #: forges human-turn provenance and advances the last-human-turn ranking stamp #: (``chat_persistence._newest_human_turn_ts``), so an app token owning its slot #: could displace human sessions. Stripped here so the gateway re-applies it below -#: only for a genuine human send. -RESERVED_ROW_META_KEYS = frozenset({"decisions_strip", HUMAN_TURN_META_KEY}) +#: only for a genuine human send. ``TURN_ACTOR_META_KEY`` is the gateway's record +#: that an app sent the row, which the title counter reads (``chat_title``). +RESERVED_ROW_META_KEYS = frozenset({"decisions_strip", HUMAN_TURN_META_KEY, TURN_ACTOR_META_KEY}) #: The ``steer`` value that means "let Jev choose between the two paths" rather #: than naming one. A STRING beside the boolean the two manual modes send, so the @@ -691,7 +768,8 @@ async def api_chat(request: web.Request) -> web.StreamResponse: # option click is one such turn. The grant never crosses into another # app's slot. request_app = request.get("app", "") - if request_app and not await _app_may_send_to_slot(request_app, slot): + access = await _app_slot_access(request_app, slot) + if access is SlotAccess.NONE: slot_app = str(getattr(slot, "_app", "") or "") sel().log_api_access( caller=request_app, @@ -704,7 +782,47 @@ async def api_chat(request: web.Request) -> web.StreamResponse: ), ) return web.json_response({"error": "not found", "code": "slot_not_found"}, status=404) - if request_app and not slot._app: + # The dashboard user and the slot's owning app may change the slot's settings + # through this route; the sessionApproval grant reaches a user's session to + # send a turn and nothing else. + may_configure = access in (SlotAccess.DASHBOARD, SlotAccess.OWNER) + steer = body.get("steer") if may_configure else None + if not may_configure: + # The dedicated agent route refuses an app on a slot it does not own, and + # persona consent is the user's own grant from the consent modal. Refused + # rather than dropped, like the agent mismatch below: running the turn on + # an agent other than the one named would be a silent substitution. A + # harness slash command is refused here, above the busy branch, so a + # queued copy cannot run it later. + command = await _send_harness_command(message) + # The slot may have closed, or a cron or channel binder may have + # re-linked it, during the permission and config reads; the grant + # reaches only a local user session (`_app_slot_access` re-judges after + # its own await for the same reason). + if ( + state._slots.get(slot.key) is not slot + or slot.is_closing + or not _app_slot_is_local_user_session(slot) + ): + sel().log_api_access( + caller=request_app, + operation="chat_send", + outcome="denied", + source="app_isolation", + resources=f"slot={slot.key}", + error="slot closed or re-linked during the permission read", + ) + return web.json_response({"error": "not found", "code": "slot_not_found"}, status=404) + # No await sits between this check and the agent write below for a slot + # this grant reaches: the member awaits never run for one, and the + # mismatch branch's awaits run only on a slot that already has an agent. + # The persona condition reads only the request body. + if command: + return _deny_app_session_settings(request_app, slot.key, f"command={command[:64]}") + if _send_binds_agent(agent, slot): + return _deny_app_session_settings(request_app, slot.key, f"agent={agent}") + if _send_writes_persona(body): + return _deny_app_session_settings(request_app, slot.key, "field=color_theme") sel().log_api_access( caller=request_app, operation="chat_send", @@ -712,6 +830,9 @@ async def api_chat(request: web.Request) -> web.StreamResponse: source="app_isolation", resources=f"permissions.sessionApproval|slot={slot.key}", ) + # The gateway mints the row id for a turn sent onto another's session. + if user_meta is not None and "mid" in user_meta: + user_meta = {k: v for k, v in user_meta.items() if k != "mid"} or None # Identity gate for a peer-bound slot, on top of the app-scope 404s above: # those pass every empty-``app`` caller by contract, and a dashboard-link # token is exactly that shape. Sending here would spend the OWNER's tunnel to @@ -881,7 +1002,7 @@ def _compare_bindings(): ) else: logger.debug("agent match for slot=%s agent=%s", slot.key, agent) - elif agent: + elif _send_binds_agent(agent, slot): # Slot has no agent — set it if not running if slot.running: _emit_agent_assignment(slot.key, agent, outcome="denied_running") @@ -895,7 +1016,7 @@ def _compare_bindings(): # No agent on slot, no agent in request — nothing to enforce. pass - if "color_theme" in body: + if _send_writes_persona(body): slot.color_theme = color_theme slot.theme_consent = theme_consent slot.theme_consent_sha = theme_consent_sha @@ -946,7 +1067,7 @@ def _compare_bindings(): # more conjunct on its condition and the receipt it stamps. _auto_strip: dict | None = None _auto_queues = False - if steer_is_auto(body.get("steer")) and not request_app: + if steer_is_auto(steer) and not request_app: # The turn the question is ABOUT, captured before the await. The # decision is a provider round-trip, so the turn it describes can end # while it is in flight -- and an answer about a turn that is gone is @@ -962,7 +1083,7 @@ def _compare_bindings(): if slot.task is not _turn_before: _auto_queues = False _auto_strip = None - if body.get("steer") and not request_app and not _auto_queues: + if steer and not request_app and not _auto_queues: # Client-minted send correlation id (the same `meta.sendId` # convention the plain send path persists): thread it through the # steer so the persisted row and the steer_push echo can be matched @@ -1086,8 +1207,9 @@ def _compare_bindings(): # releases it after the last sub-agent finishes (see chat_runner _hold_users). # Opt-out: if the user explicitly chose steer mode, honour it — start a new # turn immediately so the message is processed without waiting for children. + # An app on a session it does not own has no opt-out (`steer` is None there). if ( - not body.get("steer") + not steer and state.subagents is not None and state.subagents.running_agents_for(effective_session_key(slot)) ): @@ -1150,7 +1272,13 @@ def _compare_bindings(): # (a WebSocket client already receives them) and ignored there, so the flag # can never double-deliver to a local client. relay_mode = not ws_mode and request.query.get("relay") == "1" - slot._has_reader = not ws_mode # Only block SSE broadcast if HTTP SSE reader + # Only block the global broadcast for an HTTP SSE reader that IS the slot's + # own client. An app streaming a turn on a user's session is not the user's + # dashboard, which keeps receiving its rows. + slot._has_reader = not ws_mode and may_configure + # That app's stream ends with its own turn (`TURN_END_WIRE_CLS`), so the + # user's queued follow-ups never reach it. + turn_scoped_stream = not may_configure slot._file_changes = [] # Reset file-change accumulator for the new turn # ── Sweep orphaned permissions from prior turns ── _sweep_stale_permissions(slot) @@ -1284,12 +1412,18 @@ def _compare_bindings(): # app-origin signal as `user_origin` and `turn_actor` above: an app's # send is not a human turn and must not advance the ranking stamp. _user_row_meta[HUMAN_TURN_META_KEY] = True + else: + # The queued path stamps the same actor on its entry, which the drain + # unions onto the row; the title counter reads it off either row. + _user_row_meta[TURN_ACTOR_META_KEY] = "app" _user_row = slot.append("user", message, "msg msg-u", meta=_user_row_meta) _user_mid = _user_row.get("meta", {}).get("mid") - if ws_mode and user_meta and user_meta.get("sendId"): + if not may_configure or (ws_mode and user_meta and user_meta.get("sendId")): # Raw user content belongs on the per-client slot-authorized WS path. # The global SSE queues have no slot gate. In-band/relay sends keep # their existing stream contract and must not gain an extra WS echo. + # An app's turn on a user's session always reaches the user's open tabs, + # whose composer never drew it. state.broadcast_ws( "chat_message", chat_message_frame({**_user_row, "slot": slot.key}, include_metadata=True), @@ -1321,7 +1455,8 @@ def _compare_bindings(): # finish (chat_done). Runs on an isolated background kiro-cli session # concurrent with the turn. No-ops once titled / in-flight; the instant # 60-char provisional stays as the fallback if the LLM SKIPs or errors. - if not slot._titled and not slot._title_in_flight: + # Not from an app's text on a user's session: the user's own turns name it. + if may_configure and not slot._titled and not slot._title_in_flight: _tt = asyncio.create_task(_maybe_auto_title(state, slot)) # Expose the handle so chat_done's chained title→refresh pass can wait # for this attempt to settle (see _title_then_refresh in chat_runner). @@ -1424,33 +1559,49 @@ def _compare_bindings(): resp.content_type = "text/event-stream" resp.headers["Cache-Control"] = "no-cache" resp.headers["X-Accel-Buffering"] = "no" - try: - await resp.prepare(request) - except BaseException: - # `prepare` is the one awaitable between `remote_mirror.attach` above and - # the streaming loop's detach `finally` below. A peer that vanished - # between dispatch and prepare would raise here and skip that finally, - # stranding this slot in the process-global `_MIRRORED` set forever — - # every later frame then mirrors onto `slot._pending` with no reader - # draining it. Drop mirror ownership on the way out so the leak cannot - # happen; the dispatched turn keeps running, exactly as it does when the - # reader disconnects mid-stream. - remote_mirror.detach(slot.key, _relay_owned) - raise - # Declare this reader as the owner of `slot._pending` for as long as it is - # draining. A turn-end chunk release must not run while an SSE reader still - # has undelivered tokens queued, and `_has_reader` alone cannot carry that: - # the `done` branch below clears it before this scope ends. + # draining, from before the first await after dispatch. A turn-end chunk + # release must not run while an SSE reader still has undelivered tokens + # queued, and `_has_reader` alone cannot carry that: the `done` branch below + # clears it before this scope ends, and a turn-scoped reader never sets it. with slot.pending_consumer(): + try: + await resp.prepare(request) + except BaseException: + # `prepare` is the one awaitable between `remote_mirror.attach` above + # and the streaming loop's detach `finally` below. A peer that vanished + # between dispatch and prepare would raise here and skip that finally, + # stranding this slot in the process-global `_MIRRORED` set forever — + # every later frame then mirrors onto `slot._pending` with no reader + # draining it. Drop mirror ownership on the way out so the leak cannot + # happen, and release the broadcast this reader suppressed; the + # dispatched turn keeps running, exactly as it does when the reader + # disconnects mid-stream. + slot._has_reader = False + remote_mirror.detach(slot.key, _relay_owned) + raise try: while True: pending = slot.drain() for msg in pending: - if msg["cls"] == "done": + # Fail closed even if a dispatch path misses turn_end: only + # this request's gateway-minted user row belongs to its SSE. + foreign_user_row = msg.get("role") == "user" and ( + not _user_mid or row_mid(msg) != _user_mid + ) + if msg["cls"] == "done" or ( + turn_scoped_stream and (msg["cls"] == TURN_END_WIRE_CLS or foreign_user_row) + ): await resp.write(b"data: [DONE]\n\n") slot._has_reader = False return resp + if msg["cls"] == TURN_END_WIRE_CLS: + # A boundary for turn-scoped readers, not a row. + continue + if turn_scoped_stream and msg.get("role") == "queued": + # A placeholder for a later turn (a cron notification or + # an MCP-App message queued meanwhile), never this one. + continue chunk = _build_stream_chunk(msg, include_row_meta=relay_mode) await resp.write(f"data: {chunk}\n\n".encode()) try: diff --git a/src/kiro_crew/dashboard/chat_runner.py b/src/kiro_crew/dashboard/chat_runner.py index 8bdf2789c274..99d7e9c275cc 100644 --- a/src/kiro_crew/dashboard/chat_runner.py +++ b/src/kiro_crew/dashboard/chat_runner.py @@ -130,6 +130,7 @@ from kiro_crew.dashboard.chat_tag_grants import refresh_cache as refresh_tag_grants_cache from kiro_crew.dashboard.chat_tags import resolve_board_tags from kiro_crew.dashboard.chat_title import ( + RESTORED_TURN_META_KEY, title_then_refresh, ) from kiro_crew.dashboard.chat_turn import acp_recovery as _owner_acp_recovery @@ -289,6 +290,7 @@ _MAX_TOOL_PURPOSE, STEER_POSSIBLY_DELIVERED_META, STEER_POSSIBLY_DELIVERED_NOTE, + TURN_END_WIRE_CLS, ResetCause, _append_compaction_notice, _apply_incognito_prefix, @@ -304,6 +306,7 @@ _redact_meta_for_role, _redact_tool_field, _remove_queued_by_id, + _stamped_turn_actor, _tool_identity_fields, _validate_tool_name, build_recovery_requeue, @@ -6305,12 +6308,48 @@ def _clear_session_not_found_replay(slot: Any) -> None: SESSION_NOT_FOUND_CANCELLED_TEXT = "ℹ️ Session reconnect cancelled — nothing was run." +def _mark_turn_end(slot: _ChatSlot) -> None: + """Mark on ``slot._pending`` that the turn that just ended is over. + + Pushed at a turn's end before the queue drain or the cycle's end writes + anything (a held note, a drop notice, a successor's first row), never before + a recovery the ending turn queued for itself. The end of the whole queue + cycle is ``done``; this boundary is where an app's stream on a user's + session stops (``chat_handlers.api_chat``), and every other reader skips it, + so a repeated boundary is harmless. + """ + slot.push_wire_frame(TURN_END_WIRE_CLS, "") + + +_RECOVERY_TURN_META_KEY = "recoveryTurnId" + + +def _is_own_recovery(items: "list[dict]", predecessor_actor: str, predecessor_turn_id: str) -> bool: + """Only a retry stamped by the exact ending turn continues its stream. + + Actor equality alone also admits an older, held retry of the same app. + Missing or restored provenance cannot attest to this turn's identity. + """ + return ( + bool(predecessor_actor) + and bool(predecessor_turn_id) + and len(items) == 1 + and is_synthetic_recovery_item(items[0]) + and not items[0].get(RESTORED_QUEUE_KEY) + and isinstance(items[0].get("meta"), dict) + and items[0]["meta"].get(_RECOVERY_TURN_META_KEY) == predecessor_turn_id + and _actor_for_queue_items(items) == predecessor_actor + ) + + async def _start_next_queued_turn( state: DashboardState, slot: _ChatSlot, *, allow_user_during_subagents: bool = False, required_queue_id: str | None = None, + predecessor_actor: str = "", + predecessor_turn_id: str = "", ) -> bool: """Dequeue and start one ready Kiro turn, preserving queue semantics. @@ -6318,14 +6357,36 @@ async def _start_next_queued_turn( bypasses only the child-work hold; an active stage still owns dispatch. ``required_queue_id`` binds the action to the selected card after admission revalidation, so a stale click never starts a different queued message. + ``predecessor_actor`` and ``predecessor_turn_id`` identify the ending turn, + so only a recovery stamped by that exact turn avoids a new-turn boundary + (:func:`_mark_turn_end`). """ + # A drain that follows a turn's end marks that end before it writes anything: + # the drop notices, the held-note flush and the cancellation notices below + # belong to what comes next, not to the turn that ended. Held back only while + # the queue head is that turn's own recovery; the dequeue re-decides then. + turn_ended = False + if predecessor_actor and not _is_own_recovery( + slot._queue[:1], predecessor_actor, predecessor_turn_id + ): + _mark_turn_end(slot) + turn_ended = True + # FIRST, before anything reads the queue: re-assert each entry's # admission-time containment and drop every entry that has stopped # qualifying. # Everything below — the note flush peeking at queue[0], the user-intervention # purge, the dequeue itself — must see only entries that may still deliver. _drop_stale_admissions(state, slot) + # The sweep may have dropped that recovery, leaving a new turn at the head. + if ( + predecessor_actor + and not turn_ended + and not _is_own_recovery(slot._queue[:1], predecessor_actor, predecessor_turn_id) + ): + _mark_turn_end(slot) + turn_ended = True # The admission sweep above (and any other queue removal) can drop the # model-access recovery replay's entry WITHOUT touching slot state: a @@ -6534,8 +6595,14 @@ async def _start_next_queued_turn( # Promotion selects it; merging here would consume unrelated queued user # prompts in the same turn and falsely acknowledge work the user did not # choose. + # Restored entries have no trustworthy actor. Drain sequentially while + # any remain, so their title exclusion never swallows fresh user words + # and a fresh row never launders restored text into a title prompt. next_msg, consumed = _dequeue_next_message( - slot, merge_enabled=merge and not required_queue_id + slot, + merge_enabled=merge + and not required_queue_id + and not any(item.get(RESTORED_QUEUE_KEY) for item in slot._queue), ) if next_msg is None: return False @@ -6568,6 +6635,11 @@ async def _start_next_queued_turn( # They diverge on a recovery that replays the user's own message. synthetic_payload = any(is_synthetic_payload_item(item) for item in consumed) is_system_injection = any(is_system_injection_item(item) for item in consumed) + # Before the successor writes its first row, unless the drain's top already + # marked it. A recovery the ending turn queued for itself is the same turn + # retried, so its reply belongs before the boundary. + if not turn_ended and not _is_own_recovery(consumed, predecessor_actor, predecessor_turn_id): + _mark_turn_end(slot) directive_user_origin = bool(consumed) and all( item.get("_directive_user_origin") is True for item in consumed ) @@ -6600,8 +6672,17 @@ async def _start_next_queued_turn( if not deliver_as_typed: next_msg, _ = redact_exfiltration_urls(next_msg) next_msg, _ = redact_credentials(next_msg) - is_cron = next_msg.startswith(CRON_NOTIFY_PREFIX) - is_subagent = next_msg.startswith(SUBAGENT_COMPLETION_PREFIXES) + # An entry an app sent is never a cron or sub-agent event, whatever its text + # opens with: the actor comes from the enqueue-time kind or stamp, the same + # structural source the MCP-App case below reads. Nor is a restored entry: + # only plain prompts persist (`slot_queue_repository._is_durable_queue_entry`), + # and the restore drops the actor stamp, so the text is all that is left and + # it cannot name an event. + _not_an_event = _actor_for_queue_items(consumed) == "app" or any( + item.get(RESTORED_QUEUE_KEY) for item in consumed + ) + is_cron = not _not_an_event and next_msg.startswith(CRON_NOTIFY_PREFIX) + is_subagent = not _not_an_event and next_msg.startswith(SUBAGENT_COMPLETION_PREFIXES) # STRUCTURAL, not prefix: an MCP-App message's text is app-authored, so # deriving its row from the text would let (and did let) it fall through to # role "user" — persisted and broadcast as human speech — while the @@ -6803,6 +6884,10 @@ async def _start_next_queued_turn( # with any non-human (app) entry, or the ``inject`` branch above, never # reaches here and stays unmarked. _drained_meta[HUMAN_TURN_META_KEY] = True + if row_role == "user" and any(item.get(RESTORED_QUEUE_KEY) for item in consumed): + # This is a loss-of-provenance marker, never authority recovered from disk. + # Persist it on the row so auto-titling and refresh rebase both exclude it. + _drained_meta[RESTORED_TURN_META_KEY] = True current_row = slot.append( row_role, next_msg, @@ -7182,6 +7267,10 @@ async def _finish_queue_cycle( if await _start_next_queued_turn(state, slot): return + # The cycle's end is also the end of the turn that ran it, and it is marked + # before the held-note flush below: that note is owed to the next turn. + _mark_turn_end(slot) + # Before any successor is dispatched. A held note's CONTEXT half drains into # the next turn, so flushing after that turn started would let the note shape # a turn its visible line appears below. Two automatic successors are withheld @@ -7544,6 +7633,8 @@ def _stop_pressed() -> bool: # turn no dispatch claimed is a user turn -- never a guess read off the # message, which the user writes. _crew_log_actor = _turn_actor or ("autonudge" if _directive_self_wake else "user") + # Local to this invocation, including failures before provider dispatch. + _recovery_turn_id = uuid.uuid4().hex # This turn's start priority: its cold start and the eager respawn it may arm. _turn_priority = _turn_start_priority( user_origin=_directive_user_origin, @@ -8085,7 +8176,11 @@ def _queue_recovery( # actor is still known -- the drain sees a fresh queue id and, for a # recovery, no kind that names a producer. The ORIGINAL-replay # attachment lists merged above ride along in _recovery_meta. - meta={**_recovery_meta, TURN_ACTOR_META_KEY: _crew_log_actor}, + meta={ + **_recovery_meta, + TURN_ACTOR_META_KEY: _crew_log_actor, + _RECOVERY_TURN_META_KEY: _recovery_turn_id, + }, on_consumed=_on_consumed if not _consumed_reported else None, on_irreversibly_consumed=( _on_irreversibly_consumed if not _irreversible_consumption_reported else None @@ -17988,7 +18083,12 @@ def _emit_error(msg: str, *, will_retry: bool = False) -> None: # cancellable) and resumes on the user's next send after they log in # — the no-loss rule, without a readiness waiter to strand it. state.push_slots_update() - next_turn_started = await _start_next_queued_turn(state, slot) + next_turn_started = await _start_next_queued_turn( + state, + slot, + predecessor_actor=_crew_log_actor, + predecessor_turn_id=_recovery_turn_id, + ) if not next_turn_started: await _finish_queue_cycle( diff --git a/src/kiro_crew/dashboard/chat_title.py b/src/kiro_crew/dashboard/chat_title.py index d47561785a92..3638b848fc83 100644 --- a/src/kiro_crew/dashboard/chat_title.py +++ b/src/kiro_crew/dashboard/chat_title.py @@ -12,6 +12,7 @@ from kiro_crew.config.loader import KiroCrewConfig from kiro_crew.context import ui_language_tag +from kiro_crew.dashboard.chat_delivery import TURN_ACTOR_META_KEY from kiro_crew.dashboard.chat_folder_suggest import maybe_suggest_folder from kiro_crew.dashboard.chat_utils import ( apply_pending_slot_memory_mode, @@ -1022,6 +1023,48 @@ def _is_low_signal_title(title: str, messages: list[dict[str, Any]]) -> bool: return title == _fallback_title_from_messages(messages) +# The drain records lost provenance, not a restored claim about who sent it. +RESTORED_TURN_META_KEY = "turnProvenanceRestored" + + +def _counts_as_user_turn(slot: _ChatSlot, message: dict[str, Any]) -> bool: + """Whether *message* is a turn of the session's own user, for titling. + + A user row an app sent counts only on that app's own slot. On a user's + session an app reaches through ``permissions.sessionApproval`` it is the + app's turn, and titling from it would let the app name the user's session. + A restored queue row has lost that attribution, so it is excluded too, + rather than trusting a disk stamp as proof of a human turn. + """ + if message.get("role") != "user": + return False + meta = message.get("meta") + not_user_owned = isinstance(meta, dict) and ( + meta.get(TURN_ACTOR_META_KEY) == "app" or meta.get(RESTORED_TURN_META_KEY) is True + ) + return not not_user_owned or bool(slot._app) + + +def _titling_messages(slot: _ChatSlot) -> list[dict[str, Any]]: + """``slot.messages`` without the turns :func:`_counts_as_user_turn` skips. + + A skipped turn is the user row and every row after it up to the next user + row that counts, so the reply to an app's turn goes with it. What the + auto-title and its refresh read: the prompt, the truncated fallback, the + low-signal check and whether the user's turn was answered, so an app's + text never becomes or seeds the automatic name of a session it does not + own. The user-initiated regenerate reads every row. + """ + kept: list[dict[str, Any]] = [] + in_skipped_turn = False + for m in slot.messages: + if m.get("role") == "user": + in_skipped_turn = not _counts_as_user_turn(slot, m) + if not in_skipped_turn: + kept.append(m) + return kept + + async def _maybe_auto_title(state: DashboardState, slot: _ChatSlot) -> None: """Background task: attempt to LLM-title a slot. @@ -1050,17 +1093,18 @@ async def _maybe_auto_title(state: DashboardState, slot: _ChatSlot) -> None: if any(m.get("role") == "assistant" and m.get("content") for m in slot.messages): slot._title_retry_pending = True return - user_count = sum(1 for m in slot.messages if m.get("role") == "user") + user_count = sum(1 for m in slot.messages if _counts_as_user_turn(slot, m)) if user_count < 1 or user_count > _TITLE_MAX_ATTEMPTS: if user_count > _TITLE_MAX_ATTEMPTS and not slot._titled: # Gave up after repeated attempts — fall back to the truncated # first message with an ellipsis. - slot.title = _fallback_title_from_messages(slot.messages) + messages = _titling_messages(slot) + slot.title = _fallback_title_from_messages(messages) slot._titled = True slot._title_origin = _TITLE_ORIGIN_AUTO # The fallback is an echo of the first message — flag it so the # refresh becomes due immediately rather than at the next milestone. - slot._title_low_signal = _is_low_signal_title(slot.title, slot.messages) + slot._title_low_signal = _is_low_signal_title(slot.title, messages) await _persist_title(state, slot) state.push_slot_title(slot.key, slot.title) return @@ -1070,7 +1114,7 @@ async def _maybe_auto_title(state: DashboardState, slot: _ChatSlot) -> None: # synchronously, so a moved epoch (or a set ``_titled``) means a # higher-precedence title is already in place and this attempt stands down. epoch = slot._title_epoch - messages = list(slot.messages) + messages = _titling_messages(slot) attempt_has_assistant = any(m.get("role") == "assistant" and m.get("content") for m in messages) logger.info("Auto-title: attempting for slot %s (turn %d)", slot.key, user_count) @@ -1118,7 +1162,8 @@ async def _maybe_auto_title(state: DashboardState, slot: _ChatSlot) -> None: # definitive failure); on the on-send attempt leave it unlocked so # the end-of-turn retry can still upgrade the truncation to a real # LLM title. - slot.title = _fallback_title_from_messages(slot.messages) + current = _titling_messages(slot) + slot.title = _fallback_title_from_messages(current) slot._titled = attempt_has_assistant if attempt_has_assistant: slot._title_origin = _TITLE_ORIGIN_AUTO @@ -1126,7 +1171,7 @@ async def _maybe_auto_title(state: DashboardState, slot: _ChatSlot) -> None: # it so the refresh prompt (which reads the conversational tail # and frames the task as keep-or-rename rather than # title-or-SKIP) gets one immediate shot at a real name. - slot._title_low_signal = _is_low_signal_title(slot.title, slot.messages) + slot._title_low_signal = _is_low_signal_title(slot.title, current) await _persist_title(state, slot) state.push_slot_title(slot.key, slot.title) logger.info( @@ -1241,7 +1286,7 @@ async def maybe_refresh_title(state: DashboardState, slot: _ChatSlot) -> None: # Count first: the config thread hop below yields to the event loop, and a # queued follow-up that lands during it opens the NEXT turn, which this # refresh must not count. - user_count = sum(1 for m in slot.messages if m.get("role") == "user") + user_count = sum(1 for m in slot.messages if _counts_as_user_turn(slot, m)) every = await asyncio.to_thread(_title_refresh_every) # A manual rename or another turn's refresh may also have landed during the # hop, and either must stand this attempt down BEFORE it consumes the @@ -1287,7 +1332,7 @@ async def maybe_refresh_title(state: DashboardState, slot: _ChatSlot) -> None: ) return title = await _generate_refreshed_title( - state, list(slot.messages), slot.title, session_key=effective_session_key(slot) + state, _titling_messages(slot), slot.title, session_key=effective_session_key(slot) ) if not title: # KEEP/SKIP/prose/error — the current title stands. diff --git a/src/kiro_crew/dashboard/chat_turn/steer_queue.py b/src/kiro_crew/dashboard/chat_turn/steer_queue.py index 820beee1999e..a6c95bdb4e7e 100644 --- a/src/kiro_crew/dashboard/chat_turn/steer_queue.py +++ b/src/kiro_crew/dashboard/chat_turn/steer_queue.py @@ -16,10 +16,10 @@ STEER_POSSIBLY_DELIVERED_META, STEER_STATE_CONSUMED, STEER_STATE_REQUEUED, - TURN_ACTOR_META_KEY, DashboardState, _ChatSlot, _remove_queued_by_id, + _stamped_turn_actor, attachment_meta, crew_log_emit, find_written_steer_row, @@ -416,8 +416,7 @@ def _actor_for_queue_items(items: "list[dict]") -> str: if actor: return actor for item in items: - meta = item.get("meta") - stamped = meta.get(TURN_ACTOR_META_KEY, "") if isinstance(meta, dict) else "" + stamped = _stamped_turn_actor(item) if isinstance(stamped, str) and stamped in crew_log_emit.ACTORS: return stamped return "" diff --git a/src/kiro_crew/dashboard/chat_utils.py b/src/kiro_crew/dashboard/chat_utils.py index e3472d558a24..d577812087cd 100644 --- a/src/kiro_crew/dashboard/chat_utils.py +++ b/src/kiro_crew/dashboard/chat_utils.py @@ -372,6 +372,15 @@ def _redact_tool_field(text: str | None, *, limit: int = _MAX_TOOL_FIELD) -> str return text +#: Wire frame pushed onto ``slot._pending`` at a turn's end, before the queue +#: drain or the cycle's end writes anything (``chat_runner._mark_turn_end``); a +#: recovery the ending turn queued for itself is the same turn and gets none. +#: ``done`` marks the end of the whole queue cycle; this marks the end of one +#: turn, which is where an app's stream on a user's session stops +#: (``chat_handlers.api_chat``). Never a row: other readers skip it. +TURN_END_WIRE_CLS = "turn_end" + + def _build_stream_chunk(msg: dict, *, include_row_meta: bool = False) -> str: """Build a JSON SSE chunk from a slot message, with meta redaction for permissions. @@ -3983,13 +3992,23 @@ def carries_attachments(item: dict) -> bool: return any(isinstance(meta.get(k), list) and meta.get(k) for k in ATTACHMENT_META_KEYS) +def _stamped_turn_actor(item: dict) -> Any: + """The turn actor stamped on a queue entry's meta, or ``""`` for none.""" + # circular import: chat_delivery imports this module at load. + from kiro_crew.dashboard.chat_delivery import TURN_ACTOR_META_KEY + + meta = item.get("meta") + return meta.get(TURN_ACTOR_META_KEY, "") if isinstance(meta, dict) else "" + + def _dequeue_next_message(slot, merge_enabled: bool) -> tuple: """Drain the queue: merge non-cron messages or pop the first one. A merge run stops at a system injection, at an attachment-bearing entry - (see :func:`carries_attachments`) and at a possibly-delivered steer - (``STEER_POSSIBLY_DELIVERED_META``); either of the last two at the head of - the queue pops alone. + (see :func:`carries_attachments`), at a possibly-delivered steer + (``STEER_POSSIBLY_DELIVERED_META``) and where the stamped turn actor + changes, so an app's queued send never folds into the user's own words; an + entry that starts no run pops alone. """ if merge_enabled and len(slot._queue) > 1: to_merge: list[dict] = [] @@ -4002,6 +4021,8 @@ def _dequeue_next_message(slot, merge_enabled: bool) -> tuple: or (item.get("meta") or {}).get(STEER_POSSIBLY_DELIVERED_META) ): break + if to_merge and _stamped_turn_actor(item) != _stamped_turn_actor(to_merge[0]): + break to_merge.append(item) if len(to_merge) > 1: del slot._queue[: len(to_merge)] diff --git a/src/kiro_crew/dashboard/slot_persistence/restored_metadata.py b/src/kiro_crew/dashboard/slot_persistence/restored_metadata.py index b6e2d95eb605..f2f56a730965 100644 --- a/src/kiro_crew/dashboard/slot_persistence/restored_metadata.py +++ b/src/kiro_crew/dashboard/slot_persistence/restored_metadata.py @@ -18,7 +18,11 @@ from typing import TYPE_CHECKING from kiro_crew.config.loader import AUTOCOMPACT_PCT_MAX, AUTOCOMPACT_PCT_MIN -from kiro_crew.dashboard.chat_title import _TITLE_ORIGINS, _rehydrated_refresh_mark +from kiro_crew.dashboard.chat_title import ( + _TITLE_ORIGINS, + _counts_as_user_turn, + _rehydrated_refresh_mark, +) from kiro_crew.dashboard.state import _MAX_DISMISSED_SOURCE_LINKS if TYPE_CHECKING: @@ -96,14 +100,15 @@ def _rebase_rehydrated_refresh_mark(slot: _ChatSlot) -> None: The window is the latest 500 rows, so the slot's user count restarts below the count the persisted mark was taken at, and the opt-in refresh cadence (``dashboard.title_refresh_every_turns``) would otherwise stay silent until - the count climbed past that mark again. Counts user rows over - ``slot.messages`` exactly as ``maybe_refresh_title`` does, so the two agree - on what a turn is. See ``chat_title._rehydrated_refresh_mark`` for the - floor that keeps a spent built-in milestone spent. + the count climbed past that mark again. Counts user turns over + ``slot.messages`` with ``maybe_refresh_title``'s own predicate + (``chat_title._counts_as_user_turn``), so the two agree on what a turn is. + See ``chat_title._rehydrated_refresh_mark`` for the floor that keeps a spent + built-in milestone spent. """ if not slot._title_refresh_mark: return - user_count = sum(1 for m in slot.messages if m.get("role") == "user") + user_count = sum(1 for m in slot.messages if _counts_as_user_turn(slot, m)) slot._title_refresh_mark = _rehydrated_refresh_mark(slot._title_refresh_mark, user_count) diff --git a/test/test_active_turn_session_key.py b/test/test_active_turn_session_key.py index 70a6baf55d75..5d07744034c1 100644 --- a/test/test_active_turn_session_key.py +++ b/test/test_active_turn_session_key.py @@ -217,7 +217,7 @@ async def test_the_clear_lands_before_a_successor_can_start( slot.queue_append("second message") observed: dict[str, str] = {} - async def _fake_start(st, sl) -> bool: + async def _fake_start(st, sl, **_kwargs) -> bool: observed["at_dispatch"] = sl._active_turn_session_key # Stand in for the successor publishing its own identity. sl._active_turn_session_key = "dashboard:successor" diff --git a/test/test_chat_mode_security.py b/test/test_chat_mode_security.py index c4856e2e172d..31bcd1c0d774 100644 --- a/test/test_chat_mode_security.py +++ b/test/test_chat_mode_security.py @@ -21,23 +21,53 @@ from __future__ import annotations +import ast import asyncio +import contextlib +import inspect import json import threading -from unittest.mock import MagicMock, patch +from operator import attrgetter +from typing import NamedTuple +from unittest.mock import ANY, AsyncMock, MagicMock, patch +import aiohttp import pytest from aiohttp import web from aiohttp.test_utils import TestClient, TestServer from chat_test_helpers import _make_state +from kiro_crew.acp.types import EVENT_COMPLETE, EVENT_TEXT_CHUNK +from kiro_crew.config.loader import KiroCrewConfig +from kiro_crew.dashboard import chat_persistence, chat_runner, session_control +from kiro_crew.dashboard.chat_delivery import TURN_ACTOR_META_KEY, queue_for_next_turn from kiro_crew.dashboard.chat_handlers import ( _app_may_send_to_slot, + api_chat, api_chat_mode, api_chat_slot_approve, ) +from kiro_crew.dashboard.chat_title import ( + _counts_as_user_turn, + _maybe_auto_title, + _rehydrated_refresh_mark, + maybe_refresh_title, +) +from kiro_crew.dashboard.chat_utils import ( + CRON_NOTIFICATION_KIND, + CRON_NOTIFY_PREFIX, + MCP_APP_MESSAGE_KIND, + SYNTHETIC_RECOVERY_KIND, + TURN_END_WIRE_CLS, + _dequeue_next_message, +) from kiro_crew.dashboard.handlers.sessions import api_approval_resolve +from kiro_crew.dashboard.slot_queue_repository import ( + durable_queue_entries, + sanitize_restored_queue, +) from kiro_crew.dashboard.state import SlotOrigin, row_mid +from kiro_crew.providers.base import LLMEvent from kiro_crew.safety_override import ( reset_singleton, ) @@ -74,6 +104,7 @@ async def _app_request(request: web.Request, handler): def _make_app_token_mode_app(state) -> web.Application: app = web.Application(middlewares=[_app_request]) app["state"] = state + app.router.add_post("/api/chat", api_chat) app.router.add_post("/api/chat/mode", api_chat_mode) app.router.add_post("/api/chat/slots/{slot}/approve", api_chat_slot_approve) return app @@ -244,6 +275,951 @@ async def test_app_without_session_approval_grant_is_denied(state) -> None: assert state._slots["s1"]._trust is False +# ── app send to a user slot: a turn, never the slot's settings ── + +_CONSENT_SHA = "a" * 64 +_THEME_FIELDS = { + "color_theme": "custom-pack", + "theme_consent": True, + "theme_consent_sha": _CONSENT_SHA, +} +_GRANT_CHECK = "kiro_crew.apps.permissions.app_can_manage_session_approvals" +#: The fields a send on a session the app does not own must leave as it found them. +_settings = attrgetter("agent", "color_theme", "theme_consent", "theme_consent_sha") + + +def _user_slot(state, *, agent: str = ""): + slot = state.get_or_create_slot("s1", origin=SlotOrigin.USER) + slot.agent = agent + slot.color_theme = "custom-mine" + slot.theme_consent = True + slot.theme_consent_sha = "b" * 64 + return slot + + +def _own_slot(state): + return state.get_or_create_slot("s1", app="crew-keyboard") + + +def _user_rows(slot) -> list[dict]: + return [m for m in slot.messages if m.get("role") == "user"] + + +class _Sent(NamedTuple): + status: int + data: dict + run_chat: AsyncMock + title: AsyncMock + grant_check: MagicMock + + +async def _app_send(state, body: dict, *, granted: bool = True) -> _Sent: + """POST /api/chat?ws=1 as the app ``crew-keyboard``.""" + run_chat = AsyncMock() + title = AsyncMock() + grant_check = MagicMock(return_value=granted) + with ( + patch(_GRANT_CHECK, grant_check), + patch("kiro_crew.dashboard.chat_handlers._run_chat", new=run_chat), + patch("kiro_crew.dashboard.chat_handlers._maybe_auto_title", new=title), + ): + async with _app_client(state) as client: + resp = await client.post("/api/chat?ws=1", json={"message": "hi", **body}) + return _Sent(resp.status, await resp.json(), run_chat, title, grant_check) + + +def _assert_refused(audit: MagicMock, trigger: str) -> None: + audit.log_api_access.assert_any_call( + caller="crew-keyboard", + operation="chat_send", + outcome="denied", + source="app_isolation", + resources=f"slot=s1 {trigger}", + error=ANY, + ) + outcomes = [c.kwargs.get("outcome") for c in audit.log_api_access.call_args_list] + assert "allowed" not in outcomes + + +@pytest.mark.parametrize( + ("slot_agent", "body", "trigger"), + [ + pytest.param("", {"agent": "researcher"}, "agent=researcher", id="agent"), + # The configured default is a binding like any other, not a no-op. + pytest.param("", {"agent": "default"}, "agent=default", id="default-agent"), + pytest.param("", _THEME_FIELDS, "field=color_theme", id="theme"), + pytest.param("", {"color_theme": ""}, "field=color_theme", id="theme-clear"), + pytest.param("researcher", _THEME_FIELDS, "field=color_theme", id="theme-agent-bound"), + pytest.param("", {"agent": "researcher", **_THEME_FIELDS}, "agent=researcher", id="both"), + ], +) +@pytest.mark.asyncio +async def test_app_on_user_slot_cannot_change_its_settings( + state, slot_agent: str, body: dict, trigger: str +) -> None: + slot = _user_slot(state, agent=slot_agent) + before = _settings(slot) + audit = MagicMock() + + with patch("kiro_crew.dashboard.chat_handlers.sel", return_value=audit): + sent = await _app_send(state, {"slot": "s1", **body}) + + assert sent.status == 403 + assert sent.data["code"] == "app_session_settings_forbidden" + sent.run_chat.assert_not_called() + assert _settings(slot) == before + assert _user_rows(slot) == [] + _assert_refused(audit, trigger) + + +@pytest.mark.parametrize( + "body", [pytest.param({}, id="plain"), pytest.param({"agent": ""}, id="empty-agent")] +) +@pytest.mark.asyncio +async def test_app_on_agentless_user_slot_sends_a_turn(state, body: dict) -> None: + slot = _user_slot(state) + before = _settings(slot) + + sent = await _app_send(state, {"slot": "s1", **body}) + + assert sent.status == 200, sent.data + sent.run_chat.assert_called_once() + assert _settings(slot) == before + + +@pytest.mark.parametrize( + "body", + [pytest.param({}, id="plain"), pytest.param({"agent": "researcher"}, id="same-agent")], +) +@pytest.mark.asyncio +async def test_app_on_agent_bound_user_slot_sends_a_turn(state, body: dict) -> None: + slot = _user_slot(state, agent="researcher") + before = _settings(slot) + audit = MagicMock() + + with patch("kiro_crew.dashboard.chat_handlers.sel", return_value=audit): + sent = await _app_send(state, {"slot": "s1", **body}) + + assert sent.status == 200, sent.data + sent.run_chat.assert_called_once() + assert _settings(slot) == before + audit.log_api_access.assert_any_call( + caller="crew-keyboard", + operation="chat_send", + outcome="allowed", + source="app_isolation", + resources="permissions.sessionApproval|slot=s1", + ) + + +@pytest.mark.asyncio +async def test_app_on_its_own_slot_keeps_agent_and_theme_writes(state) -> None: + slot = _own_slot(state) + + sent = await _app_send( + state, {"slot": "s1", "agent": "researcher", **_THEME_FIELDS}, granted=False + ) + + assert sent.status == 200, sent.data + sent.run_chat.assert_called_once() + sent.grant_check.assert_not_called() + assert _settings(slot) == ("researcher", "custom-pack", True, _CONSENT_SHA) + + +#: Every request-body field ``api_chat`` reads, by what it can do to an EXISTING +#: user session the app reaches through the grant. A turn-only field shapes the +#: turn (``memory_mode`` / ``mode`` apply only to a slot the send creates, and an +#: app's send never creates a user slot). A settings-bearing field names a value +#: the slot keeps; the sample is one that would change ``_user_slot``. +_TURN_ONLY_BODY_KEYS = frozenset({"message", "slot", "meta", "steer", "memory_mode", "mode"}) +_SETTINGS_BODY_KEYS: dict[str, object] = { + "agent": "researcher", + "color_theme": "custom-pack", + "theme_consent": False, + "theme_consent_sha": _CONSENT_SHA, +} + + +def _body_keys_read(func, name: str, functions: dict) -> set[str]: + """Keys *func* reads off its parameter *name*, following module helpers it hands it to.""" + keys: set[str] = set() + for node in ast.walk(func): + if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute): + target = node.func.value + if isinstance(target, ast.Name) and target.id == name and node.func.attr == "get": + first = node.args[0] + assert isinstance(first, ast.Constant), ast.unparse(node) + keys.add(first.value) + elif isinstance(node, ast.Subscript): + if isinstance(node.value, ast.Name) and node.value.id == name: + assert isinstance(node.slice, ast.Constant), ast.unparse(node) + keys.add(node.slice.value) + elif isinstance(node, ast.Compare) and isinstance(node.left, ast.Constant): + for op, right in zip(node.ops, node.comparators): + if isinstance(op, (ast.In, ast.NotIn)) and isinstance(right, ast.Name): + if right.id == name: + keys.add(node.left.value) + if isinstance(node, ast.Call) and isinstance(node.func, ast.Name): + helper = functions.get(node.func.id) + for index, arg in enumerate(node.args): + if helper is not None and isinstance(arg, ast.Name) and arg.id == name: + keys |= _body_keys_read(helper, helper.args.args[index].arg, functions) + return keys + + +def test_every_api_chat_body_key_is_classified() -> None: + """A new body field fails here until someone says what it can change. + + Classifying it settings-bearing puts it under + ``test_settings_bearing_body_keys_never_reach_a_user_slot``. + """ + from kiro_crew.dashboard import chat_handlers + + tree = ast.parse(inspect.getsource(chat_handlers)) + functions = { + node.name: node + for node in tree.body + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) + } + read = _body_keys_read(functions["api_chat"], "body", functions) + assert not _TURN_ONLY_BODY_KEYS & _SETTINGS_BODY_KEYS.keys() + assert read == _TURN_ONLY_BODY_KEYS | _SETTINGS_BODY_KEYS.keys() + + +@pytest.mark.parametrize("key", sorted(_SETTINGS_BODY_KEYS)) +@pytest.mark.asyncio +async def test_settings_bearing_body_keys_never_reach_a_user_slot(state, key: str) -> None: + slot = _user_slot(state) + before = _settings(slot) + + sent = await _app_send(state, {"slot": "s1", key: _SETTINGS_BODY_KEYS[key]}) + + assert sent.status in (200, 403), sent.data + assert _settings(slot) == before + + +# ── harness slash commands ── + + +@pytest.mark.parametrize("message", ["/agent researcher", "/clear", "/goal ship the release"]) +@pytest.mark.asyncio +async def test_app_on_user_slot_cannot_run_a_harness_slash_command(state, message: str) -> None: + slot = _user_slot(state, agent="researcher") + audit = MagicMock() + + with patch("kiro_crew.dashboard.chat_handlers.sel", return_value=audit): + sent = await _app_send(state, {"slot": "s1", "message": message}) + + assert sent.status == 403 + assert sent.data["code"] == "app_session_settings_forbidden" + sent.run_chat.assert_not_called() + assert _user_rows(slot) == [] + _assert_refused(audit, f"command={message.split()[0]}") + + +@pytest.mark.asyncio +async def test_app_slash_command_is_refused_before_the_queue(state) -> None: + slot = _user_slot(state, agent="researcher") + busy = MagicMock() + busy.done.return_value = False + slot.task = busy + + sent = await _app_send(state, {"slot": "s1", "message": "/clear"}) + + assert sent.status == 403 + assert slot.queue_depth == 0 + + +@pytest.mark.parametrize("message", ["/agent researcher", "/clear", "/goal ship the release"]) +@pytest.mark.asyncio +async def test_app_on_its_own_slot_runs_slash_commands(state, message: str) -> None: + _own_slot(state) + + sent = await _app_send(state, {"slot": "s1", "message": message}) + + assert sent.status == 200, sent.data + sent.run_chat.assert_called_once() + + +@pytest.mark.parametrize("message", ["please /clear the board", "/tmp/notes.txt is empty"]) +@pytest.mark.asyncio +async def test_app_text_that_is_not_a_harness_command_is_a_plain_send(state, message: str) -> None: + _user_slot(state, agent="researcher") + + sent = await _app_send(state, {"slot": "s1", "message": message}) + + assert sent.status == 200, sent.data + sent.run_chat.assert_called_once() + + +# ── steer, row id, echo, title ── + + +@pytest.mark.asyncio +async def test_app_on_user_slot_cannot_steer_past_running_subagents(state) -> None: + slot = _user_slot(state, agent="researcher") + state.subagents = MagicMock() + state.subagents.running_agents_for.return_value = ["child"] + + sent = await _app_send(state, {"slot": "s1", "steer": True}) + + assert sent.status == 200, sent.data + assert sent.data["queued"] is True + sent.run_chat.assert_not_called() + assert slot.queue_depth == 1 + + +@pytest.mark.asyncio +async def test_app_on_its_own_slot_keeps_the_steer_opt_out(state) -> None: + _own_slot(state) + state.subagents = MagicMock() + state.subagents.running_agents_for.return_value = ["child"] + + sent = await _app_send(state, {"slot": "s1", "steer": True}) + + assert sent.status == 200, sent.data + sent.run_chat.assert_called_once() + + +@pytest.mark.parametrize( + "mid", + [ + pytest.param("forged-mid", id="string"), + pytest.param(123, id="int"), + pytest.param(["forged"], id="list"), + ], +) +@pytest.mark.asyncio +async def test_app_on_user_slot_cannot_choose_the_row_id(state, mid) -> None: + slot = _user_slot(state, agent="researcher") + + sent = await _app_send(state, {"slot": "s1", "meta": {"mid": mid, "sendId": "s-1"}}) + + assert sent.status == 200, sent.data + [row] = _user_rows(slot) + minted = row_mid(row) + assert isinstance(minted, str) and minted and minted != mid + assert sent.data["mid"] == minted + + +def _user_echoes(state) -> list[dict]: + return [ + call.args[1] + for call in state.broadcast_ws.call_args_list + if call.args[0] == "chat_message" and call.args[1].get("role") == "user" + ] + + +@pytest.mark.asyncio +async def test_app_turn_on_user_slot_reaches_the_users_open_tabs(state) -> None: + _user_slot(state, agent="researcher") + + sent = await _app_send(state, {"slot": "s1", "message": "from the app"}) + + assert sent.status == 200, sent.data + assert [frame["content"] for frame in _user_echoes(state)] == ["from the app"] + + +@pytest.mark.asyncio +async def test_app_turn_on_its_own_slot_keeps_the_correlated_echo(state) -> None: + _own_slot(state) + + sent = await _app_send(state, {"slot": "s1", "message": "from the app"}) + + assert sent.status == 200, sent.data + assert _user_echoes(state) == [] + + +@pytest.mark.asyncio +async def test_app_turn_on_user_slot_starts_no_auto_title(state) -> None: + slot = _user_slot(state, agent="researcher") + + sent = await _app_send(state, {"slot": "s1"}) + + assert sent.status == 200, sent.data + sent.title.assert_not_called() + [row] = _user_rows(slot) + assert row["meta"][TURN_ACTOR_META_KEY] == "app" + + +@pytest.mark.asyncio +async def test_app_turn_on_its_own_slot_still_titles(state) -> None: + _own_slot(state) + + sent = await _app_send(state, {"slot": "s1"}) + + assert sent.status == 200, sent.data + sent.title.assert_called_once() + + +def test_title_counts_an_app_row_only_on_the_apps_own_slot(state) -> None: + app_row = {"role": "user", "content": "x", "meta": {TURN_ACTOR_META_KEY: "app"}} + user_row = {"role": "user", "content": "y"} + user_slot = _user_slot(state) + own = state.get_or_create_slot("s2", app="crew-keyboard") + + assert not _counts_as_user_turn(user_slot, app_row) + assert _counts_as_user_turn(user_slot, user_row) + assert _counts_as_user_turn(own, app_row) + + +@pytest.mark.asyncio +async def test_end_of_turn_title_ignores_an_apps_turn_on_a_user_slot(state) -> None: + slot = _user_slot(state, agent="researcher") + slot.append("user", "from the app", "msg msg-u", meta={TURN_ACTOR_META_KEY: "app"}) + slot.append("assistant", "reply") + generate = AsyncMock(return_value="An App Title") + + with patch("kiro_crew.dashboard.chat_title._generate_title_via_kiro", new=generate): + await _maybe_auto_title(state, slot) + + generate.assert_not_called() + assert not slot._titled + + +@pytest.mark.parametrize(("actor", "refreshed"), [("app", False), ("", True)]) +@pytest.mark.asyncio +async def test_title_refresh_counts_only_the_users_turns(state, actor: str, refreshed: bool): + slot = _user_slot(state, agent="researcher") + slot.title, slot._titled, slot._title_origin = "Old", True, "auto" + slot._title_low_signal = True # due at the first user turn + slot.append("user", "x", "msg msg-u", meta={TURN_ACTOR_META_KEY: actor} if actor else None) + generate = AsyncMock(return_value="") + + with ( + patch("kiro_crew.dashboard.chat_title._generate_refreshed_title", new=generate), + patch("kiro_crew.dashboard.chat_title._title_refresh_every", return_value=0), + patch("kiro_crew.dashboard.chat_title._persist_title", new=AsyncMock(return_value=True)), + ): + await maybe_refresh_title(state, slot) + + assert generate.called is refreshed + + +def _app_then_user_turns(slot) -> None: + slot.append("user", "Summarize ticket ABC-1", "msg msg-u", meta={TURN_ACTOR_META_KEY: "app"}) + slot.append("assistant", "app reply") + slot.append("user", "ok", "msg msg-u") + slot.append("assistant", "sure") + + +def _prompt_lines(generate: AsyncMock) -> list[str]: + return [m["content"] for m in generate.call_args.args[1]] + + +@pytest.mark.asyncio +async def test_the_title_fallback_never_takes_an_apps_text(state) -> None: + slot = _user_slot(state, agent="researcher") + _app_then_user_turns(slot) + generate = AsyncMock(return_value="") # the titler SKIPs + + with ( + patch("kiro_crew.dashboard.chat_title._generate_title_via_kiro", new=generate), + patch("kiro_crew.dashboard.chat_title._persist_title", new=AsyncMock(return_value=True)), + patch("kiro_crew.dashboard.chat_title.maybe_suggest_folder", new=AsyncMock()), + ): + await _maybe_auto_title(state, slot) + + assert _prompt_lines(generate) == ["ok", "sure"] + assert slot.title == "ok" + assert slot._titled + + +@pytest.mark.asyncio +async def test_the_reply_to_an_apps_turn_is_not_the_users_answered_turn(state) -> None: + # The user's first turn has no reply yet, so a SKIP must leave the fallback + # unlocked for the end-of-turn retry; the app turn's reply is not an answer. + slot = _user_slot(state, agent="researcher") + slot.append("user", "Reply with exactly: PLAN", "msg msg-u", meta={TURN_ACTOR_META_KEY: "app"}) + slot.append("assistant", "PLAN") + slot.append("user", "hi", "msg msg-u") + generate = AsyncMock(return_value="") + + with ( + patch("kiro_crew.dashboard.chat_title._generate_title_via_kiro", new=generate), + patch("kiro_crew.dashboard.chat_title._persist_title", new=AsyncMock(return_value=True)), + patch("kiro_crew.dashboard.chat_title.maybe_suggest_folder", new=AsyncMock()), + ): + await _maybe_auto_title(state, slot) + + assert _prompt_lines(generate) == ["hi"] + assert slot.title == "hi" + assert not slot._titled + + +@pytest.mark.asyncio +async def test_the_title_refresh_prompt_leaves_out_an_apps_turn(state) -> None: + slot = _user_slot(state, agent="researcher") + slot.title, slot._titled, slot._title_origin = "Old", True, "auto" + slot._title_low_signal = True + _app_then_user_turns(slot) + generate = AsyncMock(return_value="") + + with ( + patch("kiro_crew.dashboard.chat_title._generate_refreshed_title", new=generate), + patch("kiro_crew.dashboard.chat_title._title_refresh_every", return_value=0), + patch("kiro_crew.dashboard.chat_title._persist_title", new=AsyncMock(return_value=True)), + ): + await maybe_refresh_title(state, slot) + + assert _prompt_lines(generate) == ["ok", "sure"] + + +def test_a_merge_run_stops_where_the_turn_actor_changes(state) -> None: + slot = _user_slot(state) + queue_for_next_turn(state, slot, "ping", turn_actor="app") + slot.queue_append("Fix the login bug") + slot.queue_append("and the logout one") + + first, first_items = _dequeue_next_message(slot, merge_enabled=True) + second, second_items = _dequeue_next_message(slot, merge_enabled=True) + + assert (first, len(first_items)) == ("ping", 1) + assert second == "[2 queued messages merged]\n\nFix the login bug\n\nand the logout one" + assert len(second_items) == 2 + + +def test_a_rehydrated_refresh_mark_counts_turns_like_the_refresh(state) -> None: + slot = _user_slot(state, agent="researcher") + for n in range(3): + slot.append("user", f"mine {n}", "msg msg-u") + slot.append("user", f"app {n}", "msg msg-u", meta={TURN_ACTOR_META_KEY: "app"}) + slot._title_refresh_mark = 6 + + chat_persistence._rebase_rehydrated_refresh_mark(slot) + + assert slot._title_refresh_mark == _rehydrated_refresh_mark(6, 3) < 6 + + +# ── the grant re-checks the slot after its awaits ── + + +@pytest.mark.parametrize("closes", ["begin-close", "removed"]) +@pytest.mark.asyncio +async def test_app_send_refused_when_the_slot_closes_during_the_permission_read( + state, closes: str +) -> None: + slot = _user_slot(state, agent="researcher") + reading = threading.Event() + release = threading.Event() + + def gated_grant(_app: str) -> bool: + reading.set() + assert release.wait(5) + return True + + run_chat = AsyncMock() + with ( + patch(_GRANT_CHECK, gated_grant), + patch("kiro_crew.dashboard.chat_handlers._run_chat", new=run_chat), + patch("kiro_crew.dashboard.chat_handlers._maybe_auto_title", new=AsyncMock()), + ): + async with _app_client(state) as client: + send = asyncio.create_task( + client.post("/api/chat?ws=1", json={"slot": "s1", "message": "hi"}) + ) + assert await asyncio.to_thread(reading.wait, 5) + if closes == "begin-close": + slot.begin_close() + else: + state._slots.pop("s1") + release.set() + resp = await send + data = await resp.json() + + assert resp.status == 404 + assert data["code"] == "slot_not_found" + run_chat.assert_not_called() + assert _user_rows(slot) == [] + + +@pytest.mark.asyncio +async def test_app_send_refused_when_the_slot_is_relinked_during_the_command_read(state) -> None: + slot = _user_slot(state, agent="researcher") + reading = threading.Event() + release = threading.Event() + real_load = KiroCrewConfig.load + loads: list[None] = [] + + def gated_load(*args, **kwargs): + # Only the first read, `_send_harness_command`'s, is held. + loads.append(None) + if len(loads) == 1: + reading.set() + assert release.wait(5) + return real_load(*args, **kwargs) + + run_chat = AsyncMock() + audit = MagicMock() + with ( + patch(_GRANT_CHECK, return_value=True), + patch.object(KiroCrewConfig, "load", staticmethod(gated_load)), + patch("kiro_crew.dashboard.chat_handlers._run_chat", new=run_chat), + patch("kiro_crew.dashboard.chat_handlers._maybe_auto_title", new=AsyncMock()), + patch("kiro_crew.dashboard.chat_handlers.sel", return_value=audit), + ): + async with _app_client(state) as client: + send = asyncio.create_task( + client.post("/api/chat?ws=1", json={"slot": "s1", "message": "/tmp/a read it"}) + ) + assert await asyncio.to_thread(reading.wait, 5) + slot.linked_session_key = "cron:job-1" + release.set() + resp = await send + data = await resp.json() + + assert resp.status == 404 + assert data["code"] == "slot_not_found" + run_chat.assert_not_called() + assert _user_rows(slot) == [] + outcomes = [c.kwargs.get("outcome") for c in audit.log_api_access.call_args_list] + assert "allowed" not in outcomes + + +# ── an app's SSE stream on a user slot is its own turn ── + + +@pytest.mark.asyncio +async def test_app_sse_stream_stops_at_the_end_of_its_turn(state) -> None: + slot = _user_slot(state, agent="researcher") + state._broadcast = MagicMock() + + async def turn_then_queued_follow_up(_state, s, _message, **_kwargs): + s.append("assistant", "reply to the app") + s.push_wire_frame(TURN_END_WIRE_CLS, "") + # What the queue drain does next: the user's follow-up and its reply. + s.append("user", "the user's follow-up", "msg msg-u") + s.append("assistant", "reply to the user") + s.append("done", "", "done") + + with ( + patch(_GRANT_CHECK, return_value=True), + patch("kiro_crew.dashboard.chat_handlers._run_chat", new=turn_then_queued_follow_up), + patch("kiro_crew.dashboard.chat_handlers._maybe_auto_title", new=AsyncMock()), + ): + async with _app_client(state) as client: + resp = await client.post("/api/chat", json={"slot": "s1", "message": "hi"}) + stream = await resp.text() + + assert resp.status == 200 + assert "reply to the app" in stream + assert "follow-up" not in stream and "reply to the user" not in stream + assert stream.rstrip().endswith("data: [DONE]") + assert slot._has_reader is False + dashboard = [ + call.args[0]["content"] + for call in state._broadcast.call_args_list + if call.args[0].get("_type") == "chat_message" + ] + assert dashboard == ["reply to the app", "reply to the user"] + + +@pytest.mark.asyncio +async def test_app_sse_stream_skips_a_row_queued_for_a_later_turn(state) -> None: + _user_slot(state, agent="researcher") + state._broadcast = MagicMock() + cron = f'{CRON_NOTIFY_PREFIX}"job"]\nthe user\'s cron output\n[/Cron notification]' + + async def turn_with_a_cron_queued_meanwhile(_state, s, _message, **_kwargs): + s.append("assistant", "reply to the app") + # What a cron notifying a running slot does (handlers/messaging.py). + qid = s.queue_append(cron, kind=CRON_NOTIFICATION_KIND) + s.append("queued", cron, json.dumps({"cronLabel": "job", "queue_id": qid})) + s.append("assistant", "more of the app's turn") + s.append("done", "", "done") + + with ( + patch(_GRANT_CHECK, return_value=True), + patch("kiro_crew.dashboard.chat_handlers._run_chat", new=turn_with_a_cron_queued_meanwhile), + patch("kiro_crew.dashboard.chat_handlers._maybe_auto_title", new=AsyncMock()), + ): + async with _app_client(state) as client: + resp = await client.post("/api/chat", json={"slot": "s1", "message": "hi"}) + stream = await resp.text() + + assert "reply to the app" in stream and "more of the app's turn" in stream + assert "cron output" not in stream + dashboard = [ + call.args[0]["content"] + for call in state._broadcast.call_args_list + if call.args[0].get("_type") == "chat_message" + ] + assert cron in dashboard + + +@pytest.mark.asyncio +async def test_a_slot_owners_sse_stream_skips_the_turn_boundary(state) -> None: + _own_slot(state) + + async def two_turns(_state, s, _message, **_kwargs): + s.append("assistant", "first reply") + s.push_wire_frame(TURN_END_WIRE_CLS, "") + s.append("assistant", "second reply") + s.append("done", "", "done") + + with ( + patch("kiro_crew.dashboard.chat_handlers._run_chat", new=two_turns), + patch("kiro_crew.dashboard.chat_handlers._maybe_auto_title", new=AsyncMock()), + ): + async with _app_client(state) as client: + resp = await client.post("/api/chat", json={"slot": "s1", "message": "hi"}) + stream = await resp.text() + + assert "first reply" in stream and "second reply" in stream + assert TURN_END_WIRE_CLS not in stream + + +class _PrepareFails(web.StreamResponse): + async def prepare(self, request): + raise ConnectionResetError + + +@pytest.mark.asyncio +async def test_a_failed_sse_prepare_releases_the_reader(state) -> None: + slot = _own_slot(state) + + with ( + patch.object(web, "StreamResponse", _PrepareFails), + patch("kiro_crew.dashboard.chat_handlers._run_chat", new=AsyncMock()), + patch("kiro_crew.dashboard.chat_handlers._maybe_auto_title", new=AsyncMock()), + ): + async with _app_client(state) as client: + with contextlib.suppress(aiohttp.ClientError): + await client.post("/api/chat", json={"slot": "s1", "message": "hi"}) + + assert slot._has_reader is False + + +def _scripted_turns(state, monkeypatch, *turns) -> None: + """Drive the real ``_run_chat`` with one scripted provider stream per turn.""" + + async def _events(items): + for item in items: + yield item + + monkeypatch.setattr(session_control, "session_control_enabled", lambda: True) + monkeypatch.setattr(session_control, "sel", lambda: MagicMock()) + monkeypatch.setattr(session_control, "_sel_off_loop", lambda write, what: write()) + monkeypatch.setattr(chat_runner, "title_then_refresh", AsyncMock()) + monkeypatch.setattr(chat_runner, "generate_session_summary", AsyncMock()) + state.subagents = None + state.sessions.get_or_create = AsyncMock(return_value=(MagicMock(), False, False)) + state.sessions.release = MagicMock() + state.sessions.reset = AsyncMock() + state.sessions.set_approval_policy = MagicMock() + state.sessions.check_context_usage = MagicMock() + state.sessions.get_slack_link = MagicMock(return_value=(None, None)) + state.sessions.record_failure = AsyncMock() + state.is_yolo_active = MagicMock(return_value=False) + client = state.sessions.get_or_create.return_value[0] + client.shutdown = AsyncMock() + client.context_usage_pct = MagicMock(return_value=0.0) + client._client = client + client.last_prompt_stats = None + # A turn is its reply text; "" is a response that carries none. + scripts = iter( + [ + *([LLMEvent(kind=EVENT_TEXT_CHUNK, text=text)] if text else []), + LLMEvent(kind=EVENT_COMPLETE, stop_reason="end_turn"), + ] + for text in turns + ) + client.stream = MagicMock(side_effect=lambda *_a, **_k: _events(next(scripts))) + client.stream_command = client.stream + + +async def _run_app_turn_and_successors(state, slot) -> list[tuple[str, str]]: + await chat_runner._run_chat(state, slot, "from the app", _turn_actor="app") + for _ in range(5): + successor = slot.task + if successor is None or successor.done(): + break + await asyncio.wait_for(successor, timeout=10) + assert slot.task is None or slot.task.done() + return [(m["role"], m["content"]) for m in slot.drain()] + + +@pytest.mark.asyncio +async def test_the_drain_marks_the_turn_end_before_a_successor_turn(state, monkeypatch) -> None: + _scripted_turns(state, monkeypatch, "reply to the app", "reply to the user") + slot = _user_slot(state) + slot._titled = True + slot.queue_append("the user's follow-up", directive_user_origin=True) + + pending = await _run_app_turn_and_successors(state, slot) + + boundary = pending.index((TURN_END_WIRE_CLS, "")) + assert any("reply to the app" in content for _, content in pending[:boundary]) + assert ("user", "the user's follow-up") in pending[boundary:] + assert all("reply to the user" not in content for _, content in pending[:boundary]) + + +@pytest.mark.asyncio +async def test_an_empty_first_reply_is_retried_inside_the_apps_turn(state, monkeypatch) -> None: + # The first response is empty, so the runner re-queues the app's message + # (`_queue_recovery`); that retry is still the app's turn. + _scripted_turns(state, monkeypatch, "", "the real reply", "reply to the user") + slot = _user_slot(state) + slot._titled = True + slot.queue_append("the user's follow-up", directive_user_origin=True) + + pending = await _run_app_turn_and_successors(state, slot) + + # One where the app's turn ends, one where the user's follow-up ends the cycle. + assert pending.count((TURN_END_WIRE_CLS, "")) == 2 + boundary = pending.index((TURN_END_WIRE_CLS, "")) + assert any("the real reply" in content for _, content in pending[:boundary]) + assert ("user", "the user's follow-up") in pending[boundary:] + + +@pytest.mark.parametrize( + ("stamped", "predecessor", "recovery_id", "ending_id", "marked"), + [ + pytest.param("app", "app", "turn-a", "turn-a", False, id="own-retry"), + pytest.param("user", "app", "turn-a", "turn-a", True, id="another-actor"), + pytest.param("app", "", "turn-a", "turn-a", True, id="no-ending-actor"), + pytest.param("app", "app", "turn-a", "turn-b", True, id="older-app-retry"), + pytest.param("app", "app", "", "turn-a", True, id="missing-recovery-identity"), + pytest.param("app", "app", "turn-a", "", True, id="missing-ending-identity"), + ], +) +@pytest.mark.asyncio +async def test_only_the_ending_turns_own_recovery_continues_its_turn( + state, stamped: str, predecessor: str, recovery_id: str, ending_id: str, marked: bool +) -> None: + slot = _user_slot(state) + meta = {TURN_ACTOR_META_KEY: stamped} + if recovery_id: + meta[chat_runner._RECOVERY_TURN_META_KEY] = recovery_id + slot.queue_insert(0, "retry", kind=SYNTHETIC_RECOVERY_KIND, meta=meta) + + await _drain_once(state, slot, predecessor_actor=predecessor, predecessor_turn_id=ending_id) + + assert ((TURN_END_WIRE_CLS, "") in [(m["cls"], m["content"]) for m in slot.drain()]) is marked + + +def _held_note(slot, text: str) -> None: + slot._deferred_notes.append( + {"id": "n1", "content": text, "cls": "reconcile-note", "context": None, "session": None} + ) + + +@pytest.mark.asyncio +async def test_a_held_note_and_a_queued_follow_up_land_after_the_turn_end(state) -> None: + slot = _user_slot(state) + slot.drain() + _held_note(slot, "a note for the user") + slot.queue_append("the user's follow-up", directive_user_origin=True) + + await _drain_once(state, slot, predecessor_actor="app") + + pending = [(m["cls"], m["content"]) for m in slot.drain()] + boundary = pending.index((TURN_END_WIRE_CLS, "")) + assert boundary == 0 + assert ("reconcile-note", "a note for the user") in pending[boundary:] + assert any(content == "the user's follow-up" for _, content in pending[boundary:]) + + +@pytest.mark.asyncio +async def test_the_cycle_end_marks_the_turn_end_before_a_held_note(state) -> None: + slot = _user_slot(state) + slot.drain() + _held_note(slot, "a note for the user") + + await chat_runner._finish_queue_cycle(state, slot) + + assert [(m["cls"], m["content"]) for m in slot.drain()] == [ + (TURN_END_WIRE_CLS, ""), + ("reconcile-note", "a note for the user"), + ("done", ""), + ] + + +@pytest.mark.asyncio +async def test_a_synthesis_successor_is_a_new_turn(state) -> None: + slot = _user_slot(state) + slot._pending_synthesis = True + # Every fire-gate probe set: a bare MagicMock answers an unset one with a + # truthy mock, which reads as children still waiting. + state.subagents = MagicMock( + running_agents_for=MagicMock(return_value=[]), + has_in_memory_pending_work_for=MagicMock(return_value=False), + queued_count_for_async=AsyncMock(return_value=0), + queued_count_or_none_async=AsyncMock(return_value=0), + ) + + with patch.object(chat_runner, "_run_pending_synthesis", new=AsyncMock()): + await chat_runner._finish_queue_cycle(state, slot) + await asyncio.wait_for(slot.task, timeout=10) + + assert [m["cls"] for m in slot.drain()] == [TURN_END_WIRE_CLS] + + +# ── a queued app entry is never a cron or sub-agent event ── + +_CRON_LOOKALIKE = '[Cron notification from "Nightly backup"] all done' + + +def _spawn_closing_the_turn(_state, _slot, turn, *_args, **_kwargs) -> MagicMock: + """A ``spawn_guarded_turn`` stand-in that closes the turn it is never going to run.""" + if inspect.iscoroutine(turn): + turn.close() + return MagicMock() + + +async def _drain_once(state, slot, **kwargs) -> dict: + with ( + patch.object(chat_runner, "spawn_guarded_turn", side_effect=_spawn_closing_the_turn), + patch.object(chat_runner, "_run_chat", new=MagicMock()), + ): + assert await chat_runner._start_next_queued_turn(state, slot, **kwargs) is True + return slot.messages[-1] + + +@pytest.mark.asyncio +async def test_a_queued_mcp_app_message_is_an_app_inject_whatever_its_text(state) -> None: + slot = state.get_or_create_slot("s1", origin=SlotOrigin.USER) + slot.queue_append(_CRON_LOOKALIKE, kind=MCP_APP_MESSAGE_KIND, meta={"appLabel": "Keys"}) + + row = await _drain_once(state, slot) + + assert row["role"] == "inject" + assert row["meta"]["injectKind"] == "mcp_app" + assert row["meta"]["appLabel"] == "Keys" + assert "cronLabel" not in row["meta"] + assert "cronLabel" not in row["cls"] + + +@pytest.mark.asyncio +async def test_a_queued_app_send_is_never_a_cron_notification(state) -> None: + slot = state.get_or_create_slot("s1", origin=SlotOrigin.USER) + queue_for_next_turn(state, slot, _CRON_LOOKALIKE, turn_actor="app") + + row = await _drain_once(state, slot) + + # The row an immediate app send writes: a user row, not a cron inject. + assert row["role"] == "user" + assert "injectKind" not in row["meta"] + assert "cronLabel" not in row["meta"] + assert "cronLabel" not in row["cls"] + + +@pytest.mark.asyncio +async def test_a_restored_queue_entry_is_never_a_cron_notification(state) -> None: + # A restart drops the actor stamp, so a restored app send keeps only its text. + live = state.get_or_create_slot("s0", origin=SlotOrigin.USER) + queue_for_next_turn(state, live, _CRON_LOOKALIKE, turn_actor="app") + slot = state.get_or_create_slot("s1", origin=SlotOrigin.USER) + slot._queue = sanitize_restored_queue(durable_queue_entries(live._queue)) + assert slot._queue, "a plain queued send must survive the restart" + + row = await _drain_once(state, slot) + + assert row["role"] == "user" + assert "injectKind" not in (row.get("meta") or {}) + assert "cronLabel" not in row["cls"] + + @pytest.mark.parametrize( ("mode", "expected_trust", "expected_trust_reads"), [ @@ -1159,3 +2135,150 @@ async def test_valid_normal_mode_touches_the_real_singleton(state) -> None: resp = await client.post("/api/chat/mode", json={"mode": "normal"}) assert resp.status == 200 assert real_safety_override().is_active() is False + + +@pytest.mark.asyncio +async def test_a_held_app_recovery_cannot_extend_a_later_apps_stream(state, monkeypatch) -> None: + _scripted_turns(state, monkeypatch, "", "later app reply", "older recovered reply") + slot = _user_slot(state) + slot._titled = True + # The first turn queues a real recovery, but it cannot drain until later. + with patch.object(chat_runner, "_start_next_queued_turn", new=AsyncMock(return_value=False)): + await chat_runner._run_chat(state, slot, "older app request", _turn_actor="app") + [recovery] = slot._queue + assert recovery["meta"][TURN_ACTOR_META_KEY] == "app" + assert recovery["meta"][chat_runner._RECOVERY_TURN_META_KEY] + slot.drain() + + pending = await _run_app_turn_and_successors(state, slot) + + boundary = pending.index((TURN_END_WIRE_CLS, "")) + assert any("later app reply" in content for _, content in pending[:boundary]) + assert any("older recovered reply" in content for _, content in pending[boundary:]) + assert all("older recovered reply" not in content for _, content in pending[:boundary]) + + +@pytest.mark.asyncio +async def test_restored_recovery_identity_cannot_continue_a_live_stream(state) -> None: + from kiro_crew.dashboard.slot_queue_repository import RESTORED_QUEUE_KEY + + slot = _user_slot(state) + slot.queue_insert( + 0, + "retry", + kind=SYNTHETIC_RECOVERY_KIND, + meta={TURN_ACTOR_META_KEY: "app", chat_runner._RECOVERY_TURN_META_KEY: "turn-a"}, + ) + slot._queue[0][RESTORED_QUEUE_KEY] = True + + await _drain_once(state, slot, predecessor_actor="app", predecessor_turn_id="turn-a") + + assert slot.drain()[0]["cls"] == TURN_END_WIRE_CLS + + +@pytest.mark.parametrize("owned", [False, True]) +@pytest.mark.asyncio +async def test_restored_app_turn_titles_only_an_app_owned_slot(state, owned: bool) -> None: + live = state.get_or_create_slot("s0", origin=SlotOrigin.USER) + queue_for_next_turn(state, live, "restored app request", turn_actor="app") + slot = _user_slot(state) + slot._queue = sanitize_restored_queue(durable_queue_entries(live._queue)) + assert TURN_ACTOR_META_KEY not in slot._queue[0].get("meta", {}) + row = await _drain_once(state, slot) + # Exercise the titler's owner exemption independently of queue admission: + # an app-bound restore may itself be held by containment revalidation. + slot._app = "crew-keyboard" if owned else "" + slot.append("assistant", "restored app reply") + assert TURN_ACTOR_META_KEY not in row["meta"] + assert _counts_as_user_turn(slot, row) is owned + generate = AsyncMock(return_value="") + + with ( + patch("kiro_crew.dashboard.chat_title._generate_title_via_kiro", new=generate), + patch("kiro_crew.dashboard.chat_title._persist_title", new=AsyncMock(return_value=True)), + patch("kiro_crew.dashboard.chat_title.maybe_suggest_folder", new=AsyncMock()), + ): + await _maybe_auto_title(state, slot) + + assert generate.called is owned + assert slot._titled is owned + if owned: + assert _prompt_lines(generate) == ["restored app request", "restored app reply"] + assert slot.title == "restored app request" + else: + assert slot.title != "restored app request" + + +@pytest.mark.parametrize("restored_first", [False, True]) +@pytest.mark.asyncio +async def test_restored_and_fresh_queue_rows_never_merge(state, restored_first: bool) -> None: + from kiro_crew.dashboard.chat_title import _titling_messages + + slot = _user_slot(state) + restored = sanitize_restored_queue([{"id": "old", "content": "restored app request"}]) + slot.queue_append("fresh user request", directive_user_origin=True) + slot._queue = restored + slot._queue if restored_first else slot._queue + restored + config = KiroCrewConfig() + config.dashboard.merge_queued_messages = True + with patch.object(KiroCrewConfig, "load", return_value=config): + first = await _drain_once(state, slot) + slot.append("assistant", "first reply") + assert slot.queue_depth == 1 + second = await _drain_once(state, slot) + slot.append("assistant", "second reply") + assert slot.queue_depth == 0 + fresh, restored_row = (second, first) if restored_first else (first, second) + assert fresh["content"] == "fresh user request" + assert restored_row["content"] == "restored app request" + assert _counts_as_user_turn(slot, fresh) + assert not _counts_as_user_turn(slot, restored_row) + assert [row["content"] for row in _titling_messages(slot)] == [ + "fresh user request", + "second reply" if restored_first else "first reply", + ] + # Keep the count above the fixed-milestone floor, so counting the restored + # row incorrectly changes the rebase result instead of hiding under it. + slot.append("user", "another user request", "msg msg-u") + slot.append("user", "one more user request", "msg msg-u") + # A transcript reload sees the same persisted meta and uses the same count. + slot.messages = json.loads(json.dumps(slot.messages)) + slot._title_refresh_mark = 6 + chat_persistence._rebase_rehydrated_refresh_mark(slot) + assert slot._title_refresh_mark == _rehydrated_refresh_mark(6, 3) + + +@pytest.mark.parametrize("successor", ["human", "app", "missing-mid"]) +@pytest.mark.asyncio +async def test_app_sse_backstop_rejects_a_foreign_user_row_without_turn_end( + state, successor: str +) -> None: + slot = _user_slot(state) + + async def without_boundary(_state, s, _message, **_kwargs): + # The handler normally drains its opening row before dispatch. Redeliver + # that exact row to prove the reader recognizes its own minted mid. + s._pending.append(_user_rows(s)[-1]) + s.append("assistant", "own reply") + # No turn_end: the reader must defend its scope independently. + meta = {TURN_ACTOR_META_KEY: "app"} if successor == "app" else None + row = s.append("user", "private successor request", "msg msg-u", meta=meta) + if successor == "missing-mid": + row["meta"].pop("mid") + s.append("assistant", "private successor reply") + s.append("done", "", "done") + + with ( + patch(_GRANT_CHECK, return_value=True), + patch("kiro_crew.dashboard.chat_handlers._run_chat", new=without_boundary), + patch("kiro_crew.dashboard.chat_handlers._maybe_auto_title", new=AsyncMock()), + ): + async with _app_client(state) as client: + resp = await client.post("/api/chat", json={"slot": "s1", "message": "own request"}) + stream = await asyncio.wait_for(resp.text(), timeout=5) + + assert resp.status == 200 + assert "own request" in stream and "own reply" in stream + assert "private successor" not in stream + assert stream.rstrip().endswith("data: [DONE]") + assert slot._has_reader is False + assert any(row["content"] == "private successor reply" for row in slot.messages) diff --git a/test/test_dashboard_chat.py b/test/test_dashboard_chat.py index 9b1870158fab..05ea74fd2915 100644 --- a/test/test_dashboard_chat.py +++ b/test/test_dashboard_chat.py @@ -12248,7 +12248,7 @@ async def _raise_dead(msg): # Keep the requeued entry IN the queue: the post-turn drain would # otherwise dequeue and spawn it immediately, racing the assertions. - async def _no_drain(_state, _slot) -> bool: + async def _no_drain(_state, _slot, **_kwargs) -> bool: return False monkeypatch.setattr("kiro_crew.dashboard.chat_runner._start_next_queued_turn", _no_drain) diff --git a/test/test_steer_requeue.py b/test/test_steer_requeue.py index 8612e6714724..fa20a40b1d55 100644 --- a/test/test_steer_requeue.py +++ b/test/test_steer_requeue.py @@ -471,7 +471,7 @@ def test_finally_calls_requeue_before_queue_drain(self): src = self._runner_source() requeue_at = src.index("_requeue_unconsumed_steers(state, slot)") drain_at = src.index( - "next_turn_started = await _start_next_queued_turn(state, slot)", + "next_turn_started = await _start_next_queued_turn(", requeue_at, ) assert requeue_at < drain_at, (