Skip to content

fix(tui): improve live guidance and controls - #1243

Merged
XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/streamline-live-steering
Nov 9, 2026
Merged

XuPeng-SH merged 9 commits into
matrixorigin:mainfrom
XuPeng-SH:fix/streamline-live-steering

Conversation

@XuPeng-SH

@XuPeng-SH XuPeng-SH commented Nov 8, 2026 •

Copy link
Copy Markdown
Collaborator

Capability assessment: Updated: Users can guide an active conversation or child, request a model or permission change, and inspect live child output without interrupting already-running work.

Summary

  • Deliver active-turn guidance in order through the existing run control, and preserve unsent, returned, or unconfirmed messages with their original session. If the primary stream closes before an accepted message's disposition arrives, do one exact status lookup; never automatically resend an unconfirmed message. Recovered applied messages retain the server's order and content in local turn history.
  • Apply a requested model at a model-round boundary. Install the model before confirming it, keep child-tool visibility on the confirmed model, and stop rather than dispatch an unconfirmed selection. Preserve public tool history across model changes while keeping provider-private continuation bound to its originating route.
  • Allow /plan during a running task. Release the current foreground wait at the user's gesture, request Plan mode, and send the planning instruction only after its exact permission application is acknowledged. Preserve the original command for editing if it was not delivered; ordinary escaped slash input remains ordinary input.
  • Update child Ctrl+G live tool output incrementally when existing history is unchanged. Keep the full identity-aware projection for filters, selections, and genuine canonical conflicts.
  • Reuse the existing fenced settings and event mechanisms. Ordinary Run stream attachment reads its admission and requested tail instead of hydrating the entire history; no per-message primary SSE observer or new per-round settings query is introduced.

Related to #1234.

Validation

  • Current candidate: 2,136 CLI/TUI and guidance/settlement tests passed; one pre-existing test was ignored. Nine real PTY journeys against a mock server passed, including active Bash to /plan, permission gating, ordered guidance, one-shot reconciliation and local history before the next turn.
  • Runtime: 19 model-routing tests, 11 settings-boundary tests, and 21 live-attach/final-wire tests passed. An isolated MatrixOne 4.2.8 settings test passed with concurrent model and permission requests and durable application.
  • Nightly ThreadSanitizer: 84 CLI guidance/plan/transcript tests and 30 runtime model/settings tests passed. Formatting and incremental clippy for CLI, runtime and services passed.
  • Earlier checkpoint c0956318c passed the full CI runtime profile and the DeepSeek-v4.1-flash CI harness (19/19). Those results do not certify this new head; new CI is reported separately.
  • The complete candidate received an independent gpt-6.1-terra / max design and quality review; remaining validation and capacity limits are below.

Limits

No 1,000-client distributed load test has been completed. The existing active-run control watcher still polls, and cross-server replay still queries durable state. An old cursor can request a large replay, and Explain attachments still load the Run history to prove publication state. Lookup failures remain visibly unconfirmed. The overall PR remains large and is not a complete simplification of the surrounding architecture.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changes requested before merge. I reviewed the active-turn and child-transcript journeys against the current main and reproduced the credential, hidden-error, and in-flight-tool failures below. The CI checks are green, but the PTY cases use matching environment/profile tokens, only exercise successful catalog loading, and do not exercise the picker while a non-agent tool is running.

The diff is +4429/-664, approximately +1979/-406 in production and +2429/-257 in tests/fixtures (module-boundary classification), plus documentation. Preserving ownership and unknown outcomes is necessary, but the added local custody, scope and handoff logic has not yet produced a reliably correct or convincingly simpler flow. Long-history performance and 1,000 distributed clients are not established by the current tests.

