garage44.eu/jeroen/midas

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

.. /web/src/components/settings.tsx

raw

import m, {MithrilComponent} from '@garage44/mithril'
import {Button, Card, FieldSelect, FieldSwitch, FieldText} from '@garage44/mithril/components'

import {Accounts} from '@/components/accounts'
import {AdminPasskey} from '@/components/admin'
import {act} from '@/lib/actions'
import {api} from '@/lib/api'
import type {AgentEntry, BotOverview, Device, DeviceCode,DiscussOverview, DiscussSettings} from '@/lib/api'
import {talk} from '@/lib/discuss'
import {checkNtfy, notify, ntfy, saveNtfy, setNotify} from '@/lib/notify'
import {age} from '@/lib/format'
import {bind, local} from '@/lib/reactive'
import {$s} from '@/lib/store'

/** A choice of the ones offered, with the one set kept among them even when the account no longer lists it. */
const choices = (offered: string[], current: string) => [...new Set([current, ...offered])].filter(Boolean).map((v) => ({value: v, label: v}))

/** The page's parts, for its headings and the row that jumps to them: the first anyone's, the rest an admin's. */
const SECTIONS = [
    {id: 'device', title: 'This device', lead: 'This browser on this device, for whoever is logged in here.'},
    {id: 'people', title: 'People', lead: 'Who logs in to this page, and what each may do.'},
    {id: 'admin', title: 'Admin', lead: "Root on the hub's machine: only in a window you allow with your passkey."},
    {id: 'voice', title: 'Voice', lead: 'Talking sessions over by voice: Discuss, in the header.'},
    {id: 'agents', title: 'Agents', lead: 'What a session runs: Claude Code, or another agent you add here.'},
    {id: 'bots', title: 'Bots', lead: 'Cartopolis accounts an AI agent speaks for.'},
]

/** A part of the page under its heading. */
const section = (id: string, ...body: m.Children[]) => {
    const it = SECTIONS.find((x) => x.id === id)!
    return (
        <section class="settings__section" id={`settings-${id}`}>
            <header class="settings__head">
                <h3>{it.title}</h3>
                <p class="hint">{it.lead}</p>
            </header>
            {body}
        </section>
    )
}

/** Jumps down the page; links would change the address, which says the page. */
const jump = () => (
    <nav class="settings__jump" aria-label="Settings">
        {SECTIONS.map((x) => (
            <button type="button" onclick={() => document.getElementById(`settings-${x.id}`)?.scrollIntoView({behavior: 'smooth', block: 'start'})}>
                {x.title}
            </button>
        ))}
    </nav>
)

/** The switch's model: reading says whether this browser is subscribed, writing subscribes or unsubscribes it. */
const notifyModel = {
    get value() {
        return notify.on
    },
    set value(on: boolean) {
        void setNotify(on)
    },
}

/** The apps paired to the hub (device.rs): a phone whose tools the sessions call, and the code that pairs one. */
class Devices extends MithrilComponent {
    s = local({list: [] as Device[], code: null as DeviceCode | null, error: ''})
    timer = 0

    oninit() {
        void this.load()
        // Online or not changes as the app opens and closes.
        this.timer = window.setInterval(() => void this.load(), 10000)
    }

    onremove() {
        window.clearInterval(this.timer)
    }

    async load() {
        try {
            this.s.list = (await api.devices()).devices
            this.s.error = ''
        } catch (e) {
            this.s.error = (e as Error).message
        }
    }

