/* * Copyright (c) 2026 Haven for HarmonyOS contributors. * Port of Haven by GlassHaven (AGPL-3.0). See LICENSE. * * T9: process-wide registry of live TerminalSessions. Pages subscribe via * subscribe() and re-read all()/getActive() on every notification. */ import { TerminalSession } from './TerminalSession'; import type { ConnectSpec, SessionDeps } from './TerminalSession'; export class SessionManager { private static instance: SessionManager | null = null; static getInstance(): SessionManager { if (SessionManager.instance === null) { SessionManager.instance = new SessionManager(); } return SessionManager.instance; } private readonly sessions: Map = new Map(); private readonly listeners: Array<() => void> = []; private nextId: number = 1; private activeId: number | null = null; /** * Create a session, make it active and start dialing. The deps' * onStateChange is replaced with a manager notify so every state move * refreshes all subscribed pages. */ launch(spec: ConnectSpec, deps: SessionDeps): TerminalSession { const manager: SessionManager = SessionManager.getInstance(); const wrapped: SessionDeps = { knownHostStore: deps.knownHostStore, decideHostKey: deps.decideHostKey, loadPrivateKey: deps.loadPrivateKey, decryptPassword: deps.decryptPassword, encryptPassword: deps.encryptPassword, persistPassword: deps.persistPassword, markConnected: deps.markConnected, onStateChange: (session: TerminalSession): void => { manager.notify(); } }; const session: TerminalSession = new TerminalSession(this.nextId, spec, wrapped); this.nextId += 1; this.sessions.set(session.getId(), session); this.activeId = session.getId(); this.notify(); session.start(); return session; } get(id: number): TerminalSession | null { const found: TerminalSession | undefined = this.sessions.get(id); return found === undefined ? null : found; } all(): TerminalSession[] { return Array.from(this.sessions.values()); } getActiveId(): number | null { return this.activeId; } getActive(): TerminalSession | null { if (this.activeId === null) { return null; } return this.get(this.activeId); } setActive(id: number): void { if (this.sessions.has(id) && this.activeId !== id) { this.activeId = id; this.notify(); } } /** Close and forget a session; active falls back to the newest survivor. */ remove(id: number): void { const session: TerminalSession | null = this.get(id); if (session === null) { return; } session.close(); this.sessions.delete(id); if (this.activeId === id) { const rest: TerminalSession[] = this.all(); this.activeId = rest.length > 0 ? rest[rest.length - 1].getId() : null; } this.notify(); } subscribe(listener: () => void): () => void { this.listeners.push(listener); return (): void => { const idx: number = this.listeners.indexOf(listener); if (idx >= 0) { this.listeners.splice(idx, 1); } }; } notify(): void { const snapshot: Array<() => void> = this.listeners.slice(); for (let i: number = 0; i < snapshot.length; i++) { snapshot[i](); } } }