diff --git a/src/apps/cli/src/peer_host/commands/btw.rs b/src/apps/cli/src/peer_host/commands/btw.rs index 3345ed9ad0..757605b0b1 100644 --- a/src/apps/cli/src/peer_host/commands/btw.rs +++ b/src/apps/cli/src/peer_host/commands/btw.rs @@ -7,7 +7,6 @@ use std::future::Future; use std::sync::{Arc, OnceLock}; -use std::time::Duration; use openbitfun_core::agentic::coordination::{ btw_turn_id, get_global_coordinator, ConversationCoordinator, DialogSubmissionPolicy, @@ -15,7 +14,9 @@ use openbitfun_core::agentic::coordination::{ }; use openbitfun_core::agentic::core::SessionState; use openbitfun_core::agentic::image_analysis::ImageContextData; -use openbitfun_core::agentic::side_question::SideQuestionRuntime; +use openbitfun_core::agentic::side_question::{ + BtwTurnWatch, SideQuestionRuntime, BTW_TURN_POLL_INTERVAL, +}; use serde::Deserialize; use serde_json::{json, Value}; @@ -152,23 +153,17 @@ pub(crate) async fn btw_ask_stream(state: &PeerHostState, args: &Value) -> Resul ) .await; tokio::spawn(async move { - // The registration only serves cancellation; release it once the turn settles. + let mut watch = BtwTurnWatch::new(); loop { - let processing = coordinator - .get_session_manager() - .get_session(&child_session_id) - .is_some_and(|session| { - matches!( - session.state, - SessionState::Processing { current_turn_id, .. } - if current_turn_id == turn_id - ) - }); - if !processing { + let processing = matches!( + coordinator.get_session_manager().get_session_state(&child_session_id), + Some(SessionState::Processing { current_turn_id, .. }) if current_turn_id == turn_id + ); + if watch.should_release(processing) { runtime.remove(&request_id).await; break; } - tokio::time::sleep(Duration::from_millis(250)).await; + tokio::time::sleep(BTW_TURN_POLL_INTERVAL).await; } }); Ok(json!({ "ok": true })) diff --git a/src/apps/cli/src/peer_host/commands/terminal.rs b/src/apps/cli/src/peer_host/commands/terminal.rs index 0a32eb25a5..d372f84d66 100644 --- a/src/apps/cli/src/peer_host/commands/terminal.rs +++ b/src/apps/cli/src/peer_host/commands/terminal.rs @@ -40,6 +40,13 @@ fn exited_code(status: Option<&SessionStatus>) -> Option> { } } +fn unpublished_exit(status: Option<&SessionStatus>, exit_published: bool) -> Option { + if exit_published { + return None; + } + exited_code(status).map(|exit_code| json!({"exit_code":exit_code})) +} + fn api() -> Result { TerminalApi::from_singleton().map_err(|e| e.to_string()) } @@ -269,6 +276,11 @@ pub(crate) async fn create(state: &PeerHostState, args: &Value) -> Result { if changed.is_err() { + // The close can land between exit checks; keep the exit code. + let status = manager.session_status(&id).await; + if let Some(payload) = unpublished_exit(status.as_ref(), exit_published) { + publish_lifecycle(&hub, &id, TERMINAL_EXIT_EVENT, payload).await; + } publish_lifecycle(&hub, &id, TERMINAL_CLOSED_EVENT, json!({})).await; break; } @@ -500,6 +512,18 @@ pub(crate) async fn execute(args: &Value) -> Result { mod tests { use super::*; + #[test] + fn a_close_reports_an_exit_the_periodic_check_has_not_published() { + let exited = SessionStatus::Exited { exit_code: Some(7) }; + assert_eq!( + unpublished_exit(Some(&exited), false), + Some(json!({"exit_code":7})) + ); + assert_eq!(unpublished_exit(Some(&exited), true), None); + assert_eq!(unpublished_exit(Some(&SessionStatus::Active), false), None); + assert_eq!(unpublished_exit(None, false), None); + } + #[test] fn exit_is_reported_only_for_an_exited_session() { assert_eq!(exited_code(None), None); diff --git a/src/apps/desktop/src/api/btw_api.rs b/src/apps/desktop/src/api/btw_api.rs index 80271d4ab8..2da8c359eb 100644 --- a/src/apps/desktop/src/api/btw_api.rs +++ b/src/apps/desktop/src/api/btw_api.rs @@ -16,6 +16,7 @@ use openbitfun_core::agentic::coordination::{ ConversationCoordinator, DialogSubmissionPolicy, DialogTriggerSource, }; use openbitfun_core::agentic::image_analysis::ImageContextData; +use openbitfun_core::agentic::side_question::{BtwTurnWatch, BTW_TURN_POLL_INTERVAL}; fn desktop_btw_submission_policy() -> DialogSubmissionPolicy { DialogSubmissionPolicy::for_source(DialogTriggerSource::DesktopUi) @@ -143,27 +144,20 @@ pub async fn btw_ask_stream( let request_id = request.request_id.clone(); let coordinator = coordinator.inner().clone(); tokio::spawn(async move { + let mut watch = BtwTurnWatch::new(); loop { - let Some(session) = coordinator - .get_session_manager() - .get_session(&child_session_id) - else { - runtime.remove(&request_id).await; - break; - }; - - match session.state { - openbitfun_core::agentic::core::SessionState::Processing { + let processing = matches!( + coordinator.get_session_manager().get_session_state(&child_session_id), + Some(openbitfun_core::agentic::core::SessionState::Processing { current_turn_id, .. - } if current_turn_id == turn_id => { - tokio::time::sleep(std::time::Duration::from_millis(250)).await; - } - _ => { - runtime.remove(&request_id).await; - break; - } + }) if current_turn_id == turn_id + ); + if watch.should_release(processing) { + runtime.remove(&request_id).await; + break; } + tokio::time::sleep(BTW_TURN_POLL_INTERVAL).await; } }); diff --git a/src/crates/assembly/core/src/agentic/side_question.rs b/src/crates/assembly/core/src/agentic/side_question.rs index 9fadf68bb6..4ad11b7eea 100644 --- a/src/crates/assembly/core/src/agentic/side_question.rs +++ b/src/crates/assembly/core/src/agentic/side_question.rs @@ -1,7 +1,9 @@ //! Shared `/btw` prompt helpers and compatibility exports for runtime tracking. use crate::agentic::core::{InternalReminderKind, Message}; -pub use openbitfun_agent_runtime::side_question::{ActiveBtwTurn, SideQuestionRuntime}; +pub use openbitfun_agent_runtime::side_question::{ + ActiveBtwTurn, BtwTurnWatch, SideQuestionRuntime, BTW_TURN_POLL_INTERVAL, +}; pub fn btw_system_reminder() -> &'static str { r#"This is a side question from the user. You must answer this question directly. diff --git a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs index 85a75b370f..e36935fa24 100644 --- a/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs +++ b/src/crates/contracts/product-domains/src/remote_surface/capabilities.rs @@ -149,7 +149,6 @@ impl PeerHostCapability { Self::SessionTrajectoryV1, Self::UserQuestionResponse, Self::UserQuestionInteractionV1, - // Keep last: Desktop publishes every capability before it. Self::TerminalCursorReplayV1, ]; @@ -206,11 +205,50 @@ impl PeerHostCapability { } } -/// Desktop fans out `terminal_event`, so it has everything except the cursor -/// replay path, which `ALL` keeps last. -const DESKTOP_CAPABILITIES: &[PeerHostCapability] = PeerHostCapability::ALL - .split_at(PeerHostCapability::ALL.len() - 1) - .0; +/// Desktop publishes everything except `TerminalCursorReplayV1`: it fans out +/// `terminal_event`, and that key selects the other delivery path. +const DESKTOP_CAPABILITIES: &[PeerHostCapability] = &[ + PeerHostCapability::ModelRoutingV1, + PeerHostCapability::ModelPoolSelectionV1, + PeerHostCapability::BackgroundResultDeliveryV1, + PeerHostCapability::DialogQueueV1, + PeerHostCapability::IdempotentDialogSubmit, + PeerHostCapability::InlineImageAttachmentsV1, + PeerHostCapability::BtwInitialModelSelectionV1, + PeerHostCapability::BtwModelPoolSelectionV1, + PeerHostCapability::ControlConversationV1, + PeerHostCapability::ControlConversationResetV1, + PeerHostCapability::TargetedSessionRollback, + PeerHostCapability::TokenUsageStatistics, + PeerHostCapability::SubscriptionAccountsV1, + PeerHostCapability::SubscriptionProviderAccountsV1, + PeerHostCapability::SubscriptionQuotaV1, + PeerHostCapability::GrokQuotaV1, + PeerHostCapability::SubscriptionModelQuotaV1, + PeerHostCapability::SubscriptionAccountPoolsV1, + PeerHostCapability::SubscriptionAccountFailoverV1, + PeerHostCapability::ModelChannelRoutingV1, + PeerHostCapability::SubscriptionAccountManagementV1, + PeerHostCapability::MiniappAgentContextFilesV1, + PeerHostCapability::MiniappAgentImagesV1, + PeerHostCapability::WslWorkspacesV1, + PeerHostCapability::ComputerUseSharingV1, + PeerHostCapability::ProductControlV1, + PeerHostCapability::RemoteConnectControlV1, + PeerHostCapability::ProductControlNativeV1, + PeerHostCapability::ProductControlPresentationV1, + PeerHostCapability::CancelTool, + PeerHostCapability::ToolCatalog, + PeerHostCapability::ReviewPlatformV1, + PeerHostCapability::ChatMcpCatalogV1, + PeerHostCapability::WorkspaceIconV1, + PeerHostCapability::WorkspaceIdReferencesV1, + PeerHostCapability::WorkspaceHtmlPreviewV1, + PeerHostCapability::WholeSessionCopyV1, + PeerHostCapability::SessionTrajectoryV1, + PeerHostCapability::UserQuestionResponse, + PeerHostCapability::UserQuestionInteractionV1, +]; /// The CLI peer host has no MiniApp runtime, WSL connection setup, host-native /// ProductControl providers, or presentation surface. @@ -296,6 +334,14 @@ mod tests { capability.key() ); } + for capability in PeerHostCapability::ALL { + assert_eq!( + advertises(PeerHostKind::Desktop, *capability), + *capability != PeerHostCapability::TerminalCursorReplayV1, + "Desktop advertises everything but the cursor replay path: {}", + capability.key() + ); + } assert_eq!( advertised_by(PeerHostKind::Desktop).len(), PeerHostCapability::ALL.len() - 1 diff --git a/src/crates/execution/agent-runtime/src/side_question.rs b/src/crates/execution/agent-runtime/src/side_question.rs index a67a70fe86..6c386c2154 100644 --- a/src/crates/execution/agent-runtime/src/side_question.rs +++ b/src/crates/execution/agent-runtime/src/side_question.rs @@ -2,6 +2,7 @@ use std::collections::HashMap; use std::sync::Arc; +use std::time::{Duration, Instant}; use tokio::sync::Mutex; use tokio_util::sync::CancellationToken; @@ -17,6 +18,48 @@ pub struct ActiveBtwTurn { pub turn_id: String, } +/// How often a host re-reads whether a registered `/btw` turn still runs. +pub const BTW_TURN_POLL_INTERVAL: Duration = Duration::from_millis(250); +/// How long a turn that has not been seen running yet may keep its registration. +const BTW_TURN_START_GRACE: Duration = Duration::from_secs(5); + +/// Decides when a host may drop a `/btw` registration, which only serves +/// `btw_cancel`. A turn accepted a moment ago may not be running yet, and +/// dropping it then would make it uncancellable for its whole run. +#[derive(Debug)] +pub struct BtwTurnWatch { + started_at: Instant, + seen_processing: bool, +} + +impl Default for BtwTurnWatch { + fn default() -> Self { + Self::new() + } +} + +impl BtwTurnWatch { + pub fn new() -> Self { + Self { + started_at: Instant::now(), + seen_processing: false, + } + } + + /// Record one observation; `true` means the turn has settled. + pub fn should_release(&mut self, processing: bool) -> bool { + self.should_release_at(processing, Instant::now()) + } + + fn should_release_at(&mut self, processing: bool, now: Instant) -> bool { + if processing { + self.seen_processing = true; + return false; + } + self.seen_processing || now.duration_since(self.started_at) >= BTW_TURN_START_GRACE + } +} + impl Default for SideQuestionRuntime { fn default() -> Self { Self::new() @@ -83,7 +126,33 @@ impl SideQuestionRuntime { #[cfg(test)] mod tests { - use super::{ActiveBtwTurn, SideQuestionRuntime}; + use super::{ActiveBtwTurn, BtwTurnWatch, SideQuestionRuntime, BTW_TURN_START_GRACE}; + use std::time::Duration; + + #[test] + fn a_turn_not_running_yet_keeps_its_registration_during_the_grace_period() { + let mut watch = BtwTurnWatch::new(); + let start = watch.started_at; + assert!(!watch.should_release_at(false, start)); + assert!(!watch.should_release_at(false, start + Duration::from_secs(1))); + } + + #[test] + fn a_turn_that_never_runs_is_released_after_the_grace_period() { + let mut watch = BtwTurnWatch::new(); + let start = watch.started_at; + assert!(watch.should_release_at(false, start + BTW_TURN_START_GRACE)); + } + + #[test] + fn a_running_turn_is_released_as_soon_as_it_settles() { + let mut watch = BtwTurnWatch::new(); + let start = watch.started_at; + assert!(!watch.should_release_at(false, start)); + let long_after = start + BTW_TURN_START_GRACE * 10; + assert!(!watch.should_release_at(true, long_after)); + assert!(watch.should_release_at(false, start + Duration::from_millis(1))); + } #[tokio::test] async fn registering_same_request_cancels_previous_token() { diff --git a/src/web-ui/src/app/scenes/shell/hooks/useTerminalSessions.test.tsx b/src/web-ui/src/app/scenes/shell/hooks/useTerminalSessions.test.tsx new file mode 100644 index 0000000000..a95f2e76ce --- /dev/null +++ b/src/web-ui/src/app/scenes/shell/hooks/useTerminalSessions.test.tsx @@ -0,0 +1,60 @@ +// @vitest-environment jsdom + +import React, { act } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const service = vi.hoisted(() => ({ + connect: vi.fn(async () => {}), + listSessions: vi.fn(), + onEvent: vi.fn(() => () => {}), + setTrackedSessions: vi.fn(), + clearTrackedSessions: vi.fn(), +})); + +vi.mock('@/tools/terminal/services/TerminalService', () => ({ getTerminalService: () => service })); +vi.mock('@/shared/services/createManualTerminalSession', () => ({ createManualTerminalSession: vi.fn() })); + +import { useTerminalSessions } from './useTerminalSessions'; + +const scope = { + surfaceId: 'peer-host', + isCurrent: () => true, + assertCurrent: () => {}, + key: (...parts: unknown[]) => parts.join(':'), +} as never; +const savedSessionIds = new Set(); + +function Harness() { + useTerminalSessions({ + workspaceId: 'workspace-a', workspacePath: '/a', isRemote: false, currentConnectionId: null, + scope, savedSessionIds, + }); + return null; +} + +describe('useTerminalSessions', () => { + let root: Root; + + beforeEach(() => { + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + root = createRoot(document.createElement('div')); + }); + + afterEach(() => { + vi.clearAllMocks(); + }); + + it('tracks only the sessions this workspace shows and stops when it unmounts', async () => { + service.listSessions.mockResolvedValue([ + { id: 'mine', workspaceId: 'workspace-a', name: 'A', cwd: '/a' }, + { id: 'other', workspaceId: 'workspace-b', name: 'B', cwd: '/b' }, + ]); + await act(async () => root.render()); + + expect(service.setTrackedSessions).toHaveBeenLastCalledWith(expect.anything(), ['mine']); + const owner = service.setTrackedSessions.mock.calls.at(-1)?.[0]; + await act(async () => root.unmount()); + expect(service.clearTrackedSessions).toHaveBeenCalledWith(owner); + }); +}); diff --git a/src/web-ui/src/app/scenes/shell/hooks/useTerminalSessions.ts b/src/web-ui/src/app/scenes/shell/hooks/useTerminalSessions.ts index 85c8eb2ccc..3b326d55ee 100644 --- a/src/web-ui/src/app/scenes/shell/hooks/useTerminalSessions.ts +++ b/src/web-ui/src/app/scenes/shell/hooks/useTerminalSessions.ts @@ -39,6 +39,7 @@ export function useTerminalSessions(options: UseTerminalSessionsOptions) { return () => { currentActivation.current = null; }; }, [activation]); const requestVersion = useRef(0); + const trackingOwner = useRef({}).current; const [snapshot, setSnapshot] = useState(() => ({ key, sessions: snapshots.get(key) ?? [], loading: true, error: null, })); @@ -80,6 +81,7 @@ export function useTerminalSessions(options: UseTerminalSessionsOptions) { || terminalBelongsToWorkspace(session, target), ); snapshots.set(key, filtered); + service.setTrackedSessions(trackingOwner, filtered.map(session => session.id)); setSnapshot({ key, sessions: filtered, loading: false, error: null }); } catch (error) { if (!scope.isCurrent() || currentActivation.current !== activation || version !== requestVersion.current) return; @@ -88,7 +90,7 @@ export function useTerminalSessions(options: UseTerminalSessionsOptions) { loading: false, error: error instanceof Error ? error.message : String(error), })); } - }, [activation, assertCurrent, key, savedSessionIds, scope, target, workspaceId]); + }, [activation, assertCurrent, key, savedSessionIds, scope, target, trackingOwner, workspaceId]); useEffect(() => { const service = getTerminalService(); @@ -112,9 +114,10 @@ export function useTerminalSessions(options: UseTerminalSessionsOptions) { return () => { requestVersion.current += 1; unsubscribe(); + service.clearTrackedSessions(trackingOwner); window.removeEventListener('focus', refreshSessions); }; - }, [activation, key, refreshSessions, scope]); + }, [activation, key, refreshSessions, scope, trackingOwner]); const closeSessionIfPresent = useCallback(async (sessionId: string) => { assertCurrent(); diff --git a/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.test.ts b/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.test.ts index 707b464b16..42bbb0291c 100644 --- a/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.test.ts +++ b/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.test.ts @@ -141,6 +141,17 @@ describe('PeerTerminalReplay', () => { expect(events[1].payload.exit_code).toBe(3); }); + it('delivers an exit and the close right behind it, after the output', async () => { + mocks.invoke.mockResolvedValueOnce(page('bye\r\n', 15)); + replay.start(); + emit('terminal-exit', { terminal_id: 't1', exit_code: 7 }); + emit('terminal-closed', { terminal_id: 't1' }); + ready(); + await flush(); + expect(events.map(event => event.type)).toEqual(['Data', 'Exit', 'SessionDestroyed']); + expect(events[1].payload.exit_code).toBe(7); + }); + it('maps a closed session to the destroyed event', async () => { mocks.invoke.mockResolvedValue(page('', 10)); replay.start(); diff --git a/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.ts b/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.ts index 30cb4be82e..9fbd0e3a06 100644 --- a/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.ts +++ b/src/web-ui/src/tools/terminal/services/PeerTerminalReplay.ts @@ -45,7 +45,7 @@ export class PeerTerminalReplay { private followEpoch = 0; private draining = false; private dirty = false; - private pendingLifecycle: PeerTerminalRawEvent | null = null; + private readonly pendingLifecycle: PeerTerminalRawEvent[] = []; private streamFailure: string | null = null; private retryDelay = 0; private retryTimer: ReturnType | null = null; @@ -156,17 +156,16 @@ export class PeerTerminalReplay { /** The exit must not overtake output that is already in the replay log. */ private finishAfterDrain(event: PeerTerminalRawEvent): void { - // A close supersedes an exit that is still waiting for its output. - this.pendingLifecycle = event; + // Queued in order: a close right behind an exit must not lose its exit code. + this.pendingLifecycle.push(event); if (this.isFollowing() && this.caughtUp) this.requestRead(); else if (!this.isFollowing()) this.deliverPendingLifecycle(); } private deliverPendingLifecycle(): void { - const lifecycle = this.pendingLifecycle; - if (!lifecycle || !this.isActive()) return; - this.pendingLifecycle = null; - this.deliver(lifecycle); + while (this.pendingLifecycle.length > 0 && this.isActive()) { + this.deliver(this.pendingLifecycle.shift()!); + } } private requestRead(): void { diff --git a/src/web-ui/src/tools/terminal/services/TerminalService.test.ts b/src/web-ui/src/tools/terminal/services/TerminalService.test.ts index 10c726b532..03cc7b70ec 100644 --- a/src/web-ui/src/tools/terminal/services/TerminalService.test.ts +++ b/src/web-ui/src/tools/terminal/services/TerminalService.test.ts @@ -162,10 +162,9 @@ describe('TerminalService device surface switching', () => { expect(replayMock.created[0].follow).toHaveBeenCalledWith(3); }); - it('starts lifecycle tracking when a tab list subscribes after sessions were loaded', async () => { + it('starts lifecycle tracking when a tab list subscribes after declaring its sessions', async () => { const service = await connectToHost(); - invokeMock.mockResolvedValueOnce([{ id: 't1', workspaceId: 'w', name: 'Shell' }]); - await service.listSessions(); + service.setTrackedSessions({}, ['t1']); expect(replayMock.created).toHaveLength(0); service.onEvent(vi.fn()); @@ -174,6 +173,35 @@ describe('TerminalService device surface switching', () => { expect(replayMock.created[0].follow).not.toHaveBeenCalled(); }); + it('does not subscribe to every host terminal just because they were listed', async () => { + const service = await connectToHost(); + service.onEvent(vi.fn()); + invokeMock.mockResolvedValueOnce([ + { id: 'mine', workspaceId: 'w1', name: 'Shell' }, + { id: 'other-workspace', workspaceId: 'w2', name: 'Shell' }, + ]); + await service.listSessions(); + expect(replayMock.created).toHaveLength(0); + + service.setTrackedSessions({}, ['mine']); + expect(replayMock.created.map(replay => replay.sessionId)).toEqual(['mine']); + }); + + it('keeps a session tracked until the last tab list showing it leaves', async () => { + const service = await connectToHost(); + service.onEvent(vi.fn()); + const shell = {}; + const panel = {}; + service.setTrackedSessions(shell, ['t1']); + service.setTrackedSessions(panel, ['t1']); + expect(replayMock.created).toHaveLength(1); + + service.clearTrackedSessions(shell); + expect(replayMock.created[0].close).not.toHaveBeenCalled(); + service.clearTrackedSessions(panel); + expect(replayMock.created[0].close).toHaveBeenCalledTimes(1); + }); + it('falls back to host kind for a CLI host that predates the capability', async () => { const service = await connectToHost({ hostKind: 'cli' }); service.onSessionEvent('t1', vi.fn()); @@ -243,8 +271,7 @@ describe('TerminalService device surface switching', () => { const service = await connectToHost(); const events = vi.fn(); service.onEvent(events); - invokeMock.mockResolvedValueOnce([{ id: 't1', workspaceId: 'w', name: 'Shell' }]); - await service.listSessions(); + service.setTrackedSessions({}, ['t1']); expect(replayMock.created).toHaveLength(1); expect(replayMock.created[0].follow).not.toHaveBeenCalled(); @@ -255,8 +282,7 @@ describe('TerminalService device surface switching', () => { it('returns a tab to lifecycle tracking when its view unmounts', async () => { const service = await connectToHost(); service.onEvent(vi.fn()); - invokeMock.mockResolvedValueOnce([{ id: 't1', workspaceId: 'w', name: 'Shell' }]); - await service.listSessions(); + service.setTrackedSessions({}, ['t1']); const view = service.onSessionEvent('t1', vi.fn()); view(); diff --git a/src/web-ui/src/tools/terminal/services/TerminalService.ts b/src/web-ui/src/tools/terminal/services/TerminalService.ts index ea4a304e32..57447b6433 100644 --- a/src/web-ui/src/tools/terminal/services/TerminalService.ts +++ b/src/web-ui/src/tools/terminal/services/TerminalService.ts @@ -63,8 +63,8 @@ export class TerminalService { /** Where `getHistory` stopped, so the replay that follows neither repeats nor skips output. */ private readonly replayOffsets = new Map(); - /** Sessions the tab list knows about; their exit must be seen without a mounted view. */ - private trackedSessions = new Set(); + /** Sessions each tab list shows; their exit must be seen without a mounted view. */ + private readonly trackedSessions = new Map>(); private unsubscribePeers: (() => void) | null = null; @@ -154,7 +154,7 @@ export class TerminalService { const active = this.isConnected() && this.usesPeerReplay(); const wanted = new Set(!active ? [] : [ ...this.eventListeners.keys(), - ...(this.globalListeners.size > 0 ? this.trackedSessions : []), + ...(this.globalListeners.size > 0 ? [...this.trackedSessions.values()].flatMap(ids => [...ids]) : []), ]); this.peerReplays.forEach((replay, sessionId) => { if (wanted.has(sessionId)) return; @@ -180,7 +180,7 @@ export class TerminalService { private forgetSession(sessionId: string): void { this.eventListeners.delete(sessionId); - this.trackedSessions.delete(sessionId); + this.trackedSessions.forEach(ids => ids.delete(sessionId)); this.replayOffsets.delete(sessionId); this.reconcilePeerReplays(); } @@ -307,6 +307,19 @@ export class TerminalService { }; } + /** + * Declare what one tab list shows. `terminal_list` spans every workspace on the + * host, so only the caller can say which sessions deserve a stream subscription. + */ + setTrackedSessions(owner: object, sessionIds: Iterable): void { + this.trackedSessions.set(owner, new Set(sessionIds)); + this.reconcilePeerReplays(); + } + + clearTrackedSessions(owner: object): void { + if (this.trackedSessions.delete(owner)) this.reconcilePeerReplays(); + } + async getAvailableShells(): Promise { try { const shells = await api.invoke('terminal_get_shells'); @@ -364,8 +377,6 @@ export class TerminalService { try { const sessions = await api.invoke('terminal_list'); scope.assertCurrent('terminal_list'); - this.trackedSessions = new Set(sessions.map(session => session.id)); - this.reconcilePeerReplays(); return sessions.map(session => this.projectSession(scope.surfaceId, session)); } catch (error) { log.error('Failed to list sessions', error);