Skip to content

feat: cross-client real-time streaming & settings sync (TUI ↔ GUI) - #10

Merged
huichen merged 21 commits into
mainfrom
feat/cross-client-streaming
Jul 22, 2026
Merged

huichen merged 21 commits into
mainfrom
feat/cross-client-streaming

Conversation

@huichen

@huichen huichen commented Jul 22, 2026

Copy link
Copy Markdown
Collaborator

Summary

Makes TUI and GUI fully synchronized in near real-time (< 1s) when operating on the same agent session.

What's included

Streaming content (user messages + AI responses)

  • TUI-initiated streaming now appears in GUI with a streaming bubble, just like GUI's own prompts
  • User messages arrive instantly via StreamEvents → Tauri events (zero latency)
  • AI responses stream via synthetic StoredRun → useRunReattach (220ms poll)
  • Mid-entry backfill: entering a session mid-stream shows full history, not just from entry point

Settings sync (model, thinking, name, cwd, etc.)

  • Agent broadcasts settings-change events (model_changed, thinking_level_changed, session_name_changed, cwd_changed, etc.) via StreamEvents
  • TUI receives and displays immediately via handleAgentEvent
  • GUI receives via persistent StreamEvents observer → Tauri events → frontend cache update
  • cwd changes auto-switch the thread's workspace in GUI sidebar

Session isolation

  • Guard against empty sessionId in gRPC StreamEvents subscription
  • Defer TUI event subscription until session is established
  • GUI filters events by agentSessionId to prevent cross-session message leakage

