garage44.eu/jeroen/midas

logclone: git clone https://garage44.eu/jeroen/midas.git

.. /web/src/components/main.tsx

raw

import m, {MithrilComponent, Store} from '@garage44/mithril'
import {Alert, Button, Dialog, FieldText, NavGroup, NavItem, Shell, ThemeSwitch, Toaster, storedTheme} from '@garage44/mithril/components'
import type {Theme} from '@garage44/mithril/components'

import {Login, Setup} from '@/components/login'
import {ConfirmHost} from '@/components/confirm'
import {icon} from '@/components/icons'
import {AutopilotPage, PilotHost, reloadTemplates} from '@/components/autopilot'
import {ResearchPage, reloadTree} from '@/components/research'
import {FocusPage} from '@/components/focus'
import {waitingForYou} from '@/components/needs'
import {Sessions, sessionFooter, sessionHead, sessionInfoButton, sessionNav, sessionTitle, sessionWayButton} from '@/components/sessions'
import {fullscreenButton} from '@/components/fullscreen'
import {DesignPage, DiscussDialog, discussButton, discussPanel} from '@/components/discuss'
import {checkAvailable, restoreTalk, talk} from '@/lib/discuss'
import {checkNotify} from '@/lib/notify'
import {connect, hosted, live, reconnect} from '@/lib/stream'
import {linkSessions} from '@/lib/markdown'
import {Workspace} from '@/components/workspace'
import {Home} from '@/components/home'
import {Activity} from '@/components/activity'
import {Settings} from '@/components/settings'
import {Memory} from '@/components/memory'
import {api, callerKey, setCallerKey} from '@/lib/api'
import {toastModel} from '@/lib/actions'
import {pageChange, slidingPill} from '@/lib/motion'
import {bind, local} from '@/lib/reactive'
import {go, here} from '@/lib/route'
import {$s, checkCaller, poll} from '@/lib/store'
import type {Page} from '@/lib/store'

/** Where a person pastes a caller key (`midas hub caller add web`), to change the workspace from here. */
class KeyDialog extends MithrilComponent<{open: {value: boolean}}> {
    s = local({key: callerKey()})

    view({attrs}: m.Vnode<{open: {value: boolean}}>) {
        const save = (key: string) => {
            setCallerKey(key.trim())
            void checkCaller()
            attrs.open.value = false
        }
        return (
            <Dialog
                model={attrs.open}
                title="Caller key"
                footer={[
                    $s.hasKey ? (
                        <Button variant="ghost" onclick={() => save('')}>
                            Forget it
                        </Button>
                    ) : null,
                    <Button variant="primary" onclick={() => save(this.s.key)}>
                        Keep it in this browser
                    </Button>,
                ]}
            >
                <p>
                    Reading the workspace is open on the tunnel; changing it — draining a node, taking back a lease,
                    deploying — needs a caller key from <code>/srv/midas/callers.json</code>. Make one for this page with{' '}
                    <code>sudo midas hub caller add web</code>.
                </p>
                <FieldText model={bind(this.s, 'key')} type="password" label="key" autocomplete="off" />
            </Dialog>
        )
    }
}

/**
 * The menu (docs/mockups/site-structure): four places, each answering one question — what waits
 * for me (Home), how much do I decide and what decides for me (Steer), what is the work for
 * (Goals), what runs it and what happened (Workspace). A place's pages are its tabs. The
 * sessions are the nav's list, and a tab of their own on a phone; Settings is behind the account.
 */