    view() {
        const {list, code} = this.s
        return (
            <Card
                title="Paired apps"
                subtitle="an app on your phone whose tools every session of yours can call while it is open: a screenshot, the camera, the sensors"
                footer={[
                    <Button variant="primary" onclick={() => act('pairing code made', async () => (this.s.code = await api.deviceCode()), {quiet: true})}>
                        Pair a device
                    </Button>,
                ]}
            >
                {this.s.error ? <p class="hint">{this.s.error}</p> : null}
                {code ? (
                    <div class="pairing">
                        {/* The app does not open `code.link` yet: typing the code is the way in. */}
                        <p>
                            In the app, open Developer tools ▸ Midas and type <strong class="pairing__code">{code.code}</strong>. Good once, for ten minutes.
                        </p>
                    </div>
                ) : null}
                {!list.length ? (
                    <p class="hint">None yet.</p>
                ) : (
                    <ul class="devices">
                        {list.map((d) => (
                            <li class="devices__row">
                                <span class={`devices__dot${d.online ? ' devices__dot--on' : ''}`} />
                                <span class="devices__name">
                                    {d.name}{' '}
                                    <span class="hint">
                                        {d.app} {d.build?.version ?? d.version} · {d.online ? 'online' : d.seen ? `seen ${age(d.seen)} ago` : 'never linked'} ·{' '}
                                        {d.tools.length} tools
                                    </span>
                                </span>
                                <Button
                                    variant="ghost"
                                    onclick={() =>
                                        act(`${d.name} forgotten`, async () => {
                                            await api.forgetDevice(d.id)
                                            await this.load()
                                        })
                                    }
                                >
                                    Forget
                                </Button>
                            </li>
                        ))}
                    </ul>
                )}
            </Card>
        )
    }
}

/** Notify this device when something needs its person: a person's, so only once logged in. */
const device = () =>
    !$s.account ? (
        <p class="hint">Log in to have this device notified.</p>
    ) : (
        [
            m(Devices),
            <Card title="Notifications" subtitle="a notification when a session asks you something or waits for your permission">
                {notify.supported ? (
                    <FieldSwitch model={notifyModel} disabled={notify.busy} label="Notify this device when something needs me" error={notify.error || null} />
                ) : (
                    <p class="hint">This browser cannot be notified; on an iPhone, add the page to the Home Screen first.</p>
                )}
            </Card>,
            <Card
                title="ntfy"
                subtitle="the same notifications through the ntfy app, for a phone whose browser has no push service (Firefox on Android without Google)"
                footer={[
                    <Button variant="ghost" disabled={!ntfy.saved || ntfy.draft !== ntfy.saved} onclick={() => act('a test sent to ntfy', () => api.testPushNtfy())}>
                        Send a test
                    </Button>,
                    <Button variant="primary" disabled={!ntfy.loaded || ntfy.draft.trim() === ntfy.saved} onclick={() => act(ntfy.draft.trim() ? 'ntfy topic saved' : 'ntfy topic removed', () => saveNtfy(ntfy.draft))}>
                        Save
                    </Button>,
                ]}
            >
                <FieldText
                    model={bind(ntfy, 'draft')}
                    label="topic"
                    placeholder="the topic you subscribed to in the ntfy app"
                    help="A name is a topic on ntfy.sh; for a server of your own, give its address, as https://ntfy.example.org/topic. Anyone who knows a topic on ntfy.sh can read it: pick a name nobody guesses. The message says only how many things wait. Empty removes it."
                    autocomplete="off"
                />
            </Card>,
        ]
    )

/**
 * The hub's settings an admin sets here: who logs in to the page
 * (accounts.tsx), talking sessions over by voice (discuss.rs): the OpenAI key, which the page can replace or remove but
 * never read back, and the realtime model, its voice and the languages.
 */
export class Settings extends MithrilComponent {
    s = local({
        overview: null as DiscussOverview | null,
        draft: null as DiscussSettings | null,
        models: {voice: [] as string[], backend: [] as string[]},
        key: '',
        error: '',
    })

    oninit() {
        void this.load()
        checkNtfy().catch(() => undefined)
    }

    async load() {
        try {
            this.show((await api.settings()).discuss)
        } catch (e) {
            this.s.error = (e as Error).message
        }
    }

