/** * @fileoverview The "sessions someone opened by hand" block on the home screen. * * A tmux session a human started (`tmux new -s work`, then `claude`, or just a * shell) is invisible to Codeman: it lives on the DEFAULT socket, not the * instance-scoped one Codeman owns. `GET /api/mux/foreign` finds those, and one * click wraps one in a Codeman tab (`POST /api/sessions/adopt`). * * ## One renderer, two containers * * The welcome screen and the phone overview both show this list. They call the * SAME `renderForeignSessions(container)` rather than each building rows, because * two renderers are how one surface ends up calling a session "shell" while the * other calls it "bash". Same reason `CodemanSessionOrder` is shared. * * ## Polling only while the home screen is up * * The list is a poll, not an SSE stream: the server caches a local scan on a TTL, * so N tabs polling costs one scan per TTL no matter how many are open. But an * open tab that has LEFT the home screen must stop, otherwise every background * tab keeps sweeping tmux sockets forever. `startForeignPolling` / * `stopForeignPolling` are called from `showWelcome`/`hideWelcome`. * * A tab hidden while it shows the home screen skips its ticks as well. The TTL sits * under the poll interval, so one tab never hits the cache: every tick is a full * sweep, one fork or more per socket, for a list nobody is reading. It catches up * on `visibilitychange`, and the cache is what bounds a flurry of tab switches. * * ⚠️ Docker and remote locations are NOT in that poll. Each costs a `docker exec` * or a full ssh handshake per target, each with a ~12s timeout, so riding them * along on an 8s tick stacks connections on a slow host, the one cost the * server-side design explicitly refuses. The wide scan is therefore ONE-SHOT: * turning the toggle on fetches once, and after that it is the user's Rescan * button. The periodic poll stays local-only forever. * * The wide rows are kept separately (`_foreignWideSessions`) and merged into * every local render, because a local-only poll's payload does not contain them * and would otherwise wipe the container/remote rows off the list one tick after * they appeared. Turning the toggle off discards them. * * ⚠️ Adoption creates a REAL session, so the button locks while in flight and the * result goes through the app's normal idempotent create path * (`_onSessionCreated` then `selectSession`), never by inserting a tab here. * * @mixin Extends CodemanApp.prototype via Object.assign * @dependency app.js (this.sessions, _onSessionCreated, selectSession) * @dependency api-client.js (_api) * @dependency ralph-panel.js (formatRelativeTime) * @dependency i18n.js (codemanT, optional) * @loadorder 12.565 of 16, after home-sessions.js, before git-status-ui.js */ /** Fallback poll cadence; the server sends its own in `pollIntervalMs`. */ const FOREIGN_POLL_FALLBACK_MS = 8000; /** i18n.js's translator, or the English source where it has not loaded. */ function foreignT(source) { return typeof codemanT === 'function' ? codemanT(source) : source; } /** A row's mode, in the registry's own word for it. Falls back to the id, never a list of ids here. */ function foreignModeLabel(mode) { const catalog = typeof window !== 'undefined' && Array.isArray(window.__codemanCliCatalog) ? window.__codemanCliCatalog : []; return catalog.find((entry) => entry.id === mode)?.label || mode; } const FOREIGN_LOCATION_LABEL = { local: 'this machine', docker: 'container', remote: 'remote', }; Object.assign(CodemanApp.prototype, { // ═══════════════════════════════════════════════════════════════ // Lifecycle // ═══════════════════════════════════════════════════════════════ /** * Begin polling. Idempotent: the home screen re-shows on several paths * (boot, closing the last tab, a breakpoint change) and each would otherwise * stack another interval on top of the last. */ startForeignPolling() { if (this._foreignPollTimer || this._foreignRefused) return; this._foreignPollTick(); this._foreignPollTimer = setInterval( () => this._foreignPollTick(), this._foreignPollMs || FOREIGN_POLL_FALLBACK_MS ); // Stored, unlike a poller made once: this runs on every trip to the home screen. this._foreignOnVisible = () => this._foreignPollTick(); document.addEventListener('visibilitychange', this._foreignOnVisible); }, /** Stop polling. MUST run on leaving the home screen, see @fileoverview. */ stopForeignPolling() { if (!this._foreignPollTimer) return; clearInterval(this._foreignPollTimer); this._foreignPollTimer = null; document.removeEventListener('visibilitychange', this._foreignOnVisible); this._foreignOnVisible = null; }, /** One poll, and the one gate every poll passes: a hidden tab skips it, see @fileoverview. */ _foreignPollTick() { if (document.hidden) return; // Local only: see @fileoverview. The wide scan never rides the timer. void this.loadForeignSessions(); }, /** Whether the user asked for the expensive docker/remote scan too. */ foreignScanRemote() { return this._foreignScanRemote === true; }, /** * Flip the wide scan. ON fetches containers and hosts ONCE; OFF discards what * that fetch found, because those rows are not re-confirmed by any later poll * and leaving them up would show a container session that may be long gone. */ toggleForeignScanRemote() { this._foreignScanRemote = !this._foreignScanRemote; if (!this._foreignScanRemote) { this._foreignWideSessions = []; this._foreignWideNotes = []; this.renderAllForeignSessions(); return; } void this.loadForeignSessions({ wide: true }); }, /** Re-run the expensive scan on demand. The only way wide rows ever refresh. */ rescanForeignWide() { if (!this.foreignScanRemote()) return; void this.loadForeignSessions({ wide: true }); }, // ═══════════════════════════════════════════════════════════════ // Data // ═══════════════════════════════════════════════════════════════ /** * Fetch the list. `wide` asks the server for containers and ssh hosts too, and * ONLY an explicit user action ever passes it, never the interval. */ async loadForeignSessions({ wide = false } = {}) { if (this._foreignRefused) return; const qs = wide ? '?docker=1&remote=1' : ''; if (wide) this._foreignWideLoading = true; this.renderAllForeignSessions(); const res = await this._api(`/api/mux/foreign${qs}`); if (wide) this._foreignWideLoading = false; // ⚠️ A 403 is an answer, not a failed poll. The list is admin-only in multi-user // mode (it shows other people's processes), so a non-admin has nothing to see here // and nothing later on this page changes that: stop asking and show no block, // instead of "Could not reach the server" under a heading they cannot use. if (res?.status === 403) { this._foreignRefused = true; this.stopForeignPolling(); this.renderAllForeignSessions(); return; } const body = res?.ok ? await this._readJsonBody(res) : null; const data = body?.success === true ? body.data : body?.success === false ? null : body; if (!data) { // A failed poll must not blank a list the user is looking at: keep the // last good result and let the next tick recover. this._foreignError = true; this.renderAllForeignSessions(); return; } this._foreignError = false; const rows = Array.isArray(data.sessions) ? data.sessions : []; const notes = Array.isArray(data.notes) ? data.notes : []; // Every note opens with its location (foreign-tmux-discovery.ts). A local one is // re-read on each poll; a container or host one only by the next explicit scan, // so it has to outlive the local polls in between. const isLocalNote = (note) => String(note).startsWith('local:'); this._foreignNotes = notes.filter(isLocalNote); if (wide) { // Split by location: the local rows refresh on every tick, the rest only // here, so they have to be stored apart or the next local-only payload // (which cannot contain them) would read as "those sessions are gone". this._foreignSessions = rows.filter((r) => (r.location || 'local') === 'local'); this._foreignWideSessions = rows.filter((r) => (r.location || 'local') !== 'local'); this._foreignWideNotes = notes.filter((note) => !isLocalNote(note)); this._foreignWideAt = Date.now(); } else { this._foreignSessions = rows; } this._foreignCanScanWide = data.canScanWide === true; if (Number.isFinite(data.pollIntervalMs)) this._foreignPollMs = data.pollIntervalMs; this.renderAllForeignSessions(); }, /** Local rows plus whatever the last wide scan found. The render's one input. */ _allForeignRows() { const local = Array.isArray(this._foreignSessions) ? this._foreignSessions : []; if (!this.foreignScanRemote()) return local; const wide = Array.isArray(this._foreignWideSessions) ? this._foreignWideSessions : []; return wide.length ? local.concat(wide) : local; }, /** * Adopt one candidate. * * The in-flight lock is global, one adoption at a time from this page: it only * stops a double-click. The server holds the real one-wrapper-per-target * guarantee. */ async adoptForeignSession(id, buttonEl) { if (this._foreignAdoptInFlight) return; this._foreignAdoptInFlight = true; if (buttonEl) { buttonEl.disabled = true; buttonEl.textContent = foreignT('Opening…'); } try { const body = { id }; if (this.foreignScanRemote()) { body.docker = true; body.remote = true; } // ⚠️ `_api`, not `_apiJson`: the latter folds a network failure, a non-2xx // and `success:false` all into null, and the server deliberately tells // two different stories here: "that tmux session is no longer there" vs // "could not reach it just now (…), try again". Collapsing them showed a // live remote session as deleted every time the link flickered. const res = await this._api('/api/sessions/adopt', { method: 'POST', body }); const payload = await this._readJsonBody(res); const session = payload && payload.success !== false ? payload.data?.session : null; if (!session) { const fallback = foreignT('Could not open that session. Refreshing the list.'); this.showToast?.(payload?.error || fallback, 'error'); await this.loadForeignSessions(); return; } const data = { session }; // Go through the app's normal create path so tab order, lineage lines and // SSE-vs-POST ordering behave exactly as they do for a Run. this._onSessionCreated?.(data.session); await this.selectSession(data.session.id); // Still one explicit user action, so a wide row's "Open" refreshes the // wide list too, otherwise the row just adopted keeps reading as free. await this.loadForeignSessions({ wide: this.foreignScanRemote() }); } finally { this._foreignAdoptInFlight = false; if (buttonEl) { buttonEl.disabled = false; buttonEl.textContent = foreignT('Open'); } } }, /** The error envelope, or null when there was no readable body at all. */ async _readJsonBody(res) { if (!res) return null; try { return await res.json(); } catch { return null; } }, // ═══════════════════════════════════════════════════════════════ // Render // ═══════════════════════════════════════════════════════════════ /** Paint every mounted container (welcome + phone overview). */ renderAllForeignSessions() { for (const id of ['foreignSessions', 'mobileForeignSessions']) { const el = document.getElementById(id); if (el) this.renderForeignSessions(el); } }, /** * Render into one container. The ONLY row builder, see @fileoverview. * * Everything is built with DOM APIs and `textContent`: a session name and a * command line come from another user's process, so they are never allowed * near `innerHTML`. */ renderForeignSessions(container) { const rows = this._allForeignRows(); container.innerHTML = ''; if (this._foreignRefused) { container.hidden = true; return; } if (!rows.length) { // Hidden rather than shown-empty: on a first run there is usually nothing, // and an empty block on the welcome screen reads as a broken feature. // A note is a REASON the list is empty, so a block carrying one must stay // visible: hiding it is exactly how "where did my session go" becomes // unanswerable. const hasNotes = (Array.isArray(this._foreignNotes) && this._foreignNotes.length > 0) || (Array.isArray(this._foreignWideNotes) && this._foreignWideNotes.length > 0); // ⚠️ `canScanWide` must keep the block visible even with nothing to show. // The scan toggle lives in the header, so hiding an empty block also hides // the only control that could fill it: on a host with containers but no // local tmux sessions that made the whole feature unreachable. container.hidden = !this.foreignScanRemote() && !this._foreignError && !hasNotes && !this._foreignCanScanWide; if (!container.hidden) { container.appendChild(this._foreignHeader(0)); const empty = document.createElement('div'); empty.className = 'foreign-empty'; this._appendForeignNotes(container); empty.textContent = this._foreignError ? foreignT('Could not reach the server.') : foreignT('No sessions found outside Codeman.'); container.appendChild(empty); } return; } container.hidden = false; container.appendChild(this._foreignHeader(rows.length)); this._appendForeignNotes(container); const list = document.createElement('div'); list.className = 'foreign-list'; // Adoptable first: an already-open one is not an action, it is a reminder. const sorted = rows.slice().sort((a, b) => { const aOpen = a.adoptedBy ? 1 : 0; const bOpen = b.adoptedBy ? 1 : 0; if (aOpen !== bOpen) return aOpen - bOpen; return (b.createdAt || 0) - (a.createdAt || 0); }); for (const row of sorted) list.appendChild(this._foreignRow(row)); container.appendChild(list); }, /** * Why a scan produced less than the user expected. * * Without this, a session skipped for an unsafe name or a host that could not * be reached is simply ABSENT, and "my tmux session does not show up" has no * answer anywhere in the product. Notes are server-authored strings, rendered * as text. */ _appendForeignNotes(container) { const local = Array.isArray(this._foreignNotes) ? this._foreignNotes : []; const wide = this.foreignScanRemote() && Array.isArray(this._foreignWideNotes) ? this._foreignWideNotes : []; const notes = wide.length ? local.concat(wide) : local; if (!notes.length) return; const box = document.createElement('div'); box.className = 'foreign-notes'; box.setAttribute('data-i18n-skip', ''); for (const n of notes) { const line = document.createElement('div'); line.className = 'foreign-note'; line.textContent = n; box.appendChild(line); } container.appendChild(box); }, _foreignHeader(count) { const header = document.createElement('div'); header.className = 'foreign-header'; const title = document.createElement('h3'); title.className = 'foreign-title'; title.textContent = foreignT('Opened outside Codeman'); header.appendChild(title); if (count) { const badge = document.createElement('span'); badge.className = 'foreign-count'; badge.setAttribute('data-i18n-skip', ''); badge.textContent = String(count); header.appendChild(badge); } const scan = document.createElement('button'); scan.type = 'button'; scan.className = 'foreign-scan-toggle'; scan.dataset.foreignAction = 'toggle-scan'; scan.setAttribute('aria-pressed', String(this.foreignScanRemote())); scan.title = foreignT('Also scan containers and remote hosts (slower)'); scan.textContent = this.foreignScanRemote() ? '⟳ all' : '⟳ local'; header.appendChild(scan); // The wide scan is one-shot, so without this button its rows could only // ever be refreshed by toggling off and on again. if (this.foreignScanRemote()) { const rescan = document.createElement('button'); rescan.type = 'button'; rescan.className = 'foreign-scan-toggle'; rescan.dataset.foreignAction = 'rescan-wide'; rescan.disabled = this._foreignWideLoading === true; rescan.title = foreignT('Scan containers and remote hosts again'); rescan.textContent = this._foreignWideLoading ? foreignT('Scanning…') : foreignT('Rescan'); header.appendChild(rescan); } return header; }, _foreignRow(row) { const item = document.createElement('div'); item.className = 'foreign-row'; if (row.adoptedBy) item.classList.add('foreign-row--open'); const dot = document.createElement('span'); dot.className = `foreign-dot foreign-dot--${row.mode || 'shell'}`; item.appendChild(dot); const body = document.createElement('span'); body.className = 'foreign-row-body'; const line1 = document.createElement('span'); line1.className = 'foreign-row-name'; line1.setAttribute('data-i18n-skip', ''); line1.textContent = row.sessionName || '(unnamed)'; body.appendChild(line1); const line2 = document.createElement('span'); line2.className = 'foreign-row-sub'; line2.setAttribute('data-i18n-skip', ''); const bits = [foreignModeLabel(row.mode)]; const where = row.hostLabel || foreignT(FOREIGN_LOCATION_LABEL[row.location] || row.location); if (where) bits.push(where); if (row.workingDir) bits.push(row.workingDir); line2.textContent = bits.join(' · '); line2.title = row.command || ''; body.appendChild(line2); item.appendChild(body); const action = document.createElement('button'); action.type = 'button'; action.className = 'foreign-open-btn'; if (row.adoptedBy) { action.dataset.foreignAction = 'select'; action.dataset.foreignSession = row.adoptedBy; action.textContent = foreignT('Go to tab'); } else { action.dataset.foreignAction = 'adopt'; action.dataset.foreignId = row.id; action.textContent = foreignT('Open'); } item.appendChild(action); return item; }, /** * One delegated listener per container, wired once. Delegation matters here * because the list is fully rebuilt on every poll: per-button listeners would * leak one set per tick. */ wireForeignSessions() { if (this._foreignWired) return; this._foreignWired = true; document.addEventListener('click', (event) => { const el = event.target?.closest?.('[data-foreign-action]'); if (!el) return; const action = el.dataset.foreignAction; if (action === 'adopt') { void this.adoptForeignSession(el.dataset.foreignId, el); } else if (action === 'select') { void this.selectSession(el.dataset.foreignSession); } else if (action === 'toggle-scan') { this.toggleForeignScanRemote(); } else if (action === 'rescan-wide') { this.rescanForeignWide(); } }); }, });