interface Place {
    key: string
    label: string
    /** The pages it holds: the nav lights it on any of them. */
    pages: Page[]
    /** Where a tap on it goes. */
    to: string
    /** Its parts, as tabs over its pages: each an address, and whether the page is on it. */
    tabs?: {label: string; to: string; on: (h: string) => boolean}[]
}
const PLACES: Place[] = [
    {key: 'home', label: 'Home', pages: ['home'], to: 'home'},
    {
        key: 'steer',
        label: 'Steer',
        pages: ['focus', 'autopilot'],
        to: 'focus',
        tabs: [
            {label: 'Today', to: 'focus', on: (h) => h === 'focus' || h === 'focus/block'},
            {label: 'Week', to: 'focus/week', on: (h) => h === 'focus/week'},
            {label: 'Autopilot', to: 'autopilot', on: (h) => h === 'autopilot' || h.startsWith('autopilot/')},
            {label: 'Rules', to: 'focus/rules', on: (h) => h === 'focus/rules'},
        ],
    },
    {key: 'goals', label: 'Goals', pages: ['research'], to: 'research'},
    {
        key: 'workspace',
        label: 'Workspace',
        pages: ['workspace', 'activity', 'memory'],
        to: 'workspace',
        tabs: [
            {label: 'Machines', to: 'workspace', on: (h) => h === 'workspace' || h === 'machines'},
            {label: 'Deploys', to: 'workspace/deploys', on: (h) => h === 'workspace/deploys'},
            {label: 'Services', to: 'workspace/services', on: (h) => h === 'workspace/services'},
            {label: 'Activity', to: 'activity', on: (h) => h === 'activity' || h.startsWith('activity/') || h === 'history' || h === 'log'},
            {label: 'Memory', to: 'memory', on: (h) => h === 'memory'},
        ],
    },
]
/** The phone's tabs: the places, with the sessions second. */
const SESSIONS: Place = {key: 'sessions', label: 'Sessions', pages: ['sessions'], to: 'sessions'}
const TABS: Place[] = [PLACES[0], SESSIONS, ...PLACES.slice(1)]
const placeOf = (page: Page): Place | undefined => TABS.find((p) => p.pages.includes(page))

/** The tabs' icons, drawn rather than typed: a phone's font had no ⌂ or ▦ of the same weight. */
const svg = (...paths: m.Children[]) => (
    <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
        {paths}
    </svg>
)
const ICONS: Record<string, m.Children> = {
    home: svg(<path d="M4 11l8-7 8 7v9h-5v-6H9v6H4z" />),
    sessions: svg(<path d="M4 6h16M4 12h16M4 18h10" />),
    workspace: svg(<rect x="4" y="4" width="7" height="7" rx="2" />, <rect x="13" y="4" width="7" height="7" rx="2" />, <rect x="4" y="13" width="7" height="7" rx="2" />, <rect x="13" y="13" width="7" height="7" rx="2" />),
    steer: svg(<circle cx="12" cy="12" r="8" />, <path d="M12 12l4-4" />, <circle cx="12" cy="12" r="1" fill="currentColor" />),
    goals: svg(<circle cx="5" cy="12" r="2" />, <circle cx="19" cy="6" r="2" />, <circle cx="19" cy="18" r="2" />, <path d="M7 12h4l6-6M11 12l6 6" />),
    // Sliders, not a cog: a cog drawn this small reads as the theme switch's sun beside it.
    settings: svg(<path d="M4 7h9M17 7h3M4 17h3M11 17h9" />, <circle cx="15" cy="7" r="2" />, <circle cx="9" cy="17" r="2" />),
}

/** Where a page sits among the tabs, for which way a change slides. */
const ORDER: Page[] = ['home', 'sessions', 'focus', 'autopilot', 'research', 'workspace', 'activity', 'memory', 'more', 'settings', 'design']

/** Settings: this device's for anyone logged in; the hub's own, an admin's. */
const mayOpenSettings = () => !!$s.account || $s.role === 'admin'

/** The page a place names: `workspace`, a session's own `sessions/s3`, or an old link's page. */
function pageOf(h: string): Page | null {
    if (h === '' || h === 'home') return 'home'
    if (h === 'workspace' || h === 'workspace/deploys' || h === 'workspace/services') return 'workspace'
    if (h === 'memory' || h === 'settings' || h === 'more' || h === 'design') return h
    if (h === 'activity' || h.startsWith('activity/')) return 'activity'
    if (h === 'autopilot' || h.startsWith('autopilot/')) return 'autopilot'
    if (h === 'research' || h.startsWith('research/')) return 'research'
    if (h === 'focus' || h.startsWith('focus/')) return 'focus'
    if (h === 'sessions' || h.startsWith('sessions/')) return 'sessions'
    // Old links: the board and the messages are Home now, the machines the workspace, history and the log Activity.
    if (h === 'board' || h === 'messages') return 'home'
    if (h === 'machines') return 'workspace'
    if (h === 'history' || h === 'log') return 'activity'
    return null
}