    /** What the hub says now; and, with a key, the models it may use. */
    show(o: DiscussOverview) {
        this.s.overview = o
        this.s.draft = {...o.settings}
        // The Discuss button follows the key.
        talk.available = o.key.set
        if (o.key.set) {
            api.settingsModels()
                .then((r) => (this.s.models = {voice: r.voice, backend: r.backend ?? []}))
                .catch(() => (this.s.models = {voice: [], backend: []}))
        }
    }

    view() {
        // Only this device, for anyone not an admin.
        if ($s.role !== 'admin') return <div class="settings">{section('device', device())}</div>
        const {overview: o, draft: d} = this.s
        if (!o || !d) return this.s.error ? <p class="hint">{this.s.error}</p> : <p class="hint">Loading…</p>
        const changed = JSON.stringify(d) !== JSON.stringify(o.settings)
        const languages = o.languages.map((l) => ({value: l.code, label: l.name}))
        return (
            <div class="settings">
                {jump()}
                {section('device', device())}
                {section('people', <Accounts />)}
                {section('admin', <AdminPasskey />)}
                {section(
                    'voice',
                <Card
                    title="OpenAI key"
                    subtitle={o.key.set ? `set, ending in …${o.key.ends}` : 'none yet: without one, the header has no Discuss button'}
                    footer={[
                        o.key.set ? (
                            <Button variant="ghost" onclick={() => act('OpenAI key removed', async () => this.show((await api.setOpenaiKey('')).discuss))}>
                                Remove it
                            </Button>
                        ) : null,
                        <Button
                            variant="primary"
                            disabled={!this.s.key.trim()}
                            onclick={() =>
                                act('OpenAI key kept', async () => {
                                    this.show((await api.setOpenaiKey(this.s.key)).discuss)
                                    this.s.key = ''
                                })
                            }
                        >
                            {o.key.set ? 'Replace it' : 'Keep it'}
                        </Button>,
                    ]}
                >
                    <p class="hint">
                        For talking sessions over by voice, on OpenAI's realtime model. The hub keeps it beside its state, readable by its own user only, and only signs
                        calls with it: it never reaches a browser.
                    </p>
                    <p class="hint">
                        A restricted key needs: List models on Read, and under Model capabilities, Realtime on Write; Voices on Read only for a
                        custom voice. The rest can stay at None.
                    </p>
                    <FieldText model={bind(this.s, 'key')} type="password" label="key" placeholder="sk-…" autocomplete="off" />
                </Card>,
                <Card
                    title="Voice discussions"
                    subtitle="how Discuss, in the header, talks things over"
                    footer={[
                        <Button variant="ghost" disabled={!changed} onclick={() => (this.s.draft = {...o.settings})}>
                            Undo
                        </Button>,
                        <Button variant="primary" disabled={!changed} onclick={() => act('settings saved', async () => this.show((await api.setDiscuss(d)).discuss))}>
                            Save
                        </Button>,
                    ]}
                >
                    <FieldSelect
                        label="model"
                        help="GPT-Live (gpt-live-…) sounds the most like a person; a realtime model (gpt-realtime-…) runs its own tools."
                        model={bind(d, 'model')}
                        options={choices(this.s.models.voice, d.model)}
                    />
                    {d.model.startsWith('gpt-live') ? (
                        <FieldSelect
                            label="backend"
                            help="What reasons and runs the tools for GPT-Live."
                            model={bind(d, 'backend')}
                            options={choices(this.s.models.backend, d.backend)}
                        />
                    ) : null}
                    <FieldSelect label="woman's voice" model={bind(d, 'voice')} options={choices(o.voices, d.voice)} />
                    <FieldSelect
                        label="man's voice"
                        help="Each role in Discuss speaks in one of the two; you pick which when you start."
                        model={bind(d, 'male_voice')}
                        options={choices(o.voices, d.male_voice)}
                    />
                    <FieldSelect
                        label="language spoken"
                        help="Auto: the language you speak."
                        model={bind(d, 'language')}
                        options={languages}
                    />
                    <FieldSelect label="language of the brief" model={bind(d, 'brief_language')} options={languages} />
                </Card>,
                )}
                {section('agents', <Agents />)}
                {section('bots', <Bots />)}
            </div>
        )
    }
}

