import { browse, finishMove, preflightMove, readMove, startMove, uuidv7, type Move, type MoveBinding, type TransferPreflight, type TransferRunsThere } from '../api'; import { bareHost, splitHost } from '../folderQuery'; // The one question a /cd to another host's folder asks (cli/internal/tui // cd_question.go and cd_move.go): yes moves the whole session to that // host's daemon, no moves only its kernel there, as /cd always did. Once // the target is live the move waits in its checklist: every binding still // armed here is listed, and finishing disarms them all; later leaves this // copy live until /cd or the chat's banner opens the checklist again. export const QUESTION = "Copy memory and move the agent to this machine's daemon?"; export const NOTE = "No runs only the model's python kernel remotely while its agent loop stays on this machine."; const POLL_MS = 500; export type Phase = 'asking' | 'moving' | 'checklist' | 'finishing' | 'moved' | 'failed'; export class CdQuestion { /** The folder, host:/absolute once the daemon has named it. */ target = $state(''); preflight = $state(null); /** Why the move failed, or why the preflight could not say. */ failure = $state(''); phase = $state('asking'); move = $state(null); /** The highlight; `touched` keeps it where a key put it before the preflight answered. */ yes = $state(false); /** A profile line under yes holding the highlight, counted from 1 through every pick's lines; 0 when yes or no holds it. */ option = $state(0); touched = false; /** The target profile picked for each session that needs one, sent with the move. */ profiles = $state>({}); /** Put away while the daemon goes on moving; the chat shows a status line instead. */ hidden = $state(false); #transferId = ''; #controller = new AbortController(); /** With `transferId`, opens the checklist of a move already waiting on it instead of asking. */ constructor( readonly sessionId: string, target: string, transferId?: string, ) { this.target = target; if (!transferId) { void this.#check(); return; } this.#transferId = transferId; this.phase = 'checklist'; void this.#poll(); } get host(): string { return this.preflight?.target_daemon.host || bareHost(splitHost(this.target)[0] ?? ''); } get checking(): boolean { return !this.preflight && !this.failure && this.phase === 'asking'; } get canMove(): boolean { return !!this.preflight?.available; } /** The moving sessions that run on the target only on another of its profiles, each to pick one for. */ get picks(): TransferRunsThere[] { if (!this.canMove) return []; return this.preflight!.runs_there.filter((r) => !r.ok && r.alternatives.length > 0); } /** Every pick's profile lines, in the order the box shows them. */ get options(): { session: string; profile: string }[] { return this.picks.flatMap((r) => r.alternatives.map((profile) => ({ session: r.session_id, profile }))); } /** Why yes cannot be chosen, once that is known. */ get unavailable(): string { const reason = this.preflight?.reason; const blocking = this.preflight?.runs_there.find((r) => !r.ok && !r.alternatives.length); if (reason && blocking && blocking.session_id !== this.sessionId) return `${blocking.name}: ${reason}`; return reason || this.failure || `no albedo daemon answered on ${this.host}`; } /** What yes moves: the sessions, the bytes, and where it lands. */ get facts(): string { const p = this.preflight!; const count = Math.max(1, p.sessions.length); const parts = [`${count} ${count === 1 ? 'session' : 'sessions'}`]; if (p.bytes != null) parts.push(size(p.bytes)); const home = p.target_daemon.home ? ` (${p.target_daemon.home})` : ''; return `${parts.join(', ')} with memory and work items move to ${this.host}'s daemon${home}; this machine keeps a read-only record.`; } /** What the checklist disarms, each with its status once a finish has tried it. */ get bindings(): MoveBinding[] { return this.move?.bindings ?? []; } get progress(): string { const m = this.move; let state: string = !m || m.state === 'checking' ? 'checking' : m.state; if (m?.state === 'copying' && m.progress.bytes_total > 0) state = `copying ${size(m.progress.bytes_done)} of ${size(m.progress.bytes_total)}`; return m?.reason ? `${state} ยท ${m.reason}` : state; } /** The share of the bytes copied, while the copy is under way. */ get share(): number | null { const p = this.move?.progress; if (!p || !p.bytes_total) return null; return this.move!.state === 'activating' ? 1 : Math.min(1, p.bytes_done / p.bytes_total); } /** Moves the highlight by delta through yes, the profile lines and no, wrapping round; it stays on no while yes is unavailable. */ step(delta: number) { this.touched = true; if (!this.canMove) return; const n = this.options.length + 2; const at = (((this.option || (this.yes ? 0 : n - 1)) + delta) % n + n) % n; this.yes = at === 0; this.option = at > 0 && at < n - 1 ? at : 0; } /** Runs `session` there on `profile`, and leaves the highlight on that line. */ pick(session: string, profile: string) { this.touched = true; this.profiles[session] = profile; this.yes = false; this.option = this.options.findIndex((o) => o.session === session && o.profile === profile) + 1; } /** Starts the move, or follows it again after a failure: a failed move takes a new transfer id, a failed request asks again under the same one. */ async begin() { if (!this.#transferId || this.move?.state === 'failed') { this.#transferId = uuidv7(); this.move = null; } this.phase = 'moving'; this.failure = ''; try { this.#took(await startMove(this.sessionId, this.#transferId, this.target, this.profiles)); } catch (error) { this.#failed(`could not move this session: ${message(error)}`); } } /** Disarms every binding here and finishes the move; what failed stays listed for a retry. */ async finish() { this.phase = 'finishing'; this.failure = ''; try { const move = await finishMove(this.#transferId); if (this.#controller.signal.aborted) return; this.move = move; this.phase = move.state === 'active' ? 'moved' : 'checklist'; if (move.state !== 'active') this.failure = move.error?.detail || move.error?.code || 'some bindings could not be disarmed'; } catch (error) { if (this.#controller.signal.aborted) return; this.phase = 'checklist'; this.failure = `could not finish the move: ${message(error)}`; } this.hidden = false; } /** Reads the checklist again after reading it failed. */ reread() { this.failure = ''; void this.#poll(); } close() { this.#controller.abort(); } async #check() { const signal = AbortSignal.any([this.#controller.signal, AbortSignal.timeout(30_000)]); try { const [host, path] = splitHost(this.target); if (!path.startsWith('/')) { const listed = await browse(this.target); this.target = splitHost(listed.directory)[0] ? listed.directory : `${host}:${listed.directory}`; } const preflight = await preflightMove(this.sessionId, this.target, signal); this.preflight = preflight; this.yes = preflight.available && (this.yes || !this.touched); this.option = 0; this.profiles = Object.fromEntries(this.picks.map((r) => [r.session_id, r.alternatives[0]])); } catch (error) { if (this.#controller.signal.aborted) return; this.failure = `could not check ${this.host}: ${message(error)}`; this.yes = false; } } #took(move: Move) { if (this.#controller.signal.aborted) return; this.move = move; this.target = move.target; if (move.state === 'failed') return this.#failed(move.error?.detail || move.error?.code || 'the move failed'); if (move.state === 'active' || move.state === 'checklist') { this.phase = move.state === 'active' ? 'moved' : 'checklist'; this.hidden = false; return; } setTimeout(() => this.#poll(), POLL_MS); } async #poll() { if (this.#controller.signal.aborted || (this.phase !== 'moving' && this.phase !== 'checklist')) return; try { this.#took(await readMove(this.#transferId, this.#controller.signal)); } catch (error) { if (this.#controller.signal.aborted) return; if (this.phase === 'checklist') this.failure = `could not read the checklist: ${message(error)}`; else this.#failed(`could not move this session: ${message(error)}`); } } #failed(text: string) { this.phase = 'failed'; this.hidden = false; this.failure = text; } } function message(error: unknown): string { return String((error as Error)?.message ?? error); } /** A byte count as a person reads it, as the terminal writes it. */ export function size(n: number): string { if (n < 1024) return `${n} B`; let value = n / 1024; let suffix = 'KiB'; for (const next of ['MiB', 'GiB', 'TiB']) { if (value < 1024) break; value /= 1024; suffix = next; } return `${value.toFixed(1)} ${suffix}`; }