/** In a session, or starting one: the composer has the foot of the page, and the tabs step aside. */
const inSession = () => /^sessions\/./.test(here())

/**
 * The frame, as Cartopolis's admin has it: the library's Shell, its nav panel on the left. Its
 * panels' widths are dragged (the Shell keeps them to 180–420 and 280–720 px) and kept in this
 * browser; which panels are open is not.
 */
interface Layout {
    navOpen: boolean
    navWidth: number
    contextOpen: boolean
    contextWidth: number
}
const layoutStore = new Store<Layout>({storageKey: 'midas-layout'})
layoutStore.load({navWidth: 280, contextWidth: 320}, {navOpen: false, contextOpen: window.innerWidth > 1100})
const layout = layoutStore.state as unknown as Layout

/** A width as the Shell's model, written back to the browser as it is dragged. */
function width(key: 'navWidth' | 'contextWidth'): {value: number} {
    return {
        get value() {
            return layout[key]
        },
        set value(next: number) {
            layout[key] = next
            void layoutStore.save()
        },
    }
}

export class Main extends MithrilComponent {
    theme = local({value: storedTheme() as Theme})
    keyOpen = local({value: false})
    timer = 0

    /** Go to a page or a session (`sessions/s3`); the address says where the person is. */
    go = (place: string) => {
        // Home is the page's root.
        const to = place === 'home' ? '' : place
        // The change of address draws the page (onroute), so it can slide there.
        if (to === here()) $s.tab = pageOf(to) ?? 'home'
        else go(to)
    }

    /** The place the page was last drawn for: where a change of address slides from. */
    shownPlace = here()

    onroute = () => {
        const from = this.shownPlace
        const to = here()
        this.shownPlace = to
        const p = pageOf(to)
        // Into a session slides forward, out of one back; between tabs, the way the tabs lie.
        const into = /^sessions\/./
        const before = ORDER.indexOf(pageOf(from) ?? 'home')
        const after = ORDER.indexOf(p ?? 'home')
        const direction =
            into.test(to) && !into.test(from) ? 'forward' : into.test(from) && !into.test(to) ? 'back' : after === before ? 'across' : after > before ? 'forward' : 'back'
        // Its templates and schedules as they are now, coming to the Autopilot page.
        if (p === 'autopilot' && pageOf(from) !== 'autopilot') reloadTemplates()
        if (p === 'research' && pageOf(from) !== 'research') reloadTree()
        pageChange(direction, () => {
            if (p) $s.tab = p
            // Every page shares the one scrolling column: a page opens at its top, where its
            // newest is, not where the conversation before it was scrolled to (its foot).
            // A conversation scrolls itself down.
            if (!into.test(to) && to !== from) {
                const column = document.querySelector<HTMLElement>('.m-shell__content')
                if (column) {
                    column.onscroll = null
                    delete column.dataset.height
                    column.scrollTop = 0
                }
            }
            m.redraw.sync()
        })
    }

    oninit() {
        // A session named in a message (S123, session-s3) links to it, when this hub has one by that name.
        linkSessions((id) => hosted().some((h) => h.id === id))
        const p = pageOf(here())
        if (p) $s.tab = p
        window.addEventListener('popstate', this.onroute)
        // The nav lists the sessions on every page: the stream runs whatever page is open.
        connect()
        void poll()
        void checkCaller()
        // The header's Discuss: only where the hub has an OpenAI key.
        checkAvailable()
        // A conversation open here when the page went (a reload, a phone that closed it): back, ended, to carry on.
        void restoreTalk()
        void checkNotify()
        // The live state every ten seconds while the page is in view.
        this.timer = window.setInterval(() => {
            if (document.visibilityState === 'visible') void poll()
        }, 10000)
    }

    onremove() {
        clearInterval(this.timer)
        window.removeEventListener('popstate', this.onroute)
    }