Comment thread crates/astra-cli/src/tui/event_loop.rs Outdated
if !owner.is_current() {
return None;
}
let token = if owner.native_binding.is_some() || owner.legacy_binding.is_some() {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Keep the bearer that admitted the active turn. presented_access_token gives a valid ASTRA_ACCESS_TOKEN priority over saved legacy credentials, but this branch instead picks the saved profile whenever a legacy binding exists. A real PTY test with distinct fake environment and profile tokens observed the active permission request using the profile token while the turn used the environment token. The same helper is used for active guidance, so a legitimate gateway/explicit-profile session can fail authorization or issue its controls as a different principal. Capture the actual admitted credential source with the turn and use that same authority for every active control; do not infer it from the existence of a saved profile.

Comment thread crates/astra-cli/src/tui/event_loop.rs Outdated
tasks: &mut tokio::task::JoinSet<()>,
) {
tasks.spawn(async move {
let result = crate::cli::session::session_runtime::fetch_owner_model_catalog(&api, &owner)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Support the environment-bearer journey in the active model picker. fetch_owner_model_catalog only accepts owner_access_token, which requires an account-bound native/legacy profile; a valid ASTRA_ACCESS_TOKEN alone is enough to start the current turn but cannot satisfy this call. A real PTY with the documented gateway bearer and no saved account reproduced /model failing instead of opening the picker. Idle /model already has the same underlying limitation on main, but this PR newly exposes it during execution, so the advertised live switch still fails for this supported deployment. Route the catalog read through the same admitted credential authority and add a PTY case without seeded profile credentials.

) {
picker_owner = Some(owner);
}
bottom_pane.sync_popups();

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Flush catalog failures while the task is still running. The error branch of apply_model_catalog_effect_for_choice commits a system cell, but this active-turn arm only schedules a frame and never calls flush_chat_widget; the adjacent task-join error branch has the same problem. In a real PTY, /model remained at Loading models for two seconds after the authentication failure and the not logged in error appeared only after an unrelated /model mock-model command flushed history. A 401, network error, or timeout therefore looks like an indefinite hang until later activity or turn settlement. Flush the committed error in this branch and cover an asynchronous catalog failure.

Comment thread crates/astra-cli/src/tui/event_loop.rs Outdated
chat_widget.commit_system(history_cell::system::SystemCell::info("Model catalog is already loading."));
} else {
model_catalog_loading = true;
chat_widget.commit_system(history_cell::system::SystemCell::info("Loading models… Current task continues."));

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Do not finalize a running tool to display this notice. commit_system calls commit_transcript_boundary, which drains active/parked tools and finalizes a still-running ToolCell as Uncertain. A focused test with a ToolStarted event followed by this exact Loading models notice reproduced the active tool disappearing and its history row becoming Uncertain before any completion event. This falsely tells the user the operation's outcome is unknown while it is still executing; the already-flushed terminal row is not repainted by the later history reconciliation. Use the concurrent notification path for non-terminal actions during a turn, and test model/help/permission interaction while a real tool is in flight.

changed |= self.apply_live_event_without_rebuild(event);
}
if changed {
self.rebuild_transcript();

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] The live transcript remains proportional to all loaded history. Each batch still calls transcript_snapshot and replace_with, which clone/re-render all loaded rows; each event also walks live items in reconcile_durable_items. Normal sparse streaming is frequently a single event, so batching does not change this path. A local debug-mode probe of 100 one-event updates took about 4.6 ms with 20 loaded items versus 499 ms with 2,000 short items. This is not a production or 1,000-client benchmark, and the full rebuild predates this PR, but it leaves the requested long-history Ctrl+G optimization unaddressed and runs on the foreground UI reducer. Reuse an incremental/viewport projection and validate with accumulated history and a live stream.

@XuPeng-SH
XuPeng-SH force-pushed the fix/streamline-live-steering branch from ce349a9 to a979513 Compare November 9, 2026 01:15

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed e7f212246 against 7593e3086. Changes are still needed before this meets the requested interaction and scale goals, even though the current CI checks that ran are green.

The five earlier review findings have corresponding code fixes and targeted tests; their GitHub threads are still unresolved. The prior history-rendering fix does substantially improve the loaded-history case, but it does not bound the cost of a growing live reasoning item. The inline findings cover two incorrect active-turn experiences, a picker availability problem, and two remaining Ctrl+G issues. Some of those limitations already existed on main; I have identified them as such because this PR explicitly takes ownership of improving those user journeys.

[P2] Existing child-guide observation still multiplies database work by pending message. Each successful child guidance opens its own stream_run(run_id, 0, ...), replaying the complete run before observing its receipt. Each attached stream goes through stream_run_live and independently polls durable state, backing off to one second when idle; an accepted guide to a paused but live run can keep its observer alive without an application deadline. Thus 1,000 attached guide observers can cause approximately 1,000 idle durable-delta reads per second, plus full-history replays; this is not a claim that 1,000 merely connected clients always do so. The mechanism predates this PR and the PR description acknowledges it, but it remains a material gap against the explicit distributed-CLI/Edge scale requirement. Please reuse an existing run observation or otherwise make observation bounded/shared without introducing per-round SQL, and validate the multi-server, pause/reconnect and long-history paths with measured database requests.

Complexity and coverage: the diff is +6,447/-908. An approximate classification of changed lines gives implementation +2,884/-675, tests and fixtures +3,538/-232, docs +25/-1. The implementation increase is substantial in its own right: event_loop.rs adds about 1,306 implementation lines and removes 478, while bottom_pane/mod.rs adds 681 and removes 61. Message custody and authentication fencing have real value, but the additional queue, scope, acknowledgement, and display logic must earn its cost. In particular, preserving two separate user intents (steer this run versus queue a future turn) should not require the backlog to change the meaning of Enter. Prefer extending the existing run/session owners and sharing observation over another state machine or database polling path. The tests cover many races and error cases, but also encode the current backlog and future-turn-only behavior; they do not establish the requested next-model-boundary behavior, complete live export, or the stated 1,000-client capacity. Documentation accurately describes the currently deferred model behavior, but that contract needs to change along with the implementation.

Verification: current-head CI checks that ran, including shared CLI, harness, lint and check, passed; scope-skipped jobs are not evidence of execution. For this review I ran two temporary local tests against this head and restored the worktree: a live-reasoning scaling probe and a live transcript export probe. They are local debug measurements, not production load results. No 1,000-client or multi-server capacity test has been performed.

Comment thread crates/astra-cli/src/tui/event_loop.rs Outdated
chat_widget.commit_concurrent_system(history_cell::system::SystemCell::info(format!(
"Selected {label} · applies after this task, including queued messages."
)));
staged_model = Some(NextModelSelection::Requested(requested));

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Apply a model choice at the next model boundary of this run. This only stores a local staged_model; it is consumed after the entire turn settles, so a long task can perform arbitrarily many more model calls with the old model after the user selects the new one. The picker path does the same. The requested interaction is like steering: leave the current request and started tools alone, but apply the selected model to the next model request within the current run, and retain it for subsequent turns. Show pending versus actually applied/rejected, and handle model/provider authorization, context compatibility, cancellation and cross-server ownership through the canonical execution owner. Add a real active-turn test with at least two model requests and a tool boundary; merely checking the next user turn preserves the current gap.

Comment thread crates/astra-cli/src/tui/event_loop.rs Outdated
) -> bool {
guidance_admission_closed
|| follow_up_deferred_before_bind
|| earlier_next_turn_pending

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P1] Do not let a future-turn backlog change Enter from steering into queuing. For example, while task A runs, enqueue B and C with Ctrl+Q. When B starts, C is still in queued_followup_submissions, so earlier_next_turn_pending is captured as true. An ordinary Enter during B, such as “stop editing and inspect first”, is then placed after C instead of reaching B, even while B accepts guidance. This retained behavior conflicts with the stated Enter-versus-Ctrl+Q interaction and can leave the running task acting on an obsolete instruction. Keep the future-turn FIFO ordered within its own lane without making it preclude explicitly steering the active run; test the full A/B/C journey including rejection or settlement races.