/**
 * The agents a session may run (agents.rs): Claude Code always, and each one
 * added here, a name and the command the sessions runner starts for it. The
 * new-session form offers them in its model choice.
 */
class Agents extends MithrilComponent {
    s = local({
        agents: null as AgentEntry[] | null,
        drafts: {} as Record<string, {name: string; command: string}>,
        adding: {id: '', name: '', command: ''},
        error: '',
    })

    oninit() {
        api.settingsAgents()
            .then((list) => this.show(list))
            .catch((e: Error) => (this.s.error = e.message))
    }

    show(list: AgentEntry[]) {
        this.s.agents = list
        this.s.drafts = Object.fromEntries(list.map((a) => [a.id, {name: a.name, command: a.command ?? ''}]))
    }

    agent(a: AgentEntry) {
        const d = this.s.drafts[a.id]
        if (!d) return null
        const changed = d.name !== a.name || d.command !== (a.command ?? '')
        return (
            <Card
                key={a.id}
                title={a.name}
                subtitle={a.id}
                footer={[
                    <Button variant="ghost" onclick={() => act(`${a.name} removed`, async () => this.show(await api.removeAgent(a.id)))}>
                        Remove
                    </Button>,
                    <Button variant="primary" disabled={!changed} onclick={() => act(`${d.name} saved`, async () => this.show(await api.setAgent(a.id, d.name, d.command)))}>
                        Save
                    </Button>,
                ]}
            >
                <FieldText model={bind(d, 'name')} label="Name" autocomplete="off" />
                <FieldText model={bind(d, 'command')} label="Command" help="run by the sessions runner, in the session's folder" autocomplete="off" />
            </Card>
        )
    }

    view() {
        const {agents, adding} = this.s
        if (!agents) return this.s.error ? <p class="hint">{this.s.error}</p> : null
        const id = adding.id.trim()
        const ready = /^[a-z0-9-]{1,32}$/.test(id) && id !== 'claude' && !agents.some((a) => a.id === id) && adding.name.trim() && adding.command.trim()
        return [
            <p key=" claude" class="hint">
                Claude Code is always there, with midas's hooks and skills; the others get the session's brief only if they take a system prompt.
            </p>,
            ...agents.filter((a) => a.id !== 'claude').map((a) => this.agent(a)),
            <Card
                key=" add"
                title="Add an agent"
                subtitle="any program that speaks the Agent Client Protocol"
                footer={[
                    <Button
                        variant="primary"
                        disabled={!ready}
                        onclick={() =>
                            act(`${adding.name.trim()} added`, async () => {
                                this.show(await api.setAgent(id, adding.name, adding.command))
                                this.s.adding = {id: '', name: '', command: ''}
                            })
                        }
                    >
                        Add
                    </Button>,
                ]}
            >
                <p class="hint">Install it on the sessions runner's machine and log it in there first: it runs with that machine's login.</p>
                <FieldText model={bind(adding, 'name')} label="Name" placeholder="Codex" autocomplete="off" />
                <FieldText model={bind(adding, 'id')} label="Id" help="lowercase letters, digits and -; what midas sessions start --agent takes" placeholder="codex" autocomplete="off" />
                <FieldText model={bind(adding, 'command')} label="Command" placeholder="bunx @zed-industries/codex-acp" autocomplete="off" />
            </Card>,
        ]
    }
}

/** What a bot's form holds: the secrets start empty, and stay as they are unless typed. */
interface BotDraft {
    server: string
    username: string
    password: string
    works_for: string
    private_only: boolean
    node: string
    brief: string
    voice: boolean
    openai_key: string
}

