import { message, tr } from "../i18n/index.ts"; import type { Snapshot } from './client'; type Transport = (command: string, args?: Record) => Promise; export type TabStatus = { tabId: string; profileId?: string; url?: string; phase: 'connecting' | 'ready' | 'disconnected' | 'closed'; message: string; detail?: { operation: string; reason: string; tabId: string; time: string }; }; const connectionLost = (error: unknown) => /Unknown browser tab|stopped responding|timed out|response did not match|broken pipe|os error (109|232|10053|10054)\b/i.test(String(error)); export class TabSession { value: TabStatus; private transport: Transport; private changed: (value: TabStatus) => void; private pending?: Promise; private closed = false; private recovered = false; constructor(transport: Transport, initial: { tabId?: string; profileId?: string; url?: string }, changed: (value: TabStatus) => void) { this.transport = transport; this.changed = changed; this.value = { ...initial, tabId: initial.tabId || '', phase: 'connecting', message: 'Opening browser…' }; } private update(value: Partial) { this.value = { ...this.value, ...value }; this.changed(this.value); } observe(snapshot: Snapshot) { const tab = snapshot.tabs.find(tab => tab.id === this.value.tabId); if (tab) { this.value.profileId = tab.profileId; // The first snapshot can arrive before navigation starts. if (tab.url) this.value.url = tab.url; } } private failure(operation: string, error: unknown, tabId = this.value.tabId, phase: 'ready' | 'disconnected' = 'disconnected') { this.update({ phase, message: phase === 'ready' ? message('The browser could not complete this request. Check the error details.') : connectionLost(error) ? message('This tab lost its browser connection. Select Reconnect to restore the page.') : message('The browser could not complete this request. Check the details, then select Reconnect.'), detail: { operation, reason: String(error), tabId, time: new Date().toISOString() } }); } connect(): Promise { if (this.closed) return Promise.resolve(); if (this.pending) return this.pending; this.pending = this.restore().finally(() => { this.pending = undefined; }); return this.pending; } private async restore() { this.update({ phase: 'connecting', message: this.value.tabId ? message('Reconnecting browser…') : message('Opening browser…') }); let operation = 'state'; // The host discards a failed transport before the next request. for (let attempt = 0; attempt < 2; attempt++) { try { operation = 'state'; const snapshot = await this.transport('state') as Snapshot; if (this.closed) return; if (snapshot.tabs.some(tab => tab.id === this.value.tabId)) { this.observe(snapshot); this.update({ phase: 'ready', message: '' }); return; } const profileId = this.value.profileId || snapshot.profiles[0]?.id; operation = 'newTab'; const result = await this.transport('newTab', { profileId, ...(this.value.url ? { url: this.value.url } : {}) }) as { tabId: string }; if (this.closed) { await this.transport('closeTab', { tabId: result.tabId }).catch(() => {}); return; } this.update({ tabId: result.tabId, profileId }); operation = 'state'; const current = await this.transport('state') as Snapshot; if (this.closed) return; if (current.tabs.some(tab => tab.id === result.tabId)) { this.observe(current); this.update({ phase: 'ready', message: '' }); return; } if (attempt === 1) throw new Error(tr("The runtime restarted twice while opening this tab.")); } catch (error) { if (this.closed) return; if (attempt === 0 && connectionLost(error)) continue; this.failure(operation, error); return; } } } async send(command: string, args: Record = {}) { if (this.closed || this.value.phase !== 'ready') return; const tabId = this.value.tabId; try { await this.transport(command, { ...args, tabId }); if (tabId === this.value.tabId && this.value.phase === 'ready' && !['input', 'resize', 'visible'].includes(command) && this.value.message) this.update({ message: '' }); } catch (error) { // Replies from the previous connection cannot replace the current error. if (this.closed || tabId !== this.value.tabId || this.value.phase !== 'ready') return; const lost = connectionLost(error); this.failure(command, error, tabId, lost ? 'disconnected' : 'ready'); if (lost && !this.recovered) { this.recovered = true; await this.connect(); // Only an explicit address submission is safe to repeat. if (command === 'navigate' && this.value.phase === 'ready') await this.send(command, args); } } } detach() { this.closed = true; this.update({ phase: 'closed' }); } async close() { if (this.closed) return; this.closed = true; const tabId = this.value.tabId; this.update({ phase: 'closed' }); if (tabId) await this.transport('closeTab', { tabId }).catch(() => {}); } }