TUI input improvements

  • Auto soft-wrapping for long input lines
  • Arrow key symmetry: skip over invisible \n characters
  • Fix [0m ANSI escape leak after cursor

Files changed

  • Agent: commands.rs (settings broadcast), session isolation
  • TUI: app.ts, input.ts, types.ts, grpc-client.ts
  • GUI Tauri: agent_bridge/mod.rs, commands/threads.rs, store/threads.rs
  • GUI Frontend: useThreadMessages.ts, useThreadStore.ts, agentStateCache.ts, ThreadListItem.tsx, ActivityRail.tsx, AppShell.tsx

chenhui added 16 commits July 22, 2026 15:32
Agent (agent/src/rpc/commands.rs):
- list_sessions now queries active sessions' is_streaming flag
  so clients know which sessions are currently generating

TUI — cross-session isolation (tui/src/):
- Guard connectEvents() against empty sessionId to prevent
  wildcard event subscription leaking GUI streams into TUI
- Defer event subscribe() from constructor to start(),
  after the session ID is established via refresh()

TUI — input component (tui/src/components/input.ts):
- Auto soft-wrapping: long lines now wrap visually using
  wrapTextWithAnsi instead of horizontal scroll
- Arrow key symmetry: left/right skip over invisible \n
  characters, keeping cursor on visible text
- Fix [0m garbage after cursor: renderCursorInLine now
  computes byte offsets from original text (with ANSI)
  instead of stripped text, preventing escape-sequence
  truncation (tui/src/components/input.ts, utils.ts)

TUI — streaming indicator (tui/src/):
- Session picker and tree view show ● for streaming sessions
  via the new is_streaming field in SessionSummary

GUI — streaming detection (gui/src/):
- AgentSessionState gains isStreaming field
- Short-TTL (2s) streaming cache + pollStreamingStatuses()
- ThreadStore polls agent streaming status every 3s
- ThreadListItem shows spinner when agent reports streaming,
  even for prompts initiated by another client (TUI/CLI)
- AgentSessionSummary (Rust) parses is_streaming from
  list_sessions JSON
- Tauri get_thread_agent_state fallback includes isStreaming
When the GUI opens a thread whose agent session is streaming
(initiated by TUI, CLI, or phone), the frontend now asks the
Tauri backend to create a synthetic StoredRun and subscribe to
the agent's StreamEvents in the background.  Events are persisted
locally and the existing reattach machinery picks them up
automatically — no polling, no artificial delay.

Rust (gui/src-tauri):
- agent_bridge/mod.rs: attach_remote_stream() creates a run,
  spawns collect_remote_stream() which subscribes to the
  agent's gRPC StreamEvents and persists events via
  append_run_event / update_run_status_if_active
- commands/threads.rs: new tauri command attach_remote_stream
- lib.rs: register the command

Frontend (gui/src):
- useThreadMessages: replace polling reloadMessagesQuiet with
  invokeCommand('attach_remote_stream') — fires once when
  isStreaming is detected, then the existing refreshRecentRun →
  useRunReattach path takes over with real-time preview
…hows

When the TUI sends a prompt, the agent creates a new user entry.
loadFromAgent only runs on thread switch, so the user message was
missing until the next manual refresh.  Now attach_remote_stream
also calls reloadMessagesQuiet to fetch the latest session entries
immediately, ensuring the user question appears alongside the
streaming assistant bubble.
Agent now broadcasts an SseEvent whenever a settings mutation
completes successfully, so other connected clients (TUI, GUI)
receive near-real-time updates without polling get_state.

New event types:
  model_changed         — when set_model / cycle_model
  thinking_level_changed— when set_thinking / cycle_thinking
  permission_level_changed
  cwd_changed
  session_name_changed
  auto_compaction_changed
  tools_changed         — set_tools / disable_tools
  steering_mode_changed
  follow_up_mode_changed
  sandbox_policy_changed
  ephemeral_changed
  config_reloaded       — skills + context files

TUI (app.ts):
  handleAgentEvent now processes all settings-change events,
  updating local state immediately (model, thinking, cwd, etc.)
  without waiting for the next refresh() poll.
… streaming

fetchSessionStreaming (called every 3s by useThreadStore and
useThreadMessages) now updates the full AgentSessionState cache
(model, thinkingLevel, sessionName, cwd, isStreaming) instead of
only invalidating it.  This means settings changes made by another
client (TUI) are reflected in the GUI's composer and sidebar
within 3 seconds, without waiting for a new prompt or the 30s TTL.

The agent already broadcasts model_changed, thinking_level_changed,
etc. via StreamEvents — but the GUI doesn't subscribe to events
for idle sessions.  This polling bridge closes the gap.
Added a long-lived StreamEvents subscription in the Tauri backend
that runs for the active thread's session.  Settings-change events
(model_changed, thinking_level_changed, session_name_changed, etc.)
are forwarded to the frontend via Tauri 'agent-state-updated' events,
and the useCachedAgentState cache is updated immediately.

Rust (gui/src-tauri):
- agent_bridge/mod.rs: start_observing_session() spawns a background
  task that subscribes to StreamEvents and forwards settings events.
  Old observation is cancelled on thread switch via oneshot channel.
- commands/threads.rs: new observe_session tauri command
- lib.rs: register command

Frontend (gui/src):
- agentStateCache.ts: installAgentStateListener() listens for
  'agent-state-updated' events and updates the cache in real-time
- AppShell.tsx: installs listener on mount, calls observe_session
  whenever activeThread.agentSessionId changes

Now model/thinking/name/cwd changes from TUI reflect in GUI < 1s.
observe_session is a sync Tauri command that starts a background
observer.  tokio::spawn panics with 'no reactor running' in a
sync command context.  Use tauri::async_runtime::spawn instead,
which is always available within a Tauri app.
The agent-state-updated listener was iterating ALL cache entries and
updating every one that had matching fields, causing a name change
for one session to overwrite the name for all cached sessions.
Fixed by:
- Adding sessionId to AgentSessionState
- Populating it from get_thread_agent_state in both getAgentState
  and fetchSessionStreaming
- Matching on sessionId in the listener, updating only the one
  entry that belongs to the event's session
When the TUI (or another client) changes the session's cwd,
the GUI now automatically moves the thread to the workspace
matching the new cwd.

Rust:
- store/threads.rs: new move_thread_to_workspace()
- agent_bridge/mod.rs: reconcile_thread_workspace() resolves
  the correct workspace (chat vs project) for the new cwd
  and updates the thread's assignment
- commands/threads.rs: new reconcile_thread_workspace command

Frontend:
- agentStateCache.ts: when cwd_changed event arrives, calls
  reconcile_thread_workspace and dispatches future:cwd-changed
- AppShell.tsx: listens for future:cwd-changed and calls
  refreshStore() to re-render the sidebar
collect_remote_stream had a bug where the gRPC stream ending
normally (server closed it) would break out of the event loop
without marking the synthetic run as settled, leaving it stuck
in 'running' status forever.  This caused the GUI to show a
perpetual streaming spinner.

Fixes:
- On stream-end-without-agent_end, settle the run as 'failed'
- collect_reanimated_run: same fix for crash-recovery path
- Rust attach_remote_stream: skip if a run was completed in
  the last 10s (handles race between settlement and agent
  is_streaming flag clearing)
- Frontend: early-return if isRunActive (synthetic run already
  in flight), handle empty runId from attach_remote_stream
…ream

Previously the flow relied on refreshRecentRun → setRecentRun →
activeRunId → useRunReattach → upsertStreamingPreview, which has
multiple async hops and can miss the initial streaming events.
Now we call upsertStreamingPreview immediately after creating the
synthetic run, then let the existing pipeline take over on the
next tick.
The previous order was: upsertStreamingPreview → reloadMessagesQuiet.
reloadMessagesQuiet replaced all messages (including the just-added
streaming bubble) with agent entries, causing the bubble to be lost
and old assistant messages to duplicate.

Fixed order: reloadMessagesQuiet → upsertStreamingPreview.
User messages and history load first, then the streaming bubble
is added on top and maintained by useRunReattach.
useThreadMessages remote-stream poll: 3000 → 2000ms
useThreadStore stream-status poll: 3000 → 1000ms
fetchSessionStreaming cache TTL: 2000 → 1000ms

Cuts worst-case delay for TUI prompt → GUI detection by ~2s.
…stantly

Previously the observer only forwarded settings-change events.
Now ALL agent events (user_message, text_chunk, agent_start, etc.)
are forwarded via the 'agent-event' Tauri event.

Frontend handles user_message immediately by inserting it into the
message list, eliminating the reloadMessagesQuiet gRPC round-trip
delay.  Streaming content (text_chunk etc.) continues to use the
synthetic run/reattach mechanism which is already fast enough.

Settings events still update the agent state cache as before.
- collect_remote_stream: backfill past events from agent before
  subscribing to live stream, so mid-entry sessions get full
  streaming history instead of starting from subscription point.
- collect_remote_stream / collect_reanimated_run: settle runs on
  stream-end without agent_end to prevent perpetual 'running' status.
- Frontend: insert user_message from agent-event stream immediately
  (zero latency), skipping reloadMessagesQuiet gRPC round-trip.
- Frontend: match events by agentSessionId to prevent cross-session
  message leak. Pass agentSessionId through useAgentThreadState.
- AgentThread: scroll to latest message after loading completes,
  fixing the case where useLayoutEffect fires before MessageList
  is in the DOM during loading indicator.
- Removed duplicate upsertStreamingPreview call in attach flow —
  the useRunReattach path is the single source for streaming bubbles,
  preventing double-bubble bugs.
Copilot AI review requested due to automatic review settings July 22, 2026 07:33
}

consumed += subLen;
visualLine = vi + 1;
Comment thread tui/src/components/input.ts Fixed

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

This PR makes the TUI and GUI stay in near real-time sync when they’re attached to the same agent session, by (1) broadcasting settings changes over StreamEvents and (2) adding GUI-side observation/attachment paths so cross-client streaming and state updates show up promptly without relying on slow refreshes.

Changes:

  • Agent now broadcasts settings-change events (model/thinking/cwd/tools/etc.) via StreamEvents and exposes per-session is_streaming in list_sessions.
  • TUI defers StreamEvents subscription until a session is established, and upgrades the input component with soft-wrap-aware cursor navigation and ANSI-safe rendering.
  • GUI adds a Tauri StreamEvents observer + frontend event listener for real-time updates, plus remote-stream attachment to show TUI/other-client streaming as a synthetic run.

Reviewed changes

Copilot reviewed 20 out of 20 changed files in this pull request and generated 6 comments.

Show a summary per file
File Description
tui/src/rpc/types.ts Adds is_streaming to session summaries for UI indicators.
tui/src/rpc/grpc-client.ts Prevents subscribing to StreamEvents without a session ID to avoid cross-session leakage.
tui/src/components/input.ts Implements soft-wrap-aware visual cursor navigation and ANSI-safe cursor rendering.
tui/src/app.ts Defers event subscription until start() and handles new settings-change events.
tui/src/tests/input-bugs.test.ts Updates/extends cursor-navigation tests, including soft-wrap cases.
gui/src/integrations/agent/agentStateCache.ts Adds Tauri event listener + streaming-status polling helpers and extends cached state.
gui/src/features/agent/useThreadMessages.ts Attaches to remote streaming and injects real-time user_message events into the message list.
gui/src/features/agent/useAgentThreadState.ts Plumbs agentSessionId into useThreadMessages for session filtering.
gui/src/features/agent/AgentThread.tsx Ensures scroll-to-latest after loading completes.
gui/src/components/layout/ThreadListItem.tsx Uses agent-reported isStreaming as a fallback running indicator.
gui/src/components/layout/hooks/useThreadStore.ts Polls streaming status for active threads and exposes threadStreamingStatuses.
gui/src/components/layout/AppShell.tsx Installs the agent-event listener and starts backend observation on thread switch; refreshes store on cwd changes.
gui/src/components/layout/ActivityRail.tsx Threads streaming status into list items.
gui/src-tauri/src/store/threads.rs Adds move_thread_to_workspace for cwd-driven workspace reassignment.
gui/src-tauri/src/store.rs Re-exports the new thread-workspace move helper.
gui/src-tauri/src/lib.rs Registers new Tauri commands (observe/attach/reconcile).
gui/src-tauri/src/commands/threads.rs Adds Tauri commands for remote stream attach, session observation, and workspace reconciliation.
gui/src-tauri/src/agent_bridge/mod.rs Implements remote-stream collection/backfill and a StreamEvents observer that emits Tauri agent-events.
gui/src-tauri/src/agent_bridge/import.rs Extends agent session summaries with is_streaming for import/sync logic.
agent/src/rpc/commands.rs Broadcasts settings-change events and includes is_streaming in list_sessions.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +332 to +336
if (this.cursor <= consumed + subLen || vi === lines.length - 1) {
// Cursor is in (or at the end of) this visual sub-line
const offsetInSub = Math.max(0, this.cursor - consumed);
const colInWrapped = visibleWidth(plain.slice(0, offsetInSub));
return { visualLine: vi, colInWrapped, subLineText: sub };
Comment on lines +321 to +331
setMessages((prev) => {
if (prev.some((m) => m.role === "user" && m.content === text)) return prev;
return [...prev, {
id: `user_${Date.now()}`,
role: "user",
authorKey: "author.you",
content: text,
status: "complete",
createdAt: new Date().toISOString(),
} satisfies AgentMessage];
});
Comment thread agent/src/rpc/commands.rs Outdated
Comment on lines +320 to +335
// Snapshot active session streaming flags. Collect IDs first
// (drop the map lock), then read each inner lock separately so we
// never hold the outer read guard across an inner lock acquisition.
let active_flags: std::collections::HashMap<String, bool> = {
let active = state.sessions.read();
active
.iter()
.map(|(sid, sess)| {
let streaming = sess
.read()
.is_streaming
.load(std::sync::atomic::Ordering::Relaxed);
(sid.clone(), streaming)
})
.collect()
};
Comment thread gui/src-tauri/src/agent_bridge/mod.rs Resolved
Copilot AI review requested due to automatic review settings July 22, 2026 07:39
- Fix sessionId type safety in cwd_changed handler (use validated param)
- Fix TTL doc comment (2s → 1s)
- Narrow user_message dedup to last message only (allow repeated prompts)
- Fix Rust doc comment (agent-state-updated → agent-event)
- Fix lock comment in commands.rs to match actual implementation
- Remove unused subEnd variable in getCursorVisualInfo

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 20 out of 20 changed files in this pull request and generated 1 comment.

Comments suppressed due to low confidence (6)

tui/src/components/input.ts:294

  • buildVisualLayout() substitutes empty logical lines with a single space (logicalLine || " "). That makes the visual layout longer than the raw value and breaks cursor-to-visual mapping when a logical line is empty (cursor offsets no longer align with raw indices).
      const logicalLine = valueLines[li]!;
      const wrapped = wrapTextWithAnsi(logicalLine || " ", availableWidth);
      // Skip empty result (shouldn't happen, but guard)
      const subLines = wrapped.length > 0 ? wrapped : [" "];

tui/src/components/input.ts:340

  • getCursorVisualInfo() computes consumed by summing visual sub-line lengths but doesn't account for hard newlines between logical lines. Since this.cursor is an index into the raw value (which includes \n), cursor→visual line mapping becomes off by the number of preceding newlines (e.g. value "a\nb" with cursor on 'b').
      consumed += subLen;
      visualLine = vi + 1;

tui/src/components/input.ts:357

  • cursorFromVisual() maps visualLine→raw cursor offsets by summing prior visual sub-line lengths, but it also ignores hard newlines between logical lines. This makes up/down visual navigation land at the wrong raw indices whenever the value contains \n.
    for (let vi = 0; vi < vl; vi++) {
      consumed += stripAnsiCodes(lines[vi]!).length;
    }

gui/src/features/agent/useThreadMessages.ts:334

  • The real-time user_message handler de-dupes by checking any prior user message with the same text. The agent explicitly allows identical user messages across turns (no content-based dedup), so this can incorrectly drop legitimate repeats (e.g. sending "yes" again later). De-dupe should be limited to preventing immediate duplicates from event replays, not global-by-content.
      setMessages((prev) => {
        if (prev.some(m => m.role === "user" && m.content === text))
          return prev;
        return [...prev, {
          id: `user_${Date.now()}`,
          role: "user",
          authorKey: "author.you",

gui/src/integrations/agent/agentStateCache.ts:264

  • applySettingsEvent() passes sessionId: p.sessionId into reconcile_thread_workspace. p is Record<string, unknown>, so this can become non-string at runtime if the payload shape changes (and it defeats TypeScript's narrowing). Use the already-validated sessionId argument instead.
          invokeCommand("reconcile_thread_workspace", {
            sessionId: p.sessionId,
            cwd: p.cwd,
          }).then(() => {

gui/src/integrations/agent/agentStateCache.ts:292

  • STREAMING_TTL_MS is 1_000ms, but the docstring says the cache is 2s. This mismatch makes it harder to reason about refresh behavior; update the comment or the constant so they agree.
 * Uses a short-lived cache (2s) so the thread list picks up TUI-initiated
 * streaming quickly without hammering the agent with get_state RPCs.

Comment on lines +276 to +280
if (changed) {
cache.set(threadId, { state: next, fetchedAt: Date.now() });
}
break;
}
Copilot AI review requested due to automatic review settings July 22, 2026 07:46

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 20 out of 20 changed files in this pull request and generated 3 comments.

Comments suppressed due to low confidence (3)

tui/src/components/input.ts:294

  • buildVisualLayout() substitutes empty logical lines with a literal space (logicalLine || " ", and fallback [" "]). This makes truly empty lines render as visible spaces and also corrupts cursor→visual mapping for consecutive newlines (the layout now contains characters that aren't in this.value). Use the real logicalLine and treat an empty wrap result as [""].
      const logicalLine = valueLines[li]!;
      const wrapped = wrapTextWithAnsi(logicalLine || " ", availableWidth);
      // Skip empty result (shouldn't happen, but guard)
      const subLines = wrapped.length > 0 ? wrapped : [" "];

tui/src/components/input.ts:335

  • getCursorVisualInfo()/cursorFromVisual() compute consumed as the sum of wrapped sub-line lengths, but this.cursor is an index into the raw value which includes newline characters (and can jump over them due to the left/right skip logic). This causes cursor highlighting and up/down navigation to be off-by-N for multi-line values (e.g. "a\nb" at cursor=2 is treated as col 1 of the second visual line). The visual layout needs a mapping from each visual sub-line back to a raw byte offset (including +1 per hard newline) rather than assuming raw cursor indices are contiguous across visual lines.
      if (this.cursor <= consumed + subLen || vi === lines.length - 1) {
        // Cursor is in (or at the end of) this visual sub-line
        const offsetInSub = Math.max(0, this.cursor - consumed);
        const colInWrapped = visibleWidth(plain.slice(0, offsetInSub));
        return { visualLine: vi, colInWrapped, subLineText: sub };

gui/src/integrations/agent/agentStateCache.ts:280

  • applySettingsEvent() breaks after updating the first cache entry matching the sessionId. The store schema does not enforce agent_session_id uniqueness, so multiple threads can legitimately share a session; in that case only one thread's cached state will update, leaving others stale.
    if (changed) {
      cache.set(threadId, { state: next, fetchedAt: Date.now() });
    }
    break;
  }

Comment on lines +332 to +335
const userMsgs = prev.filter(m => m.role === "user");
const lastUser = userMsgs[userMsgs.length - 1];
if (lastUser && lastUser.content === text)
return prev;
Comment thread agent/src/rpc/commands.rs
Comment on lines +1387 to +1391
"config_reloaded",
serde_json::json!({
"skills": skill_names,
"contextFiles": if agent_content.is_empty() { vec![] } else { vec!["CLAUDE.md".to_string()] },
}),
Comment thread tui/src/app.ts
}
const currentMarker = s.id === this.state.sessionId ? "▶ " : " ";
const label = `${currentMarker}${prefix}${s.session_name || (s as any).first_message || s.id}`;
const streamingMark = (s as any).is_streaming ? "● " : "";
…st first

applySettingsEvent() was breaking after the first match, but
multiple threads can share one agent session. Now updates all
matching entries.
Copilot AI review requested due to automatic review settings July 22, 2026 07:52

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@huichen

huichen commented Jul 22, 2026

Copy link
Copy Markdown
Collaborator Author

LGTM

@huichen huichen self-assigned this Jul 22, 2026
@huichen
huichen requested review from Copilot and tallcode July 22, 2026 08:03

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

@huichen
huichen requested a review from Copilot July 22, 2026 08:07

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

tallcode and others added 2 commits July 22, 2026 16:17
navigator.clipboard.writeText() requires a secure context and
explicit permissions in Tauri's WKWebView, causing copy failures.
Swap order so the more reliable execCommand('copy') is tried first.
@huichen
huichen merged commit 6491f32 into main Jul 22, 2026
11 checks passed
@huichen
huichen deleted the feat/cross-client-streaming branch July 22, 2026 08:36
tallcode added a commit that referenced this pull request Jul 22, 2026
fast-uri is a transitive dev dependency in gui/ (table -> ajv ^3.0.1 -> fast-uri) locked at 3.1.3. Versions < 3.1.4 are vulnerable to host confusion via a literal backslash authority delimiter (Dependabot alert #10). 3.1.4 is the patched 3.x release and satisfies the existing range, so this is a lockfile-only bump.

Co-authored-by: Claude Fable 5 <[email protected]>
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.

3 participants