const draftOf = (b: BotOverview): BotDraft => ({
    server: b.server,
    username: b.username,
    password: '',
    works_for: b.works_for,
    private_only: b.private_only,
    node: b.node,
    brief: b.brief,
    voice: b.voice,
    openai_key: '',
})

/** How a run stands, in a few words for the card's subtitle. */
const RUN_WORDS: Record<BotOverview['run']['state'], string> = {
    stopped: 'not running',
    queued: 'waiting for the runner',
    starting: 'starting…',
    running: 'running',
    stopping: 'stopping…',
    failed: 'failed to start',
}

/**
 * The bots (botconfig.rs): for each, the Cartopolis account it signs in with,
 * who it works for, where it runs and whether it takes calls by voice, and a
 * Start and Stop that the sessions runner carries out. A password or key is
 * never sent back here: the form shows that one is set, and a key's last four.
 */
class Bots extends MithrilComponent {
    s = local({
        bots: null as BotOverview[] | null,
        drafts: {} as Record<string, BotDraft>,
        adding: '',
        error: '',
    })

    timer = 0

    oninit() {
        void this.load()
        // A start takes minutes (a first build); its card follows it.
        this.timer = window.setInterval(() => {
            if (this.s.bots?.some((b) => ['queued', 'starting', 'stopping'].includes(b.run.state))) void this.refresh()
        }, 5000)
    }

    onremove() {
        window.clearInterval(this.timer)
    }

    async load() {
        try {
            this.show((await api.bots()).bots)
        } catch (e) {
            this.s.error = (e as Error).message
        }
    }

    /** New run states, keeping whatever is being typed. */
    async refresh() {
        const bots = (await api.bots()).bots
        this.s.bots = bots
        m.redraw()
    }

    show(bots: BotOverview[]) {
        this.s.bots = bots
        this.s.drafts = Object.fromEntries(bots.map((b) => [b.name, draftOf(b)]))
    }