    /** Who is here: the account and its way out, or the caller key; and the theme. */
    account() {
        return (
            <div class="nav-account">
                {$s.account ? (
                    <Button
                        size="sm"
                        variant="ghost"
                        onclick={() =>
                            void api.logout().finally(() => {
                                $s.account = null
                                reconnect()
                                void checkCaller().then(poll)
                            })
                        }
                    >
                        {$s.account} · {$s.role} · Log out
                    </Button>
                ) : $s.keyFromProxy || $s.needLogin ? null : (
                    <Button size="sm" variant={$s.hasKey ? 'ghost' : 'secondary'} icon={$s.hasKey ? icon.key() : undefined} onclick={() => (this.keyOpen.value = true)}>
                        {$s.hasKey ? 'key set' : 'Caller key'}
                    </Button>
                )}
                <span class="nav-account__end">
                    {mayOpenSettings() ? (
                        <a class={`frame__icon${$s.tab === 'settings' ? ' is-on' : ''}`} href="/settings" aria-label="Settings" title="Settings">
                            {ICONS.settings}
                        </a>
                    ) : null}
                    <ThemeSwitch model={this.theme} />
                </span>
            </div>
        )
    }

    /** A phone's foot: the places and the sessions, Home with what waits for the person. Wider, the nav has them. */
    tabs(page: Page, waiting: number): m.Children {
        const at = placeOf(page)
        return (
            <nav class="tabs" aria-label="Midas" {...slidingPill}>
                <span class="seg__pill tabs__pill" aria-hidden="true" />
                {TABS.map((p) => {
                    const on = p === at
                    const badge = p.key === 'home' ? waiting : 0
                    return (
                        <a class={`tabs__tab${on ? ' is-on' : ''}`} href={p.to === 'home' ? '/' : `/${p.to}`} aria-current={on ? 'page' : undefined}>
                            <span class="tabs__icon">{ICONS[p.key]}</span>
                            {p.label}
                            {badge ? <span class="tabs__badge">{badge}</span> : null}
                        </a>
                    )
                })}
            </nav>
        )
    }

    /** A place's parts as tabs over its page: Steer's and the Workspace's. */
    placeTabs(page: Page): m.Children {
        const tabs = placeOf(page)?.tabs
        if (!tabs) return null
        const h = here()
        return (
            <nav class="place-tabs" aria-label={placeOf(page)?.label}>
                {tabs.map((t) => (
                    <a class={`place-tabs__tab${t.on(h) ? ' is-on' : ''}`} href={`/${t.to}`} aria-current={t.on(h) ? 'page' : undefined}>
                        {t.label}
                    </a>
                ))}
            </nav>
        )
    }

    /** The account, on a phone (the header's mark opens it): Settings, the theme, and who is signed in. */
    more(): m.Children {
        return (
            <div class="stack more">
                {mayOpenSettings() ? (
                    <ul class="more__list">
                        <li>
                            <a href="/settings">
                                <b>Settings</b>
                                <span class="hint">this device, and for an admin people, voice and bots</span>
                            </a>
                        </li>
                    </ul>
                ) : null}
                {this.account()}
            </div>
        )
    }

    /** The phone header's way to the account; wider, the nav's foot has it. */
    youButton(): m.Children {
        const on = $s.tab === 'more' || $s.tab === 'settings'
        return (
            <a class={`frame__icon frame__you${on ? ' is-on' : ''}`} href="/more" aria-label="Account and settings" title="Account and settings">
                <span class="frame__you-mark">{($s.account || '?').slice(0, 1).toUpperCase()}</span>
            </a>
        )
    }