>,
) -> Option<crate::cli::session::session_runtime::AdmittedAuth> {
loop {
if run.borrow().is_some()

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Do not make the active model picker wait for an unrelated Run ID. publish_admitted_auth happens before starting the streaming request, but this helper waits for both that authenticated binding and RunBound before it can fetch the catalog. If run admission or its first response stalls, /model remains loading for the same 30-second catalog deadline and then reports a catalog timeout, even if the catalog service is healthy and the selected credential is available. Catalog browsing does not itself address a run. Capture an independently valid, correctly fenced owner/credential for this read so the picker can open during slow admission; retain the protection against profile switches, refreshed credentials and a replaced physical request. Test a held run admission and an independently responsive catalog.

}
}
TranscriptItem::rendered_kind(id, TranscriptItemKind::Assistant,
cell.live_viewport_lines(self.viewport_width, 48), 1)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Keep full live assistant text available to transcript search and export. The snapshot stores only the 48-row viewport rendering rather than a reference to the underlying live cell. While a long child reply is still streaming, scrolling, searching and export_plain_lines cannot access its earlier output; a local probe with 2,000 lines exported only 49 lines and omitted line 0. The original full projection on main has the same limitation, and this new fast path preserves it, so this is an outstanding issue in the Ctrl+G experience being changed rather than a newly introduced data-loss claim. Preserve the full logical content for on-demand navigation/search/export, while keeping routine live repaint bounded; test both before and after the item settles.