    bot(b: BotOverview) {
        const d = this.s.drafts[b.name]
        if (!d) return null
        const changed = JSON.stringify(d) !== JSON.stringify(draftOf(b))
        const busy = ['queued', 'starting', 'stopping'].includes(b.run.state)
        const up = b.run.state === 'running' || b.run.state === 'starting'
        const nodes = ($s.workspace?.nodes ?? []).map((n) => ({value: n.id, label: `${n.id} (${n.machine})`}))
        const keyHelp = b.key.own
            ? `it has its own key, ending in …${b.key.ends}; type another to replace it`
            : b.key.hub
              ? "leave empty to use the hub's OpenAI key (above); a restricted key needs Realtime on Write"
              : 'needed for voice: the hub has no OpenAI key to use instead'
        return (
            <Card
                key={b.name}
                title={b.name}
                subtitle={`${RUN_WORDS[b.run.state]}${b.voice ? ' · takes calls' : ''}`}
                footer={[
                    <Button variant="ghost" disabled={up || busy} onclick={() => act(`${b.name} removed`, async () => this.show((await api.removeBot(b.name)).bots))}>
                        Remove
                    </Button>,
                    <Button
                        variant="ghost"
                        disabled={!changed}
                        onclick={() =>
                            act(`${b.name} saved`, async () =>
                                this.show((await api.setBot({name: b.name, ...d})).bots),
                            )
                        }
                    >
                        Save
                    </Button>,
                    up ? (
                        <Button variant="primary" disabled={busy} onclick={() => act(`stopping ${b.name}`, async () => this.show((await api.stopBot(b.name)).bots))}>
                            Stop
                        </Button>
                    ) : (
                        <Button
                            variant="primary"
                            disabled={busy || changed || b.missing.length > 0}
                            onclick={() => act(`starting ${b.name}`, async () => this.show((await api.startBot(b.name)).bots))}
                        >
                            Start
                        </Button>
                    ),
                ]}
            >
                {b.run.detail ? <p class={b.run.state === 'failed' ? 'hint error' : 'hint'}>{b.run.detail}</p> : null}
                {b.missing.length > 0 ? <p class="hint">Before it can start, it needs {b.missing.join(', ')}.</p> : changed ? <p class="hint">Save before starting.</p> : null}

                <h4>Its Cartopolis account</h4>
                <FieldText
                    model={bind(d, 'server')}
                    label="Server"
                    help="the address you would type at the app's sign-in, e.g. cartopolis.org"
                    placeholder="cartopolis.org"
                    autocomplete="off"
                />
                <FieldText model={bind(d, 'username')} label="Username" help="the bot's own account on that server" autocomplete="off" />
                <FieldText
                    model={bind(d, 'password')}
                    type="password"
                    label="Password"
                    help={b.password_set ? 'set; type a new one only to change it' : "that account's password"}
                    autocomplete="new-password"
                />
                <FieldSwitch
                    model={bind(d, 'private_only')}
                    label="Talks only in private chats"
                    help="never in nearby or global chat, and no object it builds can speak"
                />

                <h4>Who it works for</h4>
                <FieldText
                    model={bind(d, 'works_for')}
                    label="Usernames"
                    help="comma-separated: the only people whose messages it reads, whose calls it answers, and who can ask it to do things"
                    placeholder="sam"
                    autocomplete="off"
                />

                <h4>Where it runs</h4>
                <FieldSelect
                    model={bind(d, 'node')}
                    label="Node"
                    help="keep it on one node: its chat keys live there, and every new node is another device of the account"
                    options={[{value: '', label: 'choose a node'}, ...nodes]}
                />
                <FieldText
                    model={bind(d, 'brief')}
                    label="Instructions file"
                    help="the agent's instructions, a file in the Cartopolis repository"
                    placeholder="tools/bot/viberfox.md"
                    autocomplete="off"
                />

                <h4>Voice</h4>
                <FieldSwitch
                    model={bind(d, 'voice')}
                    label="Takes calls"
                    help="answers calls from the people it works for and phones whoever they ask it to, with OpenAI's Realtime model"
                />
                {d.voice ? (
                    <FieldText model={bind(d, 'openai_key')} type="password" label="OpenAI key" placeholder="sk-…" help={keyHelp} autocomplete="off" />
                ) : null}
                {b.key.own ? (
                    <Button variant="ghost" onclick={() => act('its own key removed', async () => this.show((await api.setBot({name: b.name, clear_key: true})).bots))}>
                        Use the hub's key instead
                    </Button>
                ) : null}
            </Card>
        )
    }

    view() {
        const {bots} = this.s
        if (!bots) return this.s.error ? <p class="hint">{this.s.error}</p> : null
        const name = this.s.adding.trim()
        return [
            ...bots.map((b) => this.bot(b)),
            // Keyed like the bots' cards, since a fragment's vnodes all have keys or none
            // do; the space keeps it apart from any bot's name.
            <Card
                key=" add"
                title="Add a bot"
                subtitle="an account in Cartopolis that an AI agent speaks for"
                footer={[
                    <Button
                        variant="primary"
                        disabled={!/^[A-Za-z0-9_-]{1,40}$/.test(name) || bots.some((b) => b.name === name)}
                        onclick={() =>
                            act(`${name} added`, async () => {
                                this.show((await api.setBot({name})).bots)
                                this.s.adding = ''
                            })
                        }
                    >
                        Add
                    </Button>,
                ]}
            >
                <p class="hint">
                    A bot is a Cartopolis account with an agent behind it. Make the account on the Cartopolis server first (and mark it as an agent on its
                    Admin page, so callers see the badge), then add it here, fill in its card and press Start. The sessions runner builds the client from
                    main on the node you choose and starts its agent; Stop ends both.
                </p>
                <FieldText model={bind(this.s, 'adding')} label="Name" help="what midas calls it, usually the account's username" placeholder="viberfox" autocomplete="off" />
            </Card>,
        ]
    }
}