    view() {
        // A setup link (`midas account add`): nothing else until it is done.
        const setup = here().match(/^setup\/([0-9a-f]+)$/)
        // Questions, permissions, sessions that will not start: the tab says so, a background one too.
        const waiting = waitingForYou().length
        document.title = waiting ? `(${waiting}) Midas hub` : 'Midas hub'
        const brand = (
            <h1 class="app__title">
                <img class="app__logo" src="/icon.svg" alt="" />
                Midas <span>hub</span>
            </h1>
        )
        // A setup link and the login: a page of their own, no frame.
        if (setup || $s.needLogin) {
            return (
                <div class="app">
                    <header class="app__head">
                        {brand}
                        {this.account()}
                    </header>
                    {setup ? <Setup token={setup[1]} /> : <Login />}
                    <Toaster model={toastModel} />
                </div>
            )
        }
        const page = $s.tab
        const content =
            page === 'sessions' ? (
                <Sessions />
            ) : page === 'workspace' ? (
                <Workspace />
            ) : page === 'activity' ? (
                <Activity />
            ) : page === 'memory' ? (
                <Memory />
            ) : page === 'autopilot' ? (
                <AutopilotPage />
            ) : page === 'research' ? (
                <ResearchPage />
            ) : page === 'focus' ? (
                <FocusPage />
            ) : page === 'settings' ? (
                <Settings />
            ) : page === 'more' ? (
                this.more()
            ) : page === 'design' ? (
                DesignPage()
            ) : (
                <Home />
            )
        const title =
            page === 'sessions'
                ? sessionTitle()
                : page === 'home'
                  ? 'Midas'
                  : page === 'design'
                    ? 'Design'
                    : page === 'settings'
                      ? 'Settings'
                      : page === 'more'
                        ? 'Account'
                        : (placeOf(page)?.label ?? 'Midas')
        const at = placeOf(page)
        return (
            <div class="app-frame">
                <Shell
                    class="midas"
                    navLabel="Midas hub"
                    navOpen={bind(layout, 'navOpen')}
                    navWidth={width('navWidth')}
                    navHeader={brand}
                    nav={[
                        <NavGroup title="">
                            {PLACES.map((p) => (
                                <NavItem key={p.key} active={p === at} onclick={() => this.go(p.to)} badge={p.key === 'home' && waiting ? waiting : undefined}>
                                    <span class="nav-place">
                                        <span class="nav-place__icon">{ICONS[p.key]}</span>
                                        {p.label}
                                    </span>
                                </NavItem>
                            ))}
                        </NavGroup>,
                        sessionNav(this.go),
                    ]}
                    navFooter={this.account()}
                    header={[
                        // On a phone, a session goes back to the list: the tabs are the composer's place there.
                        inSession() ? (
                            <a class="frame__back" href="/sessions" aria-label="Back to the sessions" title="Back to the sessions">
                                {svg(<path d="M15 5l-7 7 7 7" />)}
                            </a>
                        ) : null,
                        // A session's own: its name, and what it is doing under it; the name opens its Files and About.
                        inSession() && here() !== 'sessions/new' ? sessionHead() : <h2 class="frame__title">{title}</h2>,
                        <span class="frame__end">
                            {inSession() && here() !== 'sessions/new' ? [sessionWayButton(), sessionInfoButton()] : null}
                            {discussButton(() => (layout.contextOpen = true))}
                            {fullscreenButton()}
                            {inSession() ? null : this.youButton()}
                        </span>,
                    ]}
                    // A conversation (Discuss in the header), on any page.
                    context={talk.about ? discussPanel() : undefined}
                    contextTitle="Discussion"
                    contextOpen={bind(layout, 'contextOpen')}
                    contextWidth={width('contextWidth')}
                    footer={inSession() ? sessionFooter([discussButton(() => (layout.contextOpen = true)), fullscreenButton()]) : this.tabs(page, waiting)}
                >
                    <div class={`frame__page frame__page--${page}`}>
                        {/* What shows may be old: the stream is down. Comes in after a moment, so a quick reconnect never flashes it. */}
                        {live.loaded && !live.connected ? (
                            <div class="frame__offline" role="status">
                                Reconnecting… what shows may be out of date
                            </div>
                        ) : null}
                        {$s.error ? <Alert tone="danger">{$s.error}</Alert> : null}
                        {this.placeTabs(page)}
                        {content}
                    </div>
                </Shell>
                <KeyDialog open={this.keyOpen} />
                <DiscussDialog onstart={() => (layout.contextOpen = true)} />
                <ConfirmHost />
                <PilotHost />
                <Toaster model={toastModel} />
            </div>
        )
    }
}