cell.push_delta(text);
}
}
TranscriptItem::reasoning(id, cell.clone(), 1)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Bound work per live reasoning update, not just per historical item. Each delta clones the complete accumulated ReasoningCell, and replace_live_tail renders it. The reasoning renderer counts all characters/lines and wraps the entire text twice even for the collapsed preview. Consequently the total work over a growing response is quadratic and runs on the interactive UI path. A local debug probe, 50 one-character deltas with 20 fixed historical items, measured 4.35 ms at ~2 KB, 124 ms at ~64 KB and 492 ms at ~256 KB; this is not a release or server-capacity benchmark. Keep counts/preview incrementally or project a bounded tail from the existing authoritative cell; render/search the full content on demand. Cover long streaming thinking as well as the 20-versus-2,000-history benchmark.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deep review of c095631 against current main f8a8d19. The remaining concerns are incorrect model-status reporting, long-history work on the live guidance path, repeated history processing on ordinary model rounds, and the requested in-flight /plan journey. Details are inline.

For low-probability failures, an honest failure or unknown result is acceptable; this review does not ask for retries or extra state merely to make every switch succeed. The important requirement is not to display a model as applied when the execution owner did not apply it.

The previous ten review threads are still marked unresolved in GitHub. The current head has corresponding fixes for nine reported paths, including bound credentials, catalog access and error flushing, preserving live tools, next-round model changes, FIFO steering, and live transcript search/reasoning. The earlier long-history Ctrl+G performance concern is only partially addressed: consecutive output/reasoning deltas have a fast path, but tool start/finish events still rebuild all loaded rows. In a synthetic unoptimized local test, 100 start/finish pairs took about 102 ms with 20 rows and 1,015 ms with 2,000 rows. This is not a production benchmark; the full rebuild predates this PR. I did not independently rerun every previous PTY reproduction.

The change is 84 files, +15,825/-2,811. By path, tests account for +1,699/-32 and docs for +52/-4; the remaining +14,074/-2,775 includes inline tests, so it is not an implementation-only count. Reusing the existing permission channel and coalescing child guidance observers are useful simplifications, but ordinary unchanged-model rounds still pay for repeated projection, and the existing main guidance observer still reads unbounded history. The complexity therefore has not yet demonstrated the desired cost/benefit for long histories and many distributed clients.

Validation: five additional targeted tests in an isolated worktree (two runtime, three CLI) passed as reproductions/measurements, including the injected post-commit read failure and /plan routing; no files in the working tree were changed. On a separate MatrixOne 4.2.8 test database, a synthetic 20,000-event EXPLAIN ANALYZE confirmed indexed settings queries but also confirmed that the full-run hydration returns all 20,000 events. These are not a thousand-client load test or release-mode benchmark. Current CI reports 39 successful, 3 skipped and 1 neutral check; passing CI does not establish the above scaling properties.

.run_settings_observation
.read(control.as_ref(), &user_id, &session_id, &run_id)
.await
.map_err(|_| {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Do not report an applied model before the execution owner has installed it. finish_run_model stores an Applied outcome and updates the effective model before this read, while install_explicit_model/ensure_applied_model happens only after it. If the read fails (or installing the admitted model later fails), the round exits with the old in-memory model but the stored outcome is already Applied. The snapshot/event can reach ActiveModelControl, whose Applied feedback sets the footer and prints Switched to …. A targeted fault-injection test reproduced a stored Applied(strong) alongside the owner still using economy and an error from prepare_turn_iteration. A rare failed switch is acceptable; a success status for a model the owner did not apply is not. Please make the visible outcome reflect the actual installation, or report unknown/failure when that cannot be established, without requiring a new retry state machine.

Comment thread crates/astra-cli/src/tui/event_loop.rs Outdated
match submission.result {
Ok(receipt) => {
debug_assert_eq!(receipt.intent_id, submission.intent_id);
bottom_pane.promote_user_intent_accepted(
&submission.intent_id,
);
let _ = spawn_primary_guidance_reconciliation(
api.clone(),
profile.map(str::to_string),
api.clone().without_bearer_provider(),

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] The guidance observer still hydrates the entire run on every connection. The observer calls ThinClient::stream_run from its accepted cursor, but /chat/runs/{id}/stream calls stream_run_live, which unconditionally calls load_run for metadata; the database implementation then hydrate_run_events with event_idx <= last_event_idx and fetch_all. Consequently one observer per run with unresolved guidance, and every reconnect, loads and deserializes the whole run even when the requested tail contains only a couple of events. With 20,000 synthetic events on MatrixOne 4.2.8, the full hydration returned 20,000 rows. This endpoint behavior predates the PR, but the current guidance path still relies on it and does not satisfy the stated long-history/1,000-distributed-client goal. Please use the existing live observation where possible and keep any recovery read bounded to the required metadata/tail rather than adding another per-message mechanism.

// concurrent requests do not retain an extra plaintext copy.
budget_source = self
.responses_budget_view(&candidate.messages, llm_cfg)
.provider_budget_view(&candidate.messages, llm_cfg, state)

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Avoid projecting the same history repeatedly on normal model rounds. provider_budget_view now invokes project_model_history before returning None for an unchanged non-Responses view. The candidate has already gone through the same call at line 18159; the None case calls it again here for the same candidate, in addition to other projection/verification on the round. project walks the assistant/tool history and authenticates relevant messages even when the user never changes models. A synthetic debug-mode probe of ten projection+verification pairs grew from about 78 ms for 100 tool groups to 785 ms for 1,000; this is not a production throughput benchmark, but it exposes avoidable history-sized CPU on the common path. Can the round reuse the already computed result, including the None result, without adding durable state? Please also measure representative long histories/concurrency in release mode before claiming the scale goal.

// The current run no longer accepts guidance.
if slash_dispatch::parse_submission(&queued_text).is_command() {
chat_widget.commit_concurrent_system(history_cell::system::SystemCell::info(
"Command queued until the current task finishes."

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] The requested in-flight /plan workflow still waits for the whole task. Unlike /model and /allow, /plan falls through to this generic command queue. If a user selects plan while a long task is running, the UI truthfully says it is queued, but the active task continues in its previous workflow until completion. /allow read_only changes permission and is not the same as entering the plan workflow. The design document explicitly describes this deferral, so this is a product/requirements gap rather than an inaccurate message: please support the requested next-safe-boundary behavior, or explicitly narrow the PR scope with acceptance of that limitation, and cover the actual user journey without introducing a separate parallel state machine.

@XuPeng-SH
XuPeng-SH force-pushed the fix/streamline-live-steering branch from ec66346 to 33fbcb6 Compare November 9, 2026 12:12
@XuPeng-SH
XuPeng-SH merged commit a03b471 into matrixorigin:main Nov 9, 2026
40 checks passed
@XuPeng-SH
XuPeng-SH deleted the fix/streamline-live-steering branch November 9, 2026 12:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant