forked from vhaudiquet/rhema-together
feat: add the multiplayer room server and client
A room is one conversation, one ssh sandbox, and one agent. Accounts create rooms; friends join through a single-use invite link and a display name; the agent speaks only through the message tool. The server is Axum and SQLite. It serves the built Nuxt client, streams room events over SSE, and runs one serialized turn loop per room with turn-level steering copied from rhema-code. The client has the chat, preview iframe, read-only file pane, xterm terminal, and presence. Preview URLs are signed wildcard hosts, and the proxy tunnels HTTP over ssh direct-tcpip. HostAgent::step remains deferred in the framework.
This commit is contained in:
1 parent
04dd63c4ca
commit
0035f4e031
69 files changed
+22501
-48
No files matched your search
@@ -0,0 +1,2 @@
|
||||
shamefully-hoist=false
|
||||
strict-peer-dependencies=false
|
||||
@@ -0,0 +1,5 @@
|
||||
<template>
|
||||
<NuxtLayout>
|
||||
<NuxtPage />
|
||||
</NuxtLayout>
|
||||
</template>
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,28 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { initials } from '~/utils/format'
|
||||
import { memberColorVar } from '~/utils/member'
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
name: string
|
||||
color?: string | null
|
||||
size?: 'sm' | 'md' | 'lg'
|
||||
offline?: boolean
|
||||
}>(),
|
||||
{ color: null, size: 'md', offline: false },
|
||||
)
|
||||
|
||||
const style = computed(() => ({ '--member': memberColorVar(props.color) }))
|
||||
const className = computed(() => ({
|
||||
'avatar-lg': props.size === 'lg',
|
||||
'avatar-sm': props.size === 'sm',
|
||||
'avatar-offline': props.offline,
|
||||
}))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<span class="avatar" :class="className" :style="style" :title="name" role="img" :aria-label="name">
|
||||
{{ initials(name) }}
|
||||
</span>
|
||||
</template>
|
||||
@@ -0,0 +1,108 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, onMounted, ref, useId } from 'vue'
|
||||
import { X } from 'lucide-vue-next'
|
||||
|
||||
const props = withDefaults(defineProps<{ title: string; description?: string; wide?: boolean }>(), {
|
||||
description: '',
|
||||
wide: false,
|
||||
})
|
||||
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const titleId = useId()
|
||||
const descId = useId()
|
||||
const panel = ref<HTMLElement | null>(null)
|
||||
let previousFocus: HTMLElement | null = null
|
||||
let previousOverflow = ''
|
||||
|
||||
function focusable(): HTMLElement[] {
|
||||
if (!panel.value) return []
|
||||
const selector = [
|
||||
'a[href]',
|
||||
'button:not([disabled])',
|
||||
'input:not([disabled]):not([type="hidden"])',
|
||||
'select:not([disabled])',
|
||||
'textarea:not([disabled])',
|
||||
'[tabindex]:not([tabindex="-1"])',
|
||||
].join(',')
|
||||
return Array.from(panel.value.querySelectorAll<HTMLElement>(selector)).filter(
|
||||
(element) => element.offsetParent !== null,
|
||||
)
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (event.key === 'Escape') {
|
||||
event.preventDefault()
|
||||
emit('close')
|
||||
return
|
||||
}
|
||||
if (event.key !== 'Tab') return
|
||||
const items = focusable()
|
||||
if (items.length === 0) {
|
||||
event.preventDefault()
|
||||
panel.value?.focus()
|
||||
return
|
||||
}
|
||||
const first = items[0]
|
||||
const last = items[items.length - 1]
|
||||
const active = document.activeElement as HTMLElement | null
|
||||
if (event.shiftKey) {
|
||||
if (active === first || !panel.value?.contains(active)) {
|
||||
event.preventDefault()
|
||||
last?.focus()
|
||||
}
|
||||
} else if (active === last || !panel.value?.contains(active)) {
|
||||
event.preventDefault()
|
||||
first?.focus()
|
||||
}
|
||||
}
|
||||
|
||||
function onBackdrop(event: MouseEvent) {
|
||||
if (event.target === event.currentTarget) emit('close')
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
previousFocus = document.activeElement as HTMLElement | null
|
||||
previousOverflow = document.body.style.overflow
|
||||
document.body.style.overflow = 'hidden'
|
||||
document.addEventListener('keydown', onKeydown)
|
||||
await nextTick()
|
||||
const preferred = panel.value?.querySelector<HTMLElement>('[autofocus]')
|
||||
const items = focusable()
|
||||
;(preferred ?? items[0] ?? panel.value)?.focus()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
document.removeEventListener('keydown', onKeydown)
|
||||
document.body.style.overflow = previousOverflow
|
||||
previousFocus?.focus?.()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Teleport to="body">
|
||||
<div class="dialog-backdrop" @mousedown="onBackdrop">
|
||||
<section
|
||||
ref="panel"
|
||||
class="dialog"
|
||||
:class="{ 'dialog-wide': wide }"
|
||||
role="dialog"
|
||||
aria-modal="true"
|
||||
:aria-labelledby="titleId"
|
||||
:aria-describedby="description ? descId : undefined"
|
||||
tabindex="-1"
|
||||
>
|
||||
<div class="dialog-head">
|
||||
<div>
|
||||
<h2 :id="titleId" class="dialog-title">{{ props.title }}</h2>
|
||||
<p v-if="description" :id="descId" class="dialog-sub">{{ description }}</p>
|
||||
</div>
|
||||
<button type="button" class="icon-btn" aria-label="Close dialog" title="Close" @click="emit('close')">
|
||||
<X :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
<slot />
|
||||
</section>
|
||||
</div>
|
||||
</Teleport>
|
||||
</template>
|
||||
@@ -0,0 +1,136 @@
|
||||
<script setup lang="ts">
|
||||
import { nextTick, onBeforeUnmount, ref } from 'vue'
|
||||
import { AtSign, Send } from 'lucide-vue-next'
|
||||
import type { Message, SendMessageResponse } from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
|
||||
const props = defineProps<{ roomId: string }>()
|
||||
const emit = defineEmits<{ sent: [message: Message]; typing: [active: boolean] }>()
|
||||
|
||||
const api = useApi()
|
||||
const text = ref('')
|
||||
const sending = ref(false)
|
||||
const error = ref('')
|
||||
const input = ref<HTMLTextAreaElement | null>(null)
|
||||
let typingTimer: number | null = null
|
||||
let typingActive = false
|
||||
|
||||
function resize() {
|
||||
const element = input.value
|
||||
if (!element) return
|
||||
element.style.height = 'auto'
|
||||
element.style.height = `${element.scrollHeight}px`
|
||||
}
|
||||
|
||||
function notifyTyping(active: boolean) {
|
||||
if (typingActive === active) return
|
||||
typingActive = active
|
||||
emit('typing', active)
|
||||
}
|
||||
|
||||
function onInput() {
|
||||
resize()
|
||||
notifyTyping(true)
|
||||
if (typingTimer !== null) window.clearTimeout(typingTimer)
|
||||
typingTimer = window.setTimeout(() => {
|
||||
typingTimer = null
|
||||
notifyTyping(false)
|
||||
}, 2000)
|
||||
}
|
||||
|
||||
function insertMention() {
|
||||
const element = input.value
|
||||
const current = text.value
|
||||
const start = element?.selectionStart ?? current.length
|
||||
const end = element?.selectionEnd ?? current.length
|
||||
const before = current.slice(0, start)
|
||||
const after = current.slice(end)
|
||||
const spacer = before.length > 0 && !/\s$/.test(before) ? ' ' : ''
|
||||
const insertion = `${spacer}@rhema `
|
||||
text.value = `${before}${insertion}${after}`
|
||||
const cursor = before.length + insertion.length
|
||||
void nextTick(() => {
|
||||
element?.focus()
|
||||
element?.setSelectionRange(cursor, cursor)
|
||||
resize()
|
||||
})
|
||||
}
|
||||
|
||||
function onKeydown(event: KeyboardEvent) {
|
||||
if (event.key !== 'Enter' || event.shiftKey || event.isComposing) return
|
||||
event.preventDefault()
|
||||
void send()
|
||||
}
|
||||
|
||||
async function send() {
|
||||
const value = text.value.trim()
|
||||
if (!value || sending.value) return
|
||||
sending.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const response = await api.post<SendMessageResponse>(`/rooms/${props.roomId}/messages`, { text: value })
|
||||
text.value = ''
|
||||
if (typingTimer !== null) {
|
||||
window.clearTimeout(typingTimer)
|
||||
typingTimer = null
|
||||
}
|
||||
notifyTyping(false)
|
||||
emit('sent', response.message)
|
||||
await nextTick()
|
||||
resize()
|
||||
input.value?.focus()
|
||||
} catch (err) {
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
sending.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (typingTimer !== null) window.clearTimeout(typingTimer)
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="composer">
|
||||
<div class="composer-inner">
|
||||
<label class="sr-only" for="room-composer">Message the room</label>
|
||||
<textarea
|
||||
id="room-composer"
|
||||
ref="input"
|
||||
v-model="text"
|
||||
class="composer-input"
|
||||
rows="1"
|
||||
placeholder="Message the room. Use @rhema to ask the agent."
|
||||
@input="onInput"
|
||||
@keydown="onKeydown"
|
||||
/>
|
||||
<div class="composer-actions">
|
||||
<span class="composer-hint">Enter sends, Shift+Enter adds a line.</span>
|
||||
<div class="composer-buttons">
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Insert @rhema mention"
|
||||
title="Insert @rhema mention"
|
||||
@click="insertMention"
|
||||
>
|
||||
<AtSign :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-primary btn-sm"
|
||||
:disabled="!text.trim() || sending"
|
||||
aria-label="Send message"
|
||||
title="Send"
|
||||
@click="send"
|
||||
>
|
||||
<Send :size="14" aria-hidden="true" />
|
||||
{{ sending ? 'Sending' : 'Send' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<p v-if="error" class="form-error composer-error" role="alert">{{ error }}</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,49 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { Message } from '~/types'
|
||||
import { fullTime, relativeTime } from '~/utils/format'
|
||||
import { memberColorVar } from '~/utils/member'
|
||||
|
||||
const props = defineProps<{ message: Message; color?: string | null }>()
|
||||
|
||||
const segments = computed(() => {
|
||||
const parts = props.message.text.split(/(@rhema\b)/gi)
|
||||
return parts
|
||||
.filter((part) => part.length > 0)
|
||||
.map((part) => ({ text: part, mention: /^@rhema$/i.test(part) }))
|
||||
})
|
||||
|
||||
const style = computed(() => ({ '--member': memberColorVar(props.color) }))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="message.author_kind === 'system'" class="msg msg-system">
|
||||
{{ message.text }}
|
||||
</div>
|
||||
|
||||
<div v-else-if="message.author_kind === 'agent'" class="msg msg-agent">
|
||||
<div class="msg-head">
|
||||
<span class="msg-agent-label">rhema</span>
|
||||
<span class="msg-time" :title="fullTime(message.created_at)">{{ relativeTime(message.created_at) }}</span>
|
||||
</div>
|
||||
<div class="msg-text">
|
||||
<template v-for="(segment, index) in segments" :key="index">
|
||||
<span v-if="segment.mention" class="mention">{{ segment.text }}</span>
|
||||
<template v-else>{{ segment.text }}</template>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-else class="msg">
|
||||
<div class="msg-head">
|
||||
<span class="msg-author member-name" :style="style">{{ message.author_name }}</span>
|
||||
<span class="msg-time" :title="fullTime(message.created_at)">{{ relativeTime(message.created_at) }}</span>
|
||||
</div>
|
||||
<div class="msg-text">
|
||||
<template v-for="(segment, index) in segments" :key="index">
|
||||
<span v-if="segment.mention" class="mention">{{ segment.text }}</span>
|
||||
<template v-else>{{ segment.text }}</template>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,190 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ChevronLeft, ChevronRight, File, Folder, Link as LinkIcon } from 'lucide-vue-next'
|
||||
import type { FileContentResponse, FileEntry, FileListResponse, GitSummaryResponse } from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
import { formatSize } from '~/utils/format'
|
||||
|
||||
const props = defineProps<{ roomId: string; roomName: string }>()
|
||||
const api = useApi()
|
||||
|
||||
const path = ref('.')
|
||||
const entries = ref<FileEntry[]>([])
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
const selected = ref<FileEntry | null>(null)
|
||||
const file = ref<FileContentResponse | null>(null)
|
||||
const fileLoading = ref(false)
|
||||
const fileError = ref('')
|
||||
|
||||
const git = ref<GitSummaryResponse | null>(null)
|
||||
const gitLoading = ref(false)
|
||||
const gitError = ref('')
|
||||
|
||||
let dirRequest = 0
|
||||
let fileRequest = 0
|
||||
|
||||
const segments = computed(() => (path.value === '.' ? [] : path.value.split('/').filter(Boolean)))
|
||||
const hasParent = computed(() => segments.value.length > 0)
|
||||
|
||||
const lineNumbers = computed(() => {
|
||||
const content = file.value?.content ?? ''
|
||||
const count = content === '' ? 1 : content.replace(/\n$/, '').split('\n').length
|
||||
return Array.from({ length: count }, (_, index) => index + 1).join('\n')
|
||||
})
|
||||
|
||||
function crumbPath(index: number) {
|
||||
return segments.value.slice(0, index + 1).join('/')
|
||||
}
|
||||
|
||||
async function loadDir(target: string) {
|
||||
const request = ++dirRequest
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const response = await api.get<FileListResponse>(`/rooms/${props.roomId}/files`, { path: target })
|
||||
if (request !== dirRequest) return
|
||||
path.value = response.path
|
||||
entries.value = response.entries
|
||||
} catch (err) {
|
||||
if (request !== dirRequest) return
|
||||
entries.value = []
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
if (request === dirRequest) loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function openFile(entry: FileEntry) {
|
||||
const request = ++fileRequest
|
||||
selected.value = entry
|
||||
file.value = null
|
||||
fileError.value = ''
|
||||
fileLoading.value = true
|
||||
try {
|
||||
const response = await api.get<FileContentResponse>(`/rooms/${props.roomId}/file`, { path: entry.path })
|
||||
if (request !== fileRequest) return
|
||||
file.value = response
|
||||
} catch (err) {
|
||||
if (request !== fileRequest) return
|
||||
fileError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
if (request === fileRequest) fileLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openEntry(entry: FileEntry) {
|
||||
if (entry.kind === 'dir') {
|
||||
selected.value = null
|
||||
file.value = null
|
||||
fileError.value = ''
|
||||
void loadDir(entry.path)
|
||||
} else {
|
||||
void openFile(entry)
|
||||
}
|
||||
}
|
||||
|
||||
function goBack() {
|
||||
const parent = segments.value.slice(0, -1).join('/')
|
||||
void loadDir(parent)
|
||||
}
|
||||
|
||||
async function loadGit() {
|
||||
gitLoading.value = true
|
||||
gitError.value = ''
|
||||
try {
|
||||
git.value = await api.get<GitSummaryResponse>(`/rooms/${props.roomId}/git`)
|
||||
} catch (err) {
|
||||
gitError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
gitLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void loadDir('')
|
||||
void loadGit()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="files-pane">
|
||||
<div class="files">
|
||||
<div class="files-browser">
|
||||
<div class="crumbs">
|
||||
<button v-if="hasParent" type="button" class="crumb-back" @click="goBack">
|
||||
<ChevronLeft :size="12" aria-hidden="true" />
|
||||
Back
|
||||
</button>
|
||||
<div class="crumbs-row">
|
||||
<button type="button" class="crumb" @click="loadDir('')">Workspace</button>
|
||||
<template v-for="(segment, index) in segments" :key="crumbPath(index)">
|
||||
<ChevronRight :size="12" class="faint" aria-hidden="true" />
|
||||
<button type="button" class="crumb" @click="loadDir(crumbPath(index))">
|
||||
{{ segment }}
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="file-list">
|
||||
<p v-if="loading" class="meta pane-pad">Loading files.</p>
|
||||
<p v-else-if="error" class="form-error pane-pad">{{ error }}</p>
|
||||
<p v-else-if="entries.length === 0" class="empty pane-pad">This folder is empty.</p>
|
||||
<template v-else>
|
||||
<button
|
||||
v-for="entry in entries"
|
||||
:key="entry.path"
|
||||
type="button"
|
||||
class="file-row"
|
||||
:class="{ active: selected?.path === entry.path }"
|
||||
:title="entry.path"
|
||||
@click="openEntry(entry)"
|
||||
>
|
||||
<Folder v-if="entry.kind === 'dir'" :size="14" aria-hidden="true" />
|
||||
<LinkIcon v-else-if="entry.kind === 'link'" :size="14" aria-hidden="true" />
|
||||
<File v-else :size="14" aria-hidden="true" />
|
||||
<span class="file-row-name">{{ entry.name }}</span>
|
||||
<span v-if="entry.kind === 'file'" class="file-row-size">{{ formatSize(entry.size) }}</span>
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="files-viewer">
|
||||
<template v-if="selected">
|
||||
<div class="viewer-head">
|
||||
<span class="viewer-path" :title="selected.path">{{ selected.path }}</span>
|
||||
<span v-if="file" class="file-row-size">{{ formatSize(file.size) }}</span>
|
||||
</div>
|
||||
|
||||
<div class="viewer-scroll">
|
||||
<p v-if="fileLoading" class="meta pane-pad-3">Reading file.</p>
|
||||
<p v-else-if="fileError" class="form-error pane-pad-3">{{ fileError }}</p>
|
||||
<p v-else-if="file?.binary" class="meta pane-pad-3">Binary file. Preview is not available.</p>
|
||||
<p v-else-if="file && file.content === ''" class="meta pane-pad-3">This file is empty.</p>
|
||||
<template v-else-if="file">
|
||||
<pre class="gutter" aria-hidden="true">{{ lineNumbers }}</pre>
|
||||
<pre class="viewer-code">{{ file.content }}</pre>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<p v-if="file?.truncated" class="meta viewer-note">
|
||||
Showing the first 400 KB.
|
||||
</p>
|
||||
</template>
|
||||
|
||||
<p v-else class="empty pane-pad-3">Select a file to read.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<details class="git-strip">
|
||||
<summary>Git status</summary>
|
||||
<p v-if="gitLoading" class="meta pane-note">Reading git status.</p>
|
||||
<p v-else-if="gitError" class="form-error pane-note">{{ gitError }}</p>
|
||||
<pre v-else-if="git?.text">{{ git.text }}</pre>
|
||||
<p v-else class="meta pane-note">No git output.</p>
|
||||
</details>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,80 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onMounted, ref } from 'vue'
|
||||
import { Check, Copy } from 'lucide-vue-next'
|
||||
import type { Invite } from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
import { formatDate } from '~/utils/format'
|
||||
import BaseDialog from '~/components/BaseDialog.vue'
|
||||
|
||||
const props = defineProps<{ roomId: string; roomName: string }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const api = useApi()
|
||||
const invite = ref<Invite | null>(null)
|
||||
const loading = ref(true)
|
||||
const error = ref('')
|
||||
const copied = ref(false)
|
||||
const linkInput = ref<HTMLInputElement | null>(null)
|
||||
|
||||
const inviteUrl = computed(() => invite.value?.url ?? '')
|
||||
|
||||
async function create() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
invite.value = await api.post<Invite>(`/rooms/${props.roomId}/invites`)
|
||||
await nextTick()
|
||||
linkInput.value?.focus()
|
||||
linkInput.value?.select()
|
||||
} catch (err) {
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function copy() {
|
||||
if (!inviteUrl.value) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(inviteUrl.value)
|
||||
copied.value = true
|
||||
window.setTimeout(() => {
|
||||
copied.value = false
|
||||
}, 1800)
|
||||
} catch {
|
||||
error.value = 'The clipboard is not available. Select the link and copy it by hand.'
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(create)
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<BaseDialog title="Invite people" @close="emit('close')">
|
||||
<p v-if="loading" class="meta">Creating the link.</p>
|
||||
<p v-else-if="error && !invite" class="form-error" role="alert">{{ error }}</p>
|
||||
|
||||
<div v-if="invite" class="form">
|
||||
<div class="field">
|
||||
<label class="field-label" for="invite-url">Invite link</label>
|
||||
<div class="key-line">
|
||||
<input id="invite-url" ref="linkInput" class="input mono" :value="inviteUrl" readonly autofocus>
|
||||
<button type="button" class="btn" aria-label="Copy invite link" title="Copy invite link" @click="copy">
|
||||
<component :is="copied ? Check : Copy" :size="14" aria-hidden="true" />
|
||||
{{ copied ? 'Copied' : 'Copy' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="form-note">
|
||||
Anyone with this link can join {{ roomName }}. It works once and expires {{ formatDate(invite.expires_at) }}.
|
||||
</p>
|
||||
|
||||
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
|
||||
</div>
|
||||
|
||||
<div class="dialog-actions">
|
||||
<button type="button" class="btn" @click="emit('close')">Done</button>
|
||||
</div>
|
||||
</BaseDialog>
|
||||
</template>
|
||||
@@ -0,0 +1,190 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useRouter } from 'vue-router'
|
||||
import type {
|
||||
CreateRoomBody,
|
||||
CreateRoomResponse,
|
||||
ProviderConfig,
|
||||
ProviderListResponse,
|
||||
SandboxListResponse,
|
||||
SandboxTarget,
|
||||
} from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
import BaseDialog from '~/components/BaseDialog.vue'
|
||||
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const api = useApi()
|
||||
const router = useRouter()
|
||||
const rooms = useRooms()
|
||||
|
||||
const providers = ref<ProviderConfig[]>([])
|
||||
const targets = ref<SandboxTarget[]>([])
|
||||
const loading = ref(true)
|
||||
const loadError = ref('')
|
||||
|
||||
const name = ref('')
|
||||
const providerId = ref('')
|
||||
const targetId = ref('')
|
||||
const workspace = ref('')
|
||||
const repoUrl = ref('')
|
||||
const model = ref('')
|
||||
|
||||
const submitting = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
const canSubmit = computed(
|
||||
() => !loading.value && !submitting.value && !!name.value.trim() && !!providerId.value && !!targetId.value,
|
||||
)
|
||||
|
||||
const missing = computed(() => {
|
||||
if (loading.value) return ''
|
||||
if (providers.value.length === 0 && targets.value.length === 0) {
|
||||
return 'Add a provider and a sandbox in settings before creating a room.'
|
||||
}
|
||||
if (providers.value.length === 0) return 'Add a provider in settings before creating a room.'
|
||||
if (targets.value.length === 0) return 'Add a sandbox in settings before creating a room.'
|
||||
return ''
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const [providerList, targetList] = await Promise.all([
|
||||
api.get<ProviderListResponse>('/provider-configs'),
|
||||
api.get<SandboxListResponse>('/sandbox-targets'),
|
||||
])
|
||||
providers.value = providerList.providers
|
||||
targets.value = targetList.targets
|
||||
providerId.value = providers.value[0]?.id ?? ''
|
||||
targetId.value = targets.value[0]?.id ?? ''
|
||||
const current = providers.value.find((provider) => provider.id === providerId.value)
|
||||
model.value = current?.model ?? ''
|
||||
} catch (err) {
|
||||
loadError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
})
|
||||
|
||||
function onProviderChange() {
|
||||
const current = providers.value.find((provider) => provider.id === providerId.value)
|
||||
if (current && !model.value.trim()) model.value = current.model
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (!canSubmit.value) return
|
||||
submitting.value = true
|
||||
error.value = ''
|
||||
const body: CreateRoomBody = {
|
||||
name: name.value.trim(),
|
||||
provider_config_id: providerId.value,
|
||||
sandbox_target_id: targetId.value,
|
||||
}
|
||||
if (workspace.value.trim()) body.workspace = workspace.value.trim()
|
||||
if (repoUrl.value.trim()) body.repo_url = repoUrl.value.trim()
|
||||
if (model.value.trim()) body.model = model.value.trim()
|
||||
try {
|
||||
const response = await api.post<CreateRoomResponse>('/rooms', body)
|
||||
await rooms.refresh()
|
||||
emit('close')
|
||||
await router.push(`/room/${response.room.id}`)
|
||||
} catch (err) {
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<BaseDialog title="New room" description="A room has one workspace, one provider, and one shared log." @close="emit('close')">
|
||||
<p v-if="loading" class="meta">Loading providers and sandboxes.</p>
|
||||
<p v-else-if="loadError" class="form-error">{{ loadError }}</p>
|
||||
|
||||
<form class="form" @submit.prevent="submit">
|
||||
<p v-if="missing" class="form-note">
|
||||
{{ missing }}
|
||||
<NuxtLink to="/settings" @click="emit('close')">Open settings</NuxtLink>
|
||||
</p>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="new-room-name">Room name</label>
|
||||
<input
|
||||
id="new-room-name"
|
||||
v-model="name"
|
||||
class="input"
|
||||
type="text"
|
||||
maxlength="60"
|
||||
autocomplete="off"
|
||||
autofocus
|
||||
required
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="new-room-provider">Provider</label>
|
||||
<select
|
||||
id="new-room-provider"
|
||||
v-model="providerId"
|
||||
class="select"
|
||||
:disabled="providers.length === 0"
|
||||
required
|
||||
@change="onProviderChange"
|
||||
>
|
||||
<option v-for="provider in providers" :key="provider.id" :value="provider.id">
|
||||
{{ provider.name }} ({{ provider.kind }})
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="new-room-sandbox">Sandbox</label>
|
||||
<select id="new-room-sandbox" v-model="targetId" class="select" :disabled="targets.length === 0" required>
|
||||
<option v-for="target in targets" :key="target.id" :value="target.id">
|
||||
{{ target.name }} ({{ target.user_name }}@{{ target.host }}:{{ target.port }})
|
||||
</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="new-room-model">Model <span class="field-optional">optional</span></label>
|
||||
<input id="new-room-model" v-model="model" class="input" type="text" autocomplete="off">
|
||||
<span class="hint">Leave this as the provider model unless the room needs another one.</span>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="new-room-workspace">Workspace <span class="field-optional">optional</span></label>
|
||||
<input
|
||||
id="new-room-workspace"
|
||||
v-model="workspace"
|
||||
class="input"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
placeholder="/root/my-project"
|
||||
>
|
||||
<span class="hint">An absolute path. Without one, the server creates a directory under the sandbox workspace root.</span>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="new-room-repo">Repository <span class="field-optional">optional</span></label>
|
||||
<input
|
||||
id="new-room-repo"
|
||||
v-model="repoUrl"
|
||||
class="input"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
placeholder="https://github.com/owner/project.git"
|
||||
>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
|
||||
|
||||
<div class="dialog-actions">
|
||||
<button type="button" class="btn btn-quiet" @click="emit('close')">Cancel</button>
|
||||
<button type="submit" class="btn btn-primary" :disabled="!canSubmit">
|
||||
{{ submitting ? 'Creating' : 'Create room' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</BaseDialog>
|
||||
</template>
|
||||
@@ -0,0 +1,105 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { Maximize2, Minimize2, X } from 'lucide-vue-next'
|
||||
|
||||
const props = defineProps<{ roomId: string }>()
|
||||
|
||||
const port = ref<number | string>(3000)
|
||||
const url = ref('')
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const fullscreen = ref(false)
|
||||
|
||||
async function load() {
|
||||
const value = Number(port.value)
|
||||
if (!Number.isInteger(value) || value < 1 || value > 65535) {
|
||||
error.value = 'Enter a port between 1 and 65535.'
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const response = await fetch(`/api/rooms/${encodeURIComponent(props.roomId)}/preview?port=${value}`, {
|
||||
credentials: 'include',
|
||||
headers: { Accept: 'application/json' },
|
||||
})
|
||||
if (response.status === 401) {
|
||||
await navigateTo('/login')
|
||||
return
|
||||
}
|
||||
const type = response.headers.get('content-type') ?? ''
|
||||
if (!type.includes('application/json')) {
|
||||
throw new Error('The server did not return a preview address.')
|
||||
}
|
||||
const body: unknown = await response.json()
|
||||
if (!response.ok) {
|
||||
const message = body && typeof body === 'object' && 'error' in body
|
||||
? String((body as { error: unknown }).error)
|
||||
: 'The preview could not be opened.'
|
||||
throw new Error(message)
|
||||
}
|
||||
if (!body || typeof body !== 'object' || typeof (body as { url?: unknown }).url !== 'string') {
|
||||
throw new Error('The server returned no preview address.')
|
||||
}
|
||||
url.value = (body as { url: string }).url
|
||||
} catch (err) {
|
||||
url.value = ''
|
||||
error.value = err instanceof Error ? err.message : 'The preview could not be opened.'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function toggleFullscreen() {
|
||||
fullscreen.value = !fullscreen.value
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="preview-wrap" :class="{ 'preview-full': fullscreen }">
|
||||
<div class="preview-bar">
|
||||
<label class="sr-only" for="preview-port">Port</label>
|
||||
<input
|
||||
id="preview-port"
|
||||
v-model.number="port"
|
||||
class="input port-field"
|
||||
type="number"
|
||||
min="1"
|
||||
max="65535"
|
||||
aria-label="Preview port"
|
||||
>
|
||||
<button type="button" class="btn btn-sm" :disabled="loading" @click="load">
|
||||
{{ loading ? 'Opening' : url ? 'Reload' : 'Go' }}
|
||||
</button>
|
||||
<div class="room-topbar-spacer" />
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
:aria-label="fullscreen ? 'Exit full screen preview' : 'Full screen preview'"
|
||||
:title="fullscreen ? 'Exit full screen' : 'Full screen'"
|
||||
@click="toggleFullscreen"
|
||||
>
|
||||
<component :is="fullscreen ? Minimize2 : Maximize2" :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
<button
|
||||
v-if="fullscreen"
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Close full screen preview"
|
||||
title="Close full screen preview"
|
||||
@click="fullscreen = false"
|
||||
>
|
||||
<X :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="preview-message form-error" role="alert">{{ error }}</p>
|
||||
|
||||
<div v-if="url" class="preview-frame-wrap">
|
||||
<iframe class="preview-frame" :src="url" :title="`Preview on port ${port}`" />
|
||||
</div>
|
||||
<p v-else-if="!error" class="preview-message">
|
||||
Enter the port the room serves and choose Go.
|
||||
</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,55 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import { Eye, FolderTree, PanelRightClose, Terminal } from 'lucide-vue-next'
|
||||
|
||||
type Tab = 'terminal' | 'preview' | 'files'
|
||||
|
||||
defineProps<{ roomId: string; roomName: string }>()
|
||||
const emit = defineEmits<{ close: [] }>()
|
||||
|
||||
const tab = ref<Tab>('files')
|
||||
const tabs: Array<{ id: Tab; label: string; icon: typeof Terminal }> = [
|
||||
{ id: 'terminal', label: 'Terminal', icon: Terminal },
|
||||
{ id: 'preview', label: 'Preview', icon: Eye },
|
||||
{ id: 'files', label: 'Files', icon: FolderTree },
|
||||
]
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside class="right-pane right-pane-overlay" aria-label="Workspace panes">
|
||||
<div class="pane-head">
|
||||
<div class="pane-tabs" role="tablist" aria-label="Workspace panels">
|
||||
<button
|
||||
v-for="item in tabs"
|
||||
:key="item.id"
|
||||
type="button"
|
||||
class="pane-tab"
|
||||
:class="{ active: tab === item.id }"
|
||||
role="tab"
|
||||
:id="`pane-tab-${item.id}`"
|
||||
:aria-selected="tab === item.id"
|
||||
aria-controls="pane-panel"
|
||||
@click="tab = item.id"
|
||||
>
|
||||
<component :is="item.icon" :size="14" aria-hidden="true" />
|
||||
{{ item.label }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Close side pane"
|
||||
title="Close side pane"
|
||||
@click="emit('close')"
|
||||
>
|
||||
<PanelRightClose :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div id="pane-panel" class="pane-body" role="tabpanel" :aria-labelledby="`pane-tab-${tab}`">
|
||||
<FilesPane v-if="tab === 'files'" :room-id="roomId" :room-name="roomName" />
|
||||
<TerminalPane v-else-if="tab === 'terminal'" :room-id="roomId" />
|
||||
<PreviewPane v-else :room-id="roomId" />
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
@@ -0,0 +1,151 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import type {
|
||||
ProviderConfig,
|
||||
ProviderListResponse,
|
||||
Room,
|
||||
UpdateRoomBody,
|
||||
UpdateRoomResponse,
|
||||
} from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
import BaseDialog from '~/components/BaseDialog.vue'
|
||||
|
||||
const props = defineProps<{ room: Room }>()
|
||||
const emit = defineEmits<{ close: []; updated: [room: Room]; archived: [] }>()
|
||||
|
||||
const api = useApi()
|
||||
|
||||
const providers = ref<ProviderConfig[]>([])
|
||||
const loadingProviders = ref(true)
|
||||
const providersError = ref('')
|
||||
|
||||
const name = ref(props.room.name)
|
||||
const providerId = ref(props.room.provider_config_id ?? '')
|
||||
const model = ref(props.room.model ?? '')
|
||||
const maxSteps = ref<number | string>(props.room.max_turn_steps)
|
||||
|
||||
const saving = ref(false)
|
||||
const error = ref('')
|
||||
const archiving = ref(false)
|
||||
const confirmingArchive = ref(false)
|
||||
const archiveError = ref('')
|
||||
|
||||
const canSave = computed(() => !saving.value && name.value.trim().length > 0)
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const list = await api.get<ProviderListResponse>('/provider-configs')
|
||||
providers.value = list.providers
|
||||
} catch (err) {
|
||||
providersError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
loadingProviders.value = false
|
||||
}
|
||||
})
|
||||
|
||||
async function save() {
|
||||
if (!canSave.value) return
|
||||
saving.value = true
|
||||
error.value = ''
|
||||
const body: UpdateRoomBody = {
|
||||
name: name.value.trim(),
|
||||
max_turn_steps: Math.min(500, Math.max(1, Math.round(Number(maxSteps.value) || 1))),
|
||||
}
|
||||
if (providerId.value) body.provider_config_id = providerId.value
|
||||
if (model.value.trim()) body.model = model.value.trim()
|
||||
try {
|
||||
const response = await api.patch<UpdateRoomResponse>(`/rooms/${props.room.id}`, body)
|
||||
emit('updated', response.room)
|
||||
emit('close')
|
||||
} catch (err) {
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function archive() {
|
||||
if (archiving.value) return
|
||||
archiving.value = true
|
||||
archiveError.value = ''
|
||||
try {
|
||||
await api.del(`/rooms/${props.room.id}`)
|
||||
emit('archived')
|
||||
emit('close')
|
||||
} catch (err) {
|
||||
archiveError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
archiving.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<BaseDialog title="Room settings" @close="emit('close')">
|
||||
<form class="form" @submit.prevent="save">
|
||||
<div class="field">
|
||||
<label class="field-label" for="room-settings-name">Name</label>
|
||||
<input id="room-settings-name" v-model="name" class="input" type="text" maxlength="60" autofocus required>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="room-settings-provider">Provider</label>
|
||||
<select id="room-settings-provider" v-model="providerId" class="select" :disabled="loadingProviders">
|
||||
<option v-if="!room.provider_config_id" value="" disabled>No provider selected</option>
|
||||
<option v-for="provider in providers" :key="provider.id" :value="provider.id">
|
||||
{{ provider.name }} ({{ provider.kind }})
|
||||
</option>
|
||||
</select>
|
||||
<span v-if="loadingProviders" class="hint">Loading providers.</span>
|
||||
<span v-else-if="providersError" class="form-error">{{ providersError }}</span>
|
||||
<span v-else-if="providers.length === 0" class="hint">
|
||||
No providers yet. <NuxtLink to="/settings">Add one in settings</NuxtLink>.
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="room-settings-model">Model</label>
|
||||
<input id="room-settings-model" v-model="model" class="input" type="text" spellcheck="false">
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="room-settings-steps">Max turn steps</label>
|
||||
<input id="room-settings-steps" v-model.number="maxSteps" class="input" type="number" min="1" max="500" required>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
|
||||
|
||||
<div class="dialog-actions">
|
||||
<button type="button" class="btn btn-quiet" @click="emit('close')">Cancel</button>
|
||||
<button type="submit" class="btn btn-primary" :disabled="!canSave">
|
||||
{{ saving ? 'Saving' : 'Save changes' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<div class="section archive-section">
|
||||
<h3 class="panel-title">Archive</h3>
|
||||
<p class="hint">
|
||||
Archiving hides the room and stops its sandbox. The log and files stay on disk.
|
||||
</p>
|
||||
<p v-if="archiveError" class="form-error" role="alert">{{ archiveError }}</p>
|
||||
<div v-if="confirmingArchive" class="confirm-line mt-2">
|
||||
<span>Archive {{ room.name }}?</span>
|
||||
<button type="button" class="btn btn-sm btn-quiet" :disabled="archiving" @click="confirmingArchive = false">
|
||||
Cancel
|
||||
</button>
|
||||
<button type="button" class="btn btn-sm btn-danger" :disabled="archiving" @click="archive">
|
||||
{{ archiving ? 'Archiving' : 'Archive room' }}
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="btn btn-danger mt-2"
|
||||
@click="confirmingArchive = true"
|
||||
>
|
||||
Archive room
|
||||
</button>
|
||||
</div>
|
||||
</BaseDialog>
|
||||
</template>
|
||||
@@ -0,0 +1,73 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { PanelRight, PanelRightClose, Settings, UserPlus } from 'lucide-vue-next'
|
||||
import type { Member } from '~/types'
|
||||
|
||||
const props = defineProps<{
|
||||
roomName: string
|
||||
members: Member[]
|
||||
onlineIds: string[]
|
||||
isOwner: boolean
|
||||
paneOpen: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{ invite: []; togglePane: []; settings: [] }>()
|
||||
|
||||
const online = computed(() => new Set(props.onlineIds))
|
||||
const visible = computed(() => props.members.slice(0, 5))
|
||||
const extra = computed(() => props.members.slice(5))
|
||||
const extraTitle = computed(() => extra.value.map((member) => member.display_name).join(', '))
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<header class="room-topbar">
|
||||
<h1 class="room-name">{{ roomName }}</h1>
|
||||
|
||||
<div class="room-topbar-spacer" />
|
||||
|
||||
<div class="presence">
|
||||
<div class="presence-avatars" aria-label="Room members">
|
||||
<AppAvatar
|
||||
v-for="member in visible"
|
||||
:key="member.id"
|
||||
:name="member.display_name"
|
||||
:color="member.color"
|
||||
:offline="!online.has(member.id)"
|
||||
size="sm"
|
||||
/>
|
||||
<span v-if="extra.length > 0" class="small muted" :title="extraTitle">+{{ extra.length }}</span>
|
||||
</div>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Invite people"
|
||||
title="Invite people"
|
||||
@click="emit('invite')"
|
||||
>
|
||||
<UserPlus :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
:aria-label="paneOpen ? 'Close side pane' : 'Open side pane'"
|
||||
:title="paneOpen ? 'Close side pane' : 'Open side pane'"
|
||||
@click="emit('togglePane')"
|
||||
>
|
||||
<component :is="paneOpen ? PanelRightClose : PanelRight" :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
|
||||
<button
|
||||
v-if="isOwner"
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Room settings"
|
||||
title="Room settings"
|
||||
@click="emit('settings')"
|
||||
>
|
||||
<Settings :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
</template>
|
||||
@@ -0,0 +1,249 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import '@xterm/xterm/css/xterm.css'
|
||||
import type { FitAddon as FitAddonInstance } from '@xterm/addon-fit'
|
||||
import type { Terminal as TerminalInstance } from '@xterm/xterm'
|
||||
|
||||
const props = defineProps<{ roomId: string }>()
|
||||
|
||||
type Status = 'connecting' | 'connected' | 'disconnected'
|
||||
|
||||
const host = ref<HTMLElement | null>(null)
|
||||
const status = ref<Status>('connecting')
|
||||
const detail = ref('')
|
||||
const exitCode = ref<number | null>(null)
|
||||
|
||||
let term: TerminalInstance | null = null
|
||||
let fit: FitAddonInstance | null = null
|
||||
let socket: WebSocket | null = null
|
||||
let observer: ResizeObserver | null = null
|
||||
let resizeFrame = 0
|
||||
let disposed = false
|
||||
|
||||
function token(name: string): string {
|
||||
return getComputedStyle(document.documentElement).getPropertyValue(name).trim()
|
||||
}
|
||||
|
||||
function terminalTheme() {
|
||||
return {
|
||||
background: token('--surface-2'),
|
||||
foreground: token('--text'),
|
||||
cursor: token('--accent'),
|
||||
cursorAccent: token('--surface-2'),
|
||||
selectionBackground: token('--accent-soft'),
|
||||
black: token('--ansi-black'),
|
||||
red: token('--ansi-red'),
|
||||
green: token('--ansi-green'),
|
||||
yellow: token('--ansi-yellow'),
|
||||
blue: token('--ansi-blue'),
|
||||
magenta: token('--ansi-magenta'),
|
||||
cyan: token('--ansi-cyan'),
|
||||
white: token('--ansi-white'),
|
||||
brightBlack: token('--ansi-bright-black'),
|
||||
brightRed: token('--ansi-bright-red'),
|
||||
brightGreen: token('--ansi-bright-green'),
|
||||
brightYellow: token('--ansi-bright-yellow'),
|
||||
brightBlue: token('--ansi-bright-blue'),
|
||||
brightMagenta: token('--ansi-bright-magenta'),
|
||||
brightCyan: token('--ansi-bright-cyan'),
|
||||
brightWhite: token('--ansi-bright-white'),
|
||||
}
|
||||
}
|
||||
|
||||
function sendResize() {
|
||||
if (!term || !socket || socket.readyState !== WebSocket.OPEN) return
|
||||
socket.send(JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows }))
|
||||
}
|
||||
|
||||
function fitTerminal() {
|
||||
if (!fit) return
|
||||
try {
|
||||
fit.fit()
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
sendResize()
|
||||
}
|
||||
|
||||
function scheduleFit() {
|
||||
if (typeof window === 'undefined') return
|
||||
if (resizeFrame) window.cancelAnimationFrame(resizeFrame)
|
||||
resizeFrame = window.requestAnimationFrame(() => {
|
||||
resizeFrame = 0
|
||||
fitTerminal()
|
||||
})
|
||||
}
|
||||
|
||||
function closeSocket() {
|
||||
if (!socket) return
|
||||
socket.onopen = null
|
||||
socket.onmessage = null
|
||||
socket.onerror = null
|
||||
socket.onclose = null
|
||||
try {
|
||||
socket.close()
|
||||
} catch {
|
||||
// Already closed.
|
||||
}
|
||||
socket = null
|
||||
}
|
||||
|
||||
function connect() {
|
||||
if (disposed) return
|
||||
closeSocket()
|
||||
term?.reset()
|
||||
status.value = 'connecting'
|
||||
detail.value = ''
|
||||
exitCode.value = null
|
||||
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
const url = `${protocol}//${window.location.host}/api/rooms/${encodeURIComponent(props.roomId)}/terminal`
|
||||
const next = new WebSocket(url)
|
||||
next.binaryType = 'arraybuffer'
|
||||
socket = next
|
||||
|
||||
next.onopen = () => {
|
||||
if (socket !== next) return
|
||||
scheduleFit()
|
||||
}
|
||||
|
||||
next.onmessage = (event) => {
|
||||
if (socket !== next) return
|
||||
if (typeof event.data === 'string') {
|
||||
try {
|
||||
const message: unknown = JSON.parse(event.data)
|
||||
if (!message || typeof message !== 'object') return
|
||||
const type = 'type' in message ? message.type : null
|
||||
if (type === 'ready') {
|
||||
status.value = 'connected'
|
||||
detail.value = ''
|
||||
sendResize()
|
||||
term?.focus()
|
||||
} else if (type === 'error') {
|
||||
status.value = 'disconnected'
|
||||
detail.value = typeof (message as { message?: unknown }).message === 'string'
|
||||
? String((message as { message: unknown }).message)
|
||||
: 'The terminal reported an error.'
|
||||
} else if (type === 'exit') {
|
||||
status.value = 'disconnected'
|
||||
const code = (message as { code?: unknown }).code
|
||||
exitCode.value = typeof code === 'number' ? code : null
|
||||
}
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if (event.data instanceof ArrayBuffer) {
|
||||
term?.write(new Uint8Array(event.data))
|
||||
} else if (event.data instanceof Blob) {
|
||||
void event.data.arrayBuffer().then((buffer) => term?.write(new Uint8Array(buffer)))
|
||||
}
|
||||
}
|
||||
|
||||
next.onerror = () => {
|
||||
if (socket !== next) return
|
||||
if (status.value !== 'disconnected') {
|
||||
status.value = 'disconnected'
|
||||
detail.value = 'The connection failed.'
|
||||
}
|
||||
}
|
||||
|
||||
next.onclose = () => {
|
||||
if (socket !== next) return
|
||||
socket = null
|
||||
if (status.value !== 'disconnected') {
|
||||
status.value = 'disconnected'
|
||||
detail.value = 'The connection closed.'
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function reconnect() {
|
||||
connect()
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await nextTick()
|
||||
const [{ Terminal }, { FitAddon }] = await Promise.all([
|
||||
import('@xterm/xterm'),
|
||||
import('@xterm/addon-fit'),
|
||||
])
|
||||
if (!host.value) return
|
||||
|
||||
term = new Terminal({
|
||||
convertEol: false,
|
||||
cursorBlink: true,
|
||||
fontFamily: getComputedStyle(document.documentElement).getPropertyValue('--font-mono').trim(),
|
||||
fontSize: Number.parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--fs-code')) || 13,
|
||||
scrollback: 3000,
|
||||
theme: terminalTheme(),
|
||||
})
|
||||
fit = new FitAddon()
|
||||
term.loadAddon(fit)
|
||||
term.open(host.value)
|
||||
term.onData((data) => {
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN) return
|
||||
socket.send(new TextEncoder().encode(data))
|
||||
})
|
||||
|
||||
observer = new ResizeObserver(() => {
|
||||
scheduleFit()
|
||||
})
|
||||
observer.observe(host.value)
|
||||
|
||||
term.focus()
|
||||
scheduleFit()
|
||||
connect()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
if (observer) {
|
||||
observer.disconnect()
|
||||
observer = null
|
||||
}
|
||||
if (resizeFrame) {
|
||||
window.cancelAnimationFrame(resizeFrame)
|
||||
resizeFrame = 0
|
||||
}
|
||||
closeSocket()
|
||||
term?.dispose()
|
||||
term = null
|
||||
fit = null
|
||||
})
|
||||
|
||||
const statusText = computed(() => {
|
||||
if (status.value === 'connected') return 'Connected'
|
||||
if (status.value === 'connecting') return 'Connecting'
|
||||
return 'Disconnected'
|
||||
})
|
||||
|
||||
function focusTerminal() {
|
||||
term?.focus()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="terminal-wrap">
|
||||
<div class="terminal-bar">
|
||||
<span class="terminal-status">
|
||||
{{ statusText }}
|
||||
<template v-if="exitCode !== null">, exit {{ exitCode }}</template>
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm"
|
||||
:disabled="status === 'connecting'"
|
||||
aria-label="Reconnect terminal"
|
||||
title="Reconnect terminal"
|
||||
@click="reconnect"
|
||||
>
|
||||
Reconnect
|
||||
</button>
|
||||
</div>
|
||||
<p v-if="detail" class="form-error pane-pad">{{ detail }}</p>
|
||||
<div ref="host" class="terminal-host" @click="focusTerminal" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,121 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import type { ToolActivity, TurnActivity } from '~/types'
|
||||
import { formatCost } from '~/utils/format'
|
||||
|
||||
const props = defineProps<{ activity: TurnActivity }>()
|
||||
|
||||
const stateLabel = computed(() => {
|
||||
switch (props.activity.status) {
|
||||
case 'running':
|
||||
return 'is working'
|
||||
case 'error':
|
||||
return 'failed'
|
||||
case 'interrupted':
|
||||
return 'stopped'
|
||||
case 'step_limit':
|
||||
return 'hit the step limit'
|
||||
case 'max_tokens':
|
||||
return 'hit the token limit'
|
||||
default:
|
||||
return 'finished'
|
||||
}
|
||||
})
|
||||
|
||||
const usageText = computed(() => {
|
||||
const usage = props.activity.usage
|
||||
if (!usage) return ''
|
||||
const parts = [
|
||||
`${usage.input_tokens.toLocaleString()} in`,
|
||||
`${usage.output_tokens.toLocaleString()} out`,
|
||||
]
|
||||
if (usage.cached_input_tokens > 0) parts.push(`${usage.cached_input_tokens.toLocaleString()} cached`)
|
||||
const cost = formatCost(usage.cost_usd)
|
||||
if (cost) parts.push(cost)
|
||||
return parts.join(', ')
|
||||
})
|
||||
|
||||
function parseArgs(raw: string): Record<string, unknown> | null {
|
||||
const trimmed = raw.trim()
|
||||
if (!trimmed.startsWith('{')) return null
|
||||
try {
|
||||
const parsed: unknown = JSON.parse(trimmed)
|
||||
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
||||
return parsed as Record<string, unknown>
|
||||
}
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
function toolSummary(tool: ToolActivity): string {
|
||||
if (!tool.args.trim()) return ''
|
||||
const parsed = parseArgs(tool.args)
|
||||
let summary = tool.args.trim()
|
||||
if (parsed) {
|
||||
summary = JSON.stringify(parsed)
|
||||
for (const key of ['command', 'cmd', 'path', 'file_path', 'pattern', 'url', 'query']) {
|
||||
const value = parsed[key]
|
||||
if (typeof value === 'string' && value.trim()) {
|
||||
summary = value.trim()
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return summary.length > 240 ? `${summary.slice(0, 240)}...` : summary
|
||||
}
|
||||
|
||||
function outputText(tool: ToolActivity): string {
|
||||
return tool.content ?? tool.output
|
||||
}
|
||||
|
||||
function toolLabel(tool: ToolActivity): string {
|
||||
return tool.name || 'tool'
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="activity">
|
||||
<div class="activity-head">
|
||||
<div class="row">
|
||||
<span class="activity-label">rhema</span>
|
||||
<span class="activity-steps">{{ stateLabel }}</span>
|
||||
</div>
|
||||
<span v-if="activity.steps > 0" class="activity-state">
|
||||
{{ activity.steps }} {{ activity.steps === 1 ? 'step' : 'steps' }}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<details v-if="activity.thinking" class="activity-draft">
|
||||
<summary>thinking</summary>
|
||||
<div>{{ activity.thinking }}</div>
|
||||
</details>
|
||||
|
||||
<details v-if="activity.text" class="activity-draft">
|
||||
<summary>draft</summary>
|
||||
<div>{{ activity.text }}</div>
|
||||
</details>
|
||||
|
||||
<div v-for="tool in activity.tools" :key="tool.call_id" class="tool">
|
||||
<div class="tool-head">
|
||||
<span class="tool-name">{{ toolLabel(tool) }}</span>
|
||||
<span v-if="tool.isError" class="tool-state tool-error">failed</span>
|
||||
<span v-else-if="tool.done && tool.code !== null" class="tool-state">exit {{ tool.code }}</span>
|
||||
<span v-else-if="!tool.done" class="tool-state">running</span>
|
||||
<span v-else class="tool-state">done</span>
|
||||
</div>
|
||||
<div v-if="toolSummary(tool)" class="tool-args">{{ toolSummary(tool) }}</div>
|
||||
<details v-if="tool.done && outputText(tool)">
|
||||
<summary>output</summary>
|
||||
<pre class="code-block tool-output">{{ outputText(tool) }}</pre>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<div v-if="activity.status === 'error' && activity.error" class="activity-error">{{ activity.error }}</div>
|
||||
|
||||
<div v-if="usageText" class="activity-foot">
|
||||
<span>{{ usageText }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,52 @@
|
||||
import { ApiRequestError, normalizeApiError } from '~/utils/errors'
|
||||
|
||||
type ApiMethod = 'GET' | 'POST' | 'PATCH' | 'DELETE'
|
||||
|
||||
interface RequestOptions {
|
||||
method?: ApiMethod
|
||||
body?: unknown
|
||||
query?: Record<string, string | number | boolean | undefined>
|
||||
}
|
||||
|
||||
const PUBLIC_PREFIXES = ['/setup', '/login', '/register', '/join']
|
||||
|
||||
export function useApi() {
|
||||
const router = useRouter()
|
||||
const route = useRoute()
|
||||
const csrf = useCookie<string | null>('together_csrf', { sameSite: 'lax' })
|
||||
|
||||
function mayRedirect() {
|
||||
return !PUBLIC_PREFIXES.some((prefix) => route.path === prefix || route.path.startsWith(`${prefix}/`))
|
||||
}
|
||||
|
||||
async function request<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
const method = options.method ?? 'GET'
|
||||
const headers: Record<string, string> = { Accept: 'application/json' }
|
||||
if (method !== 'GET' && csrf.value) headers['X-CSRF-Token'] = csrf.value
|
||||
try {
|
||||
return await $fetch<T>(path, {
|
||||
baseURL: '/api',
|
||||
method,
|
||||
body: options.body as Record<string, unknown> | undefined,
|
||||
query: options.query,
|
||||
headers,
|
||||
credentials: 'include',
|
||||
retry: 0,
|
||||
})
|
||||
} catch (error) {
|
||||
const failure = normalizeApiError(error)
|
||||
if (failure.status === 401 && mayRedirect()) {
|
||||
void router.replace('/login')
|
||||
}
|
||||
throw failure
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
get: <T>(path: string, query?: RequestOptions['query']) => request<T>(path, { query }),
|
||||
post: <T>(path: string, body?: unknown) => request<T>(path, { method: 'POST', body }),
|
||||
patch: <T>(path: string, body?: unknown) => request<T>(path, { method: 'PATCH', body }),
|
||||
del: <T>(path: string) => request<T>(path, { method: 'DELETE' }),
|
||||
ApiRequestError,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
import type { RoomListResponse, RoomSummary } from '~/types'
|
||||
|
||||
export function useRooms() {
|
||||
const api = useApi()
|
||||
const rooms = useState<RoomSummary[]>('rooms', () => [])
|
||||
const loading = useState<boolean>('rooms-loading', () => false)
|
||||
const error = useState<string | null>('rooms-error', () => null)
|
||||
const creating = useState<boolean>('room-dialog-open', () => false)
|
||||
|
||||
async function refresh() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
const response = await api.get<RoomListResponse>('/rooms')
|
||||
rooms.value = response.rooms
|
||||
} catch (err) {
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function openCreate() {
|
||||
creating.value = true
|
||||
}
|
||||
|
||||
function closeCreate() {
|
||||
creating.value = false
|
||||
}
|
||||
|
||||
function touch(room: RoomSummary) {
|
||||
rooms.value = [room, ...rooms.value.filter((item) => item.id !== room.id)]
|
||||
}
|
||||
|
||||
return { rooms, loading, error, creating, refresh, openCreate, closeCreate, touch }
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import type { BootstrapResponse, User } from '~/types'
|
||||
|
||||
interface SessionState {
|
||||
loaded: boolean
|
||||
needsSetup: boolean
|
||||
user: User | null
|
||||
allowRegistration: boolean
|
||||
publicUrl: string
|
||||
previewOrigin: string
|
||||
}
|
||||
|
||||
let inflight: Promise<SessionState> | null = null
|
||||
|
||||
export function useSession() {
|
||||
const state = useState<SessionState>('session', () => ({
|
||||
loaded: false,
|
||||
needsSetup: false,
|
||||
user: null,
|
||||
allowRegistration: false,
|
||||
publicUrl: '',
|
||||
previewOrigin: '',
|
||||
}))
|
||||
const api = useApi()
|
||||
|
||||
function apply(boot: BootstrapResponse) {
|
||||
state.value = {
|
||||
loaded: true,
|
||||
needsSetup: boot.needs_setup,
|
||||
user: boot.user,
|
||||
allowRegistration: boot.allow_registration,
|
||||
publicUrl: boot.public_url,
|
||||
previewOrigin: boot.preview_origin,
|
||||
}
|
||||
return state.value
|
||||
}
|
||||
|
||||
async function load(force = false): Promise<SessionState> {
|
||||
if (state.value.loaded && !force) return state.value
|
||||
if (!inflight) {
|
||||
inflight = api
|
||||
.get<BootstrapResponse>('/bootstrap')
|
||||
.then((boot) => apply(boot))
|
||||
.finally(() => {
|
||||
inflight = null
|
||||
})
|
||||
}
|
||||
return inflight
|
||||
}
|
||||
|
||||
async function signOut() {
|
||||
try {
|
||||
await api.post('/logout')
|
||||
} catch {
|
||||
// The cookie is cleared server-side when the session is still valid.
|
||||
}
|
||||
state.value = { ...state.value, user: null }
|
||||
await navigateTo('/login')
|
||||
}
|
||||
|
||||
return {
|
||||
session: state,
|
||||
user: computed(() => state.value.user),
|
||||
load,
|
||||
signOut,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<template>
|
||||
<div class="auth-shell">
|
||||
<div class="auth-panel">
|
||||
<NuxtLink to="/" class="auth-brand">
|
||||
<span class="sidebar-brand-mark" aria-hidden="true">r</span>
|
||||
<span>rhema together</span>
|
||||
</NuxtLink>
|
||||
<slot />
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,94 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, watch } from 'vue'
|
||||
import { LogOut, Plus, Settings } from 'lucide-vue-next'
|
||||
|
||||
const { user, signOut, session } = useSession()
|
||||
const {
|
||||
rooms: roomList,
|
||||
loading: roomsLoading,
|
||||
error: roomsError,
|
||||
creating,
|
||||
openCreate,
|
||||
closeCreate,
|
||||
refresh: refreshRooms,
|
||||
} = useRooms()
|
||||
|
||||
onMounted(() => {
|
||||
if (session.value.loaded && user.value) void refreshRooms()
|
||||
})
|
||||
|
||||
watch(user, (current) => {
|
||||
if (current) void refreshRooms()
|
||||
})
|
||||
|
||||
async function onSignOut() {
|
||||
await signOut()
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="app-shell">
|
||||
<aside class="sidebar">
|
||||
<div class="sidebar-top">
|
||||
<NuxtLink to="/rooms" class="sidebar-brand">
|
||||
<span class="sidebar-brand-mark" aria-hidden="true">r</span>
|
||||
<span>rhema together</span>
|
||||
</NuxtLink>
|
||||
</div>
|
||||
|
||||
<div class="sidebar-label">
|
||||
<span>Rooms</span>
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="New room"
|
||||
title="New room"
|
||||
@click="openCreate()"
|
||||
>
|
||||
<Plus :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<nav class="sidebar-rooms" aria-label="Rooms">
|
||||
<p v-if="roomsLoading && roomList.length === 0" class="sidebar-room muted">Loading rooms.</p>
|
||||
<p v-else-if="roomsError" class="sidebar-room muted">{{ roomsError }}</p>
|
||||
<p v-else-if="roomList.length === 0" class="sidebar-room muted">No rooms yet.</p>
|
||||
<NuxtLink
|
||||
v-for="room in roomList"
|
||||
:key="room.id"
|
||||
:to="`/room/${room.id}`"
|
||||
class="sidebar-room"
|
||||
:title="room.name"
|
||||
>
|
||||
{{ room.name }}
|
||||
</NuxtLink>
|
||||
</nav>
|
||||
|
||||
<div class="sidebar-bottom">
|
||||
<NuxtLink to="/settings" class="sidebar-link">
|
||||
<Settings :size="16" aria-hidden="true" />
|
||||
<span>Settings</span>
|
||||
</NuxtLink>
|
||||
<div class="sidebar-account">
|
||||
<AppAvatar v-if="user" :name="user.display_name" color="var(--member-1)" size="sm" />
|
||||
<span class="sidebar-account-name" :title="user?.handle">{{ user?.display_name }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Sign out"
|
||||
title="Sign out"
|
||||
@click="onSignOut"
|
||||
>
|
||||
<LogOut :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<div class="main">
|
||||
<slot />
|
||||
</div>
|
||||
|
||||
<NewRoomDialog v-if="creating" @close="closeCreate()" />
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,28 @@
|
||||
const PUBLIC_PATHS = ['/setup', '/login', '/register', '/join']
|
||||
|
||||
function isPublic(path: string) {
|
||||
return PUBLIC_PATHS.some((prefix) => path === prefix || path.startsWith(`${prefix}/`))
|
||||
}
|
||||
|
||||
export default defineNuxtRouteMiddleware(async (to) => {
|
||||
const { load, session } = useSession()
|
||||
try {
|
||||
await load()
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
const state = session.value
|
||||
if (state.needsSetup) {
|
||||
return to.path === '/setup' ? undefined : navigateTo('/setup')
|
||||
}
|
||||
if (to.path === '/setup') {
|
||||
return navigateTo(state.user ? '/rooms' : '/login')
|
||||
}
|
||||
if (!state.user && !isPublic(to.path)) {
|
||||
return navigateTo('/login')
|
||||
}
|
||||
if (state.user && (to.path === '/login' || to.path === '/register')) {
|
||||
return navigateTo('/rooms')
|
||||
}
|
||||
return undefined
|
||||
})
|
||||
@@ -0,0 +1,11 @@
|
||||
<script setup lang="ts">
|
||||
onMounted(() => {
|
||||
void navigateTo('/rooms', { replace: true })
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<p class="meta">Opening rooms.</p>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,100 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import type { InvitePreview, JoinResponse } from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
import { formatDate } from '~/utils/format'
|
||||
|
||||
definePageMeta({ layout: 'auth' })
|
||||
useHead({ title: 'Join a room · rhema together' })
|
||||
|
||||
const route = useRoute()
|
||||
const api = useApi()
|
||||
const { session, load } = useSession()
|
||||
|
||||
const token = computed(() => String(route.params.token ?? ''))
|
||||
const invite = ref<InvitePreview | null>(null)
|
||||
const loading = ref(true)
|
||||
const loadError = ref('')
|
||||
const displayName = ref('')
|
||||
const submitting = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
onMounted(async () => {
|
||||
displayName.value = session.value.user?.display_name ?? ''
|
||||
try {
|
||||
invite.value = await api.get<InvitePreview>(`/invites/${encodeURIComponent(token.value)}`)
|
||||
} catch (err) {
|
||||
loadError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
})
|
||||
|
||||
async function submit() {
|
||||
if (submitting.value || !invite.value) return
|
||||
submitting.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const name = session.value.user?.display_name || displayName.value.trim()
|
||||
const response = await api.post<JoinResponse>(`/invites/${encodeURIComponent(token.value)}`, {
|
||||
display_name: name,
|
||||
})
|
||||
await load(true)
|
||||
await navigateTo(`/room/${response.room_id}`, { replace: true })
|
||||
} catch (err) {
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<template v-if="loading">
|
||||
<p class="meta">Checking the invite.</p>
|
||||
</template>
|
||||
|
||||
<template v-else-if="loadError">
|
||||
<h1 class="auth-title">Invite</h1>
|
||||
<p class="form-error" role="alert">{{ loadError }}</p>
|
||||
<div class="auth-footer">
|
||||
<NuxtLink to="/login">Sign in</NuxtLink> if you already have an account.
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template v-else-if="invite">
|
||||
<h1 class="auth-title">Join {{ invite.room_name }}</h1>
|
||||
<p class="auth-note">
|
||||
Owned by {{ invite.owner }}. The link works once and expires {{ formatDate(invite.expires_at) }}.
|
||||
</p>
|
||||
|
||||
<form class="form" @submit.prevent="submit">
|
||||
<p v-if="session.user" class="form-note">Joining as {{ session.user.display_name }}.</p>
|
||||
<div v-else class="field">
|
||||
<label class="field-label" for="join-name">Display name</label>
|
||||
<input
|
||||
id="join-name"
|
||||
v-model="displayName"
|
||||
class="input"
|
||||
type="text"
|
||||
autocomplete="name"
|
||||
autofocus
|
||||
required
|
||||
>
|
||||
<span class="hint">This is how the room sees you. You can add an account later.</span>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
|
||||
|
||||
<button type="submit" class="btn btn-primary" :disabled="submitting || (!session.user && !displayName.trim())">
|
||||
{{ submitting ? 'Joining' : 'Join room' }}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div v-if="session.user" class="auth-footer">
|
||||
<NuxtLink to="/rooms">Back to rooms</NuxtLink>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,84 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import type { User } from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
|
||||
definePageMeta({ layout: 'auth' })
|
||||
useHead({ title: 'Sign in · rhema together' })
|
||||
|
||||
const api = useApi()
|
||||
const { session, load } = useSession()
|
||||
|
||||
const identifier = ref('')
|
||||
const password = ref('')
|
||||
const submitting = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
async function submit() {
|
||||
if (submitting.value) return
|
||||
submitting.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await api.post<User>('/login', {
|
||||
identifier: identifier.value.trim(),
|
||||
password: password.value,
|
||||
})
|
||||
await load(true)
|
||||
await navigateTo('/rooms', { replace: true })
|
||||
} catch (err) {
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1 class="auth-title">Sign in</h1>
|
||||
<p class="auth-note">Use your handle or email.</p>
|
||||
|
||||
<form class="form" @submit.prevent="submit">
|
||||
<div class="field">
|
||||
<label class="field-label" for="login-identifier">Handle or email</label>
|
||||
<input
|
||||
id="login-identifier"
|
||||
v-model="identifier"
|
||||
class="input"
|
||||
type="text"
|
||||
autocomplete="username"
|
||||
spellcheck="false"
|
||||
autofocus
|
||||
required
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="login-password">Password</label>
|
||||
<input
|
||||
id="login-password"
|
||||
v-model="password"
|
||||
class="input"
|
||||
type="password"
|
||||
autocomplete="current-password"
|
||||
required
|
||||
>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
|
||||
|
||||
<button type="submit" class="btn btn-primary" :disabled="submitting">
|
||||
{{ submitting ? 'Signing in' : 'Sign in' }}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="auth-footer">
|
||||
<template v-if="session.allowRegistration">
|
||||
No account yet? <NuxtLink to="/register">Register</NuxtLink>
|
||||
</template>
|
||||
<template v-else>
|
||||
Registration is closed. Ask a room owner for an invite link.
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,110 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue'
|
||||
import type { User } from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
|
||||
definePageMeta({ layout: 'auth' })
|
||||
useHead({ title: 'Register · rhema together' })
|
||||
|
||||
const api = useApi()
|
||||
const { session, load } = useSession()
|
||||
|
||||
const displayName = ref('')
|
||||
const handle = ref('')
|
||||
const email = ref('')
|
||||
const password = ref('')
|
||||
const submitting = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
async function submit() {
|
||||
if (submitting.value) return
|
||||
submitting.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await api.post<User>('/register', {
|
||||
display_name: displayName.value.trim(),
|
||||
handle: handle.value.trim().toLowerCase(),
|
||||
email: email.value.trim() || null,
|
||||
password: password.value,
|
||||
})
|
||||
await load(true)
|
||||
await navigateTo('/rooms', { replace: true })
|
||||
} catch (err) {
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1 class="auth-title">Register</h1>
|
||||
<p class="auth-note">Create an account for this server.</p>
|
||||
|
||||
<p v-if="!session.allowRegistration" class="empty">
|
||||
Registration is closed. Ask a room owner for an invite link.
|
||||
</p>
|
||||
|
||||
<form v-else class="form" @submit.prevent="submit">
|
||||
<div class="field">
|
||||
<label class="field-label" for="register-name">Display name</label>
|
||||
<input
|
||||
id="register-name"
|
||||
v-model="displayName"
|
||||
class="input"
|
||||
type="text"
|
||||
autocomplete="name"
|
||||
autofocus
|
||||
required
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="register-handle">Handle</label>
|
||||
<input
|
||||
id="register-handle"
|
||||
v-model="handle"
|
||||
class="input"
|
||||
type="text"
|
||||
autocomplete="username"
|
||||
spellcheck="false"
|
||||
pattern="[A-Za-z0-9_-]{3,32}"
|
||||
minlength="3"
|
||||
maxlength="32"
|
||||
required
|
||||
>
|
||||
<span class="hint">3 to 32 lowercase letters, digits, _ or -.</span>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="register-email">Email <span class="field-optional">optional</span></label>
|
||||
<input id="register-email" v-model="email" class="input" type="email" autocomplete="email">
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="register-password">Password</label>
|
||||
<input
|
||||
id="register-password"
|
||||
v-model="password"
|
||||
class="input"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
minlength="8"
|
||||
required
|
||||
>
|
||||
<span class="hint">At least 8 characters.</span>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
|
||||
|
||||
<button type="submit" class="btn btn-primary" :disabled="submitting">
|
||||
{{ submitting ? 'Creating the account' : 'Create account' }}
|
||||
</button>
|
||||
</form>
|
||||
|
||||
<div class="auth-footer">
|
||||
Already have an account? <NuxtLink to="/login">Sign in</NuxtLink>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,707 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, nextTick, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import type {
|
||||
DeltaData,
|
||||
Envelope,
|
||||
Message,
|
||||
MessagePage,
|
||||
NoticeData,
|
||||
PresencePeer,
|
||||
Room,
|
||||
RoomDetailResponse,
|
||||
StepStartData,
|
||||
TimelineEntry,
|
||||
ToolArgsData,
|
||||
ToolOutputData,
|
||||
ToolResultData,
|
||||
ToolStartData,
|
||||
TurnActivity,
|
||||
TurnEndData,
|
||||
TurnStartData,
|
||||
UsageEventData,
|
||||
} from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
|
||||
definePageMeta({ key: (route) => route.fullPath })
|
||||
|
||||
const route = useRoute()
|
||||
const api = useApi()
|
||||
const { session } = useSession()
|
||||
const rooms = useRooms()
|
||||
|
||||
const roomId = computed(() => String(route.params.id ?? ''))
|
||||
|
||||
const detail = ref<RoomDetailResponse | null>(null)
|
||||
const detailLoading = ref(true)
|
||||
const detailError = ref('')
|
||||
|
||||
const messages = ref<Message[]>([])
|
||||
const notices = ref<Array<{ seq: number; level: string; text: string }>>([])
|
||||
const activities = ref<TurnActivity[]>([])
|
||||
const messagesLoading = ref(true)
|
||||
const messagesError = ref('')
|
||||
const hasMore = ref(false)
|
||||
const loadingOlder = ref(false)
|
||||
|
||||
const chatScroll = ref<HTMLElement | null>(null)
|
||||
const chatInner = ref<HTMLElement | null>(null)
|
||||
const stick = ref(true)
|
||||
const newMessages = ref(0)
|
||||
|
||||
const streamState = ref<'connecting' | 'live' | 'disconnected'>('connecting')
|
||||
const streamError = ref('')
|
||||
const peers = ref<PresencePeer[]>([])
|
||||
const onlineIds = ref<string[]>([])
|
||||
const typingActive = ref(false)
|
||||
|
||||
const paneOpen = ref(typeof window === 'undefined' ? true : !window.matchMedia('(max-width: 1099px)').matches)
|
||||
const inviteOpen = ref(false)
|
||||
const settingsOpen = ref(false)
|
||||
|
||||
const seenMessages = new Set<number>()
|
||||
const seenNotices = new Set<number>()
|
||||
let lastDurable = 0
|
||||
let disposed = false
|
||||
|
||||
let eventController: AbortController | null = null
|
||||
let eventGeneration = 0
|
||||
let retryIndex = 0
|
||||
let reconnectTimer: number | null = null
|
||||
|
||||
let chatObserver: ResizeObserver | null = null
|
||||
let suspendAutoScroll = false
|
||||
|
||||
let presenceSocket: WebSocket | null = null
|
||||
let presenceTimer: number | null = null
|
||||
let presenceRetry = 0
|
||||
|
||||
const DURABLE_KINDS = new Set(['message', 'notice', 'turn_start', 'turn_end', 'tool_result'])
|
||||
const BACKOFF = [1000, 2000, 5000, 10000]
|
||||
|
||||
useHead({
|
||||
title: computed(() => `${detail.value?.room.name ?? 'Room'} · rhema together`),
|
||||
})
|
||||
|
||||
const isOwner = computed(
|
||||
() => !!detail.value && detail.value.room.owner_id === session.value.user?.id,
|
||||
)
|
||||
|
||||
const memberById = computed(() => {
|
||||
const map = new Map<string, { color: string }>()
|
||||
for (const member of detail.value?.members ?? []) map.set(member.id, member)
|
||||
return map
|
||||
})
|
||||
|
||||
const timeline = computed<TimelineEntry[]>(() => {
|
||||
const entries: TimelineEntry[] = []
|
||||
for (const message of messages.value) {
|
||||
entries.push({ kind: 'message', seq: message.seq, message })
|
||||
}
|
||||
for (const notice of notices.value) {
|
||||
entries.push({ kind: 'notice', seq: notice.seq, level: notice.level, text: notice.text })
|
||||
}
|
||||
for (const activity of activities.value) {
|
||||
entries.push({ kind: 'turn', seq: activity.seq, activity })
|
||||
}
|
||||
return entries.sort((a, b) => a.seq - b.seq)
|
||||
})
|
||||
|
||||
const typingText = computed(() => {
|
||||
const me = detail.value?.me.id
|
||||
const names = peers.value
|
||||
.filter((peer) => peer.member_id !== me && peer.state?.typing === true)
|
||||
.map((peer) => peer.display_name)
|
||||
if (names.length === 0) return ''
|
||||
if (names.length === 1) return `${names[0]} is typing`
|
||||
if (names.length === 2) return `${names[0]} and ${names[1]} are typing`
|
||||
return 'Several people are typing'
|
||||
})
|
||||
|
||||
function eventData<T>(envelope: Envelope): T {
|
||||
return envelope.data as unknown as T
|
||||
}
|
||||
|
||||
function findActivity(turnId: string): TurnActivity | undefined {
|
||||
return activities.value.find((activity) => activity.turnId === turnId)
|
||||
}
|
||||
|
||||
function ensureActivity(turnId: string, seq: number): TurnActivity {
|
||||
const existing = findActivity(turnId)
|
||||
if (existing) return existing
|
||||
const created: TurnActivity = {
|
||||
turnId,
|
||||
seq: Number.isFinite(seq) ? seq : lastDurable,
|
||||
startedAt: Date.now(),
|
||||
text: '',
|
||||
thinking: '',
|
||||
steps: 0,
|
||||
tools: [],
|
||||
usage: null,
|
||||
status: 'running',
|
||||
error: '',
|
||||
}
|
||||
activities.value.push(created)
|
||||
return created
|
||||
}
|
||||
|
||||
function addMessage(message: Message, quiet = false) {
|
||||
if (seenMessages.has(message.seq)) return
|
||||
seenMessages.add(message.seq)
|
||||
const index = messages.value.findIndex((item) => item.seq > message.seq)
|
||||
if (index === -1) messages.value.push(message)
|
||||
else messages.value.splice(index, 0, message)
|
||||
if (!quiet) {
|
||||
if (stick.value) {
|
||||
void nextTick(() => {
|
||||
if (stick.value) scrollToBottom()
|
||||
})
|
||||
} else {
|
||||
newMessages.value += 1
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function addNotice(seq: number, level: string, text: string) {
|
||||
if (seenNotices.has(seq)) return
|
||||
seenNotices.add(seq)
|
||||
notices.value.push({ seq, level, text })
|
||||
}
|
||||
|
||||
function handleEnvelope(envelope: Envelope) {
|
||||
if (DURABLE_KINDS.has(envelope.kind)) {
|
||||
lastDurable = Math.max(lastDurable, envelope.seq)
|
||||
}
|
||||
|
||||
switch (envelope.kind) {
|
||||
case 'message':
|
||||
addMessage(eventData<Message>(envelope))
|
||||
break
|
||||
case 'notice': {
|
||||
const data = eventData<NoticeData>(envelope)
|
||||
addNotice(envelope.seq, data.level, data.text)
|
||||
break
|
||||
}
|
||||
case 'turn_start': {
|
||||
const data = eventData<TurnStartData>(envelope)
|
||||
if (!findActivity(data.turn_id)) {
|
||||
const activity = ensureActivity(data.turn_id, envelope.seq)
|
||||
activity.startedAt = data.at || Date.now()
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'text_delta': {
|
||||
const data = eventData<DeltaData>(envelope)
|
||||
ensureActivity(data.turn_id, lastDurable).text += data.delta
|
||||
break
|
||||
}
|
||||
case 'thinking_delta': {
|
||||
const data = eventData<DeltaData>(envelope)
|
||||
ensureActivity(data.turn_id, lastDurable).thinking += data.delta
|
||||
break
|
||||
}
|
||||
case 'step_start': {
|
||||
const data = eventData<StepStartData>(envelope)
|
||||
ensureActivity(data.turn_id, lastDurable).steps += 1
|
||||
break
|
||||
}
|
||||
case 'tool_start': {
|
||||
const data = eventData<ToolStartData>(envelope)
|
||||
const activity = ensureActivity(data.turn_id, lastDurable)
|
||||
if (!activity.tools.some((tool) => tool.call_id === data.call_id)) {
|
||||
activity.tools.push({
|
||||
call_id: data.call_id,
|
||||
name: data.name,
|
||||
args: '',
|
||||
output: '',
|
||||
content: null,
|
||||
isError: null,
|
||||
code: null,
|
||||
done: false,
|
||||
})
|
||||
}
|
||||
break
|
||||
}
|
||||
case 'tool_args': {
|
||||
const data = eventData<ToolArgsData>(envelope)
|
||||
const activity = ensureActivity(data.turn_id, lastDurable)
|
||||
const tool = activity.tools.find((item) => item.call_id === data.call_id)
|
||||
if (tool) tool.args += data.delta
|
||||
break
|
||||
}
|
||||
case 'tool_output': {
|
||||
const data = eventData<ToolOutputData>(envelope)
|
||||
const activity = ensureActivity(data.turn_id, lastDurable)
|
||||
const tool = activity.tools.find((item) => item.call_id === data.call_id)
|
||||
if (tool) tool.output += data.chunk
|
||||
break
|
||||
}
|
||||
case 'tool_result': {
|
||||
const data = eventData<ToolResultData>(envelope)
|
||||
const activity = findActivity(data.turn_id)
|
||||
if (!activity) break
|
||||
let tool = activity.tools.find((item) => item.call_id === data.call_id)
|
||||
if (!tool) {
|
||||
tool = {
|
||||
call_id: data.call_id,
|
||||
name: '',
|
||||
args: '',
|
||||
output: '',
|
||||
content: null,
|
||||
isError: null,
|
||||
code: null,
|
||||
done: false,
|
||||
}
|
||||
activity.tools.push(tool)
|
||||
}
|
||||
if (data.name) tool.name = data.name
|
||||
if (data.args) tool.args = data.args
|
||||
tool.content = data.content
|
||||
tool.isError = data.is_error
|
||||
tool.code = data.code
|
||||
tool.done = true
|
||||
break
|
||||
}
|
||||
case 'usage': {
|
||||
const data = eventData<UsageEventData>(envelope)
|
||||
const activity = ensureActivity(data.turn_id, lastDurable)
|
||||
const usage = activity.usage ?? {
|
||||
input_tokens: 0,
|
||||
output_tokens: 0,
|
||||
cached_input_tokens: 0,
|
||||
cost_usd: null,
|
||||
}
|
||||
usage.input_tokens += data.input_tokens
|
||||
usage.output_tokens += data.output_tokens
|
||||
usage.cached_input_tokens += data.cached_input_tokens
|
||||
if (data.cost_usd !== null && data.cost_usd !== undefined) {
|
||||
usage.cost_usd = (usage.cost_usd ?? 0) + data.cost_usd
|
||||
}
|
||||
activity.usage = usage
|
||||
break
|
||||
}
|
||||
case 'turn_end': {
|
||||
const data = eventData<TurnEndData>(envelope)
|
||||
const activity = findActivity(data.turn_id)
|
||||
if (!activity) break
|
||||
activity.status = data.status
|
||||
activity.steps = data.steps
|
||||
activity.usage = data.usage
|
||||
if (data.status === 'error') activity.error = data.error ?? 'The turn failed.'
|
||||
break
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
function processChunk(chunk: string) {
|
||||
const dataLines = chunk
|
||||
.split('\n')
|
||||
.filter((line) => line.startsWith('data:'))
|
||||
.map((line) => line.slice(5).replace(/^ /, ''))
|
||||
if (dataLines.length === 0) return
|
||||
const raw = dataLines.join('\n')
|
||||
try {
|
||||
const envelope = JSON.parse(raw) as Envelope
|
||||
if (envelope.kind === 'lag') {
|
||||
handleLag()
|
||||
return
|
||||
}
|
||||
handleEnvelope(envelope)
|
||||
scheduleStick()
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
async function connectEvents() {
|
||||
if (disposed) return
|
||||
eventController?.abort()
|
||||
const generation = ++eventGeneration
|
||||
const controller = new AbortController()
|
||||
eventController = controller
|
||||
streamState.value = 'connecting'
|
||||
streamError.value = ''
|
||||
try {
|
||||
const response = await fetch(`/api/rooms/${encodeURIComponent(roomId.value)}/events?since=${lastDurable}`, {
|
||||
credentials: 'include',
|
||||
headers: { Accept: 'text/event-stream' },
|
||||
signal: controller.signal,
|
||||
})
|
||||
if (response.status === 401) {
|
||||
await navigateTo('/login')
|
||||
return
|
||||
}
|
||||
if (!response.ok || !response.body) {
|
||||
if (response.status === 403 || response.status === 404) {
|
||||
streamState.value = 'disconnected'
|
||||
streamError.value = 'Live updates are unavailable.'
|
||||
return
|
||||
}
|
||||
throw new Error('The live feed is unavailable.')
|
||||
}
|
||||
streamState.value = 'live'
|
||||
retryIndex = 0
|
||||
const reader = response.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let buffer = ''
|
||||
while (!disposed && generation === eventGeneration) {
|
||||
const { value, done } = await reader.read()
|
||||
if (done) break
|
||||
buffer += decoder.decode(value, { stream: true })
|
||||
let boundary = buffer.indexOf('\n\n')
|
||||
while (boundary !== -1) {
|
||||
const chunk = buffer.slice(0, boundary)
|
||||
buffer = buffer.slice(boundary + 2)
|
||||
processChunk(chunk)
|
||||
boundary = buffer.indexOf('\n\n')
|
||||
}
|
||||
}
|
||||
if (generation !== eventGeneration || disposed) return
|
||||
throw new Error('The live feed closed.')
|
||||
} catch {
|
||||
if (controller.signal.aborted || generation !== eventGeneration || disposed) return
|
||||
streamState.value = 'disconnected'
|
||||
scheduleReconnect()
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleReconnect() {
|
||||
if (disposed || reconnectTimer !== null) return
|
||||
const delay = BACKOFF[Math.min(retryIndex, BACKOFF.length - 1)] ?? 1000
|
||||
retryIndex += 1
|
||||
reconnectTimer = window.setTimeout(() => {
|
||||
reconnectTimer = null
|
||||
void connectEvents()
|
||||
}, delay)
|
||||
}
|
||||
|
||||
function handleLag() {
|
||||
eventController?.abort()
|
||||
streamState.value = 'disconnected'
|
||||
void refetchNewest()
|
||||
scheduleReconnect()
|
||||
}
|
||||
|
||||
async function refetchNewest() {
|
||||
try {
|
||||
const page = await api.get<MessagePage>(`/rooms/${roomId.value}/messages`, { limit: 60 })
|
||||
for (const message of page.messages) addMessage(message, true)
|
||||
} catch {
|
||||
// The next reconnect brings the durable backlog.
|
||||
}
|
||||
}
|
||||
|
||||
function connectPresence() {
|
||||
if (disposed) return
|
||||
const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
|
||||
const socket = new WebSocket(`${protocol}//${window.location.host}/api/rooms/${encodeURIComponent(roomId.value)}/presence`)
|
||||
presenceSocket = socket
|
||||
|
||||
socket.onopen = () => {
|
||||
presenceRetry = 0
|
||||
if (typingActive.value) sendPresenceState(true)
|
||||
}
|
||||
|
||||
socket.onmessage = (event) => {
|
||||
if (typeof event.data !== 'string') return
|
||||
try {
|
||||
const parsed = JSON.parse(event.data) as unknown
|
||||
if (!parsed || typeof parsed !== 'object') return
|
||||
if ((parsed as { type?: unknown }).type !== 'presence') return
|
||||
const list = (parsed as { peers?: unknown }).peers
|
||||
if (!Array.isArray(list)) return
|
||||
peers.value = list as PresencePeer[]
|
||||
onlineIds.value = peers.value.map((peer) => peer.member_id)
|
||||
} catch {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
socket.onclose = () => {
|
||||
if (presenceSocket !== socket || disposed) return
|
||||
presenceSocket = null
|
||||
if (presenceTimer !== null) return
|
||||
const delay = BACKOFF[Math.min(presenceRetry, BACKOFF.length - 1)] ?? 1000
|
||||
presenceRetry += 1
|
||||
presenceTimer = window.setTimeout(() => {
|
||||
presenceTimer = null
|
||||
connectPresence()
|
||||
}, delay)
|
||||
}
|
||||
|
||||
socket.onerror = () => {
|
||||
socket.close()
|
||||
}
|
||||
}
|
||||
|
||||
function sendPresenceState(typing: boolean) {
|
||||
if (!presenceSocket || presenceSocket.readyState !== WebSocket.OPEN) return
|
||||
presenceSocket.send(JSON.stringify({ state: { typing } }))
|
||||
}
|
||||
|
||||
function onTyping(active: boolean) {
|
||||
typingActive.value = active
|
||||
sendPresenceState(active)
|
||||
}
|
||||
|
||||
function colorFor(message: Message): string | null {
|
||||
if (!message.author_id) return null
|
||||
return memberById.value.get(message.author_id)?.color ?? null
|
||||
}
|
||||
|
||||
function isNearBottom(element: HTMLElement) {
|
||||
return element.scrollHeight - element.scrollTop - element.clientHeight < 80
|
||||
}
|
||||
|
||||
function scrollToBottom() {
|
||||
const element = chatScroll.value
|
||||
if (!element) return
|
||||
element.scrollTop = element.scrollHeight
|
||||
stick.value = true
|
||||
newMessages.value = 0
|
||||
}
|
||||
|
||||
function onScroll() {
|
||||
const element = chatScroll.value
|
||||
if (!element) return
|
||||
if (isNearBottom(element)) {
|
||||
stick.value = true
|
||||
newMessages.value = 0
|
||||
} else {
|
||||
stick.value = false
|
||||
}
|
||||
}
|
||||
|
||||
let stickScheduled = false
|
||||
|
||||
/// Keep the newest turn card or message in view while the log grows,
|
||||
/// unless the reader has scrolled away from the bottom.
|
||||
function scheduleStick() {
|
||||
if (!stick.value || stickScheduled) return
|
||||
stickScheduled = true
|
||||
void nextTick(() => {
|
||||
stickScheduled = false
|
||||
if (stick.value) scrollToBottom()
|
||||
})
|
||||
}
|
||||
|
||||
async function loadDetail() {
|
||||
detailLoading.value = true
|
||||
detailError.value = ''
|
||||
try {
|
||||
const response = await api.get<RoomDetailResponse>(`/rooms/${roomId.value}`)
|
||||
detail.value = response
|
||||
if (onlineIds.value.length === 0) {
|
||||
onlineIds.value = response.members.filter((member) => member.online).map((member) => member.id)
|
||||
}
|
||||
} catch (err) {
|
||||
detailError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
detailLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMessages() {
|
||||
messagesLoading.value = true
|
||||
messagesError.value = ''
|
||||
try {
|
||||
const page = await api.get<MessagePage>(`/rooms/${roomId.value}/messages`, { limit: 60 })
|
||||
for (const message of page.messages) addMessage(message, true)
|
||||
hasMore.value = page.has_more
|
||||
lastDurable = messages.value.reduce((max, message) => Math.max(max, message.seq), 0)
|
||||
} catch (err) {
|
||||
messagesError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
messagesLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function loadOlder() {
|
||||
if (loadingOlder.value || !hasMore.value || messages.value.length === 0) return
|
||||
const element = chatScroll.value
|
||||
const previousHeight = element?.scrollHeight ?? 0
|
||||
const previousTop = element?.scrollTop ?? 0
|
||||
loadingOlder.value = true
|
||||
suspendAutoScroll = true
|
||||
try {
|
||||
const oldest = messages.value[0]?.seq
|
||||
const page = await api.get<MessagePage>(`/rooms/${roomId.value}/messages`, {
|
||||
limit: 60,
|
||||
before: oldest,
|
||||
})
|
||||
for (const message of page.messages) addMessage(message, true)
|
||||
hasMore.value = page.has_more
|
||||
await nextTick()
|
||||
if (element) element.scrollTop = element.scrollHeight - previousHeight + previousTop
|
||||
} catch (err) {
|
||||
messagesError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
loadingOlder.value = false
|
||||
await nextTick()
|
||||
window.requestAnimationFrame(() => {
|
||||
suspendAutoScroll = false
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
async function onSent(message: Message) {
|
||||
addMessage(message, true)
|
||||
stick.value = true
|
||||
newMessages.value = 0
|
||||
await nextTick()
|
||||
scrollToBottom()
|
||||
}
|
||||
|
||||
async function onSettingsUpdated(room: Room) {
|
||||
if (detail.value) detail.value = { ...detail.value, room }
|
||||
await loadDetail()
|
||||
await rooms.refresh()
|
||||
}
|
||||
|
||||
async function onArchived() {
|
||||
await rooms.refresh()
|
||||
await navigateTo('/rooms', { replace: true })
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await loadDetail()
|
||||
await loadMessages()
|
||||
|
||||
if (!detailError.value) {
|
||||
await nextTick()
|
||||
scrollToBottom()
|
||||
window.requestAnimationFrame(() => {
|
||||
if (stick.value) scrollToBottom()
|
||||
})
|
||||
if (chatInner.value) {
|
||||
chatObserver = new ResizeObserver(() => {
|
||||
if (!stick.value || suspendAutoScroll) return
|
||||
const element = chatScroll.value
|
||||
if (element) element.scrollTop = element.scrollHeight
|
||||
})
|
||||
chatObserver.observe(chatInner.value)
|
||||
}
|
||||
void connectEvents()
|
||||
connectPresence()
|
||||
}
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
disposed = true
|
||||
eventGeneration += 1
|
||||
chatObserver?.disconnect()
|
||||
chatObserver = null
|
||||
eventController?.abort()
|
||||
eventController = null
|
||||
if (reconnectTimer !== null) window.clearTimeout(reconnectTimer)
|
||||
if (presenceTimer !== null) window.clearTimeout(presenceTimer)
|
||||
presenceSocket?.close()
|
||||
presenceSocket = null
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="detailLoading" class="page">
|
||||
<p class="meta">Opening the room.</p>
|
||||
</div>
|
||||
|
||||
<div v-else-if="detailError" class="page">
|
||||
<h1 class="page-title">Room</h1>
|
||||
<p class="form-error" role="alert">{{ detailError }}</p>
|
||||
<p class="mt-4"><NuxtLink to="/rooms">Back to rooms</NuxtLink></p>
|
||||
</div>
|
||||
|
||||
<div v-else-if="detail" class="room-shell">
|
||||
<RoomTopBar
|
||||
:room-name="detail.room.name"
|
||||
:members="detail.members"
|
||||
:online-ids="onlineIds"
|
||||
:is-owner="isOwner"
|
||||
:pane-open="paneOpen"
|
||||
@invite="inviteOpen = true"
|
||||
@settings="settingsOpen = true"
|
||||
@toggle-pane="paneOpen = !paneOpen"
|
||||
/>
|
||||
|
||||
<div class="room-body">
|
||||
<div class="chat-column">
|
||||
<div class="chat-area">
|
||||
<div ref="chatScroll" class="chat-scroll" @scroll="onScroll">
|
||||
<div ref="chatInner" class="chat-inner">
|
||||
<button
|
||||
v-if="hasMore"
|
||||
type="button"
|
||||
class="btn btn-sm btn-quiet chat-start"
|
||||
:disabled="loadingOlder"
|
||||
@click="loadOlder"
|
||||
>
|
||||
{{ loadingOlder ? 'Loading older messages' : 'Load older messages' }}
|
||||
</button>
|
||||
|
||||
<p v-if="messagesError" class="form-error" role="alert">{{ messagesError }}</p>
|
||||
<p v-if="messagesLoading && timeline.length === 0" class="meta">Loading the log.</p>
|
||||
|
||||
<p v-if="!messagesLoading && !messagesError && timeline.length === 0" class="empty">
|
||||
No messages yet. Ask @rhema to start.
|
||||
</p>
|
||||
|
||||
<template v-for="(entry, index) in timeline" :key="`${entry.kind}-${entry.seq}-${index}`">
|
||||
<ChatMessage
|
||||
v-if="entry.kind === 'message'"
|
||||
:message="entry.message"
|
||||
:color="colorFor(entry.message)"
|
||||
/>
|
||||
<p
|
||||
v-else-if="entry.kind === 'notice'"
|
||||
class="msg msg-system"
|
||||
:class="{ 'msg-system-danger': entry.level === 'error' }"
|
||||
>
|
||||
{{ entry.text }}
|
||||
</p>
|
||||
<TurnActivityView v-else :activity="entry.activity" />
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<button
|
||||
v-if="newMessages > 0"
|
||||
type="button"
|
||||
class="btn btn-sm new-messages"
|
||||
@click="scrollToBottom"
|
||||
>
|
||||
{{ newMessages }} new {{ newMessages === 1 ? 'message' : 'messages' }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p v-if="streamError" class="typing">{{ streamError }}</p>
|
||||
<p v-else-if="streamState === 'disconnected'" class="typing">Reconnecting to live updates.</p>
|
||||
<p v-if="typingText" class="typing">{{ typingText }}</p>
|
||||
|
||||
<ChatComposer :room-id="roomId" @sent="onSent" @typing="onTyping" />
|
||||
</div>
|
||||
|
||||
<RightPane
|
||||
v-if="paneOpen"
|
||||
:room-id="detail.room.id"
|
||||
:room-name="detail.room.name"
|
||||
@close="paneOpen = false"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<InviteDialog
|
||||
v-if="inviteOpen"
|
||||
:room-id="detail.room.id"
|
||||
:room-name="detail.room.name"
|
||||
@close="inviteOpen = false"
|
||||
/>
|
||||
|
||||
<RoomSettingsDialog
|
||||
v-if="settingsOpen && isOwner"
|
||||
:room="detail.room"
|
||||
@close="settingsOpen = false"
|
||||
@updated="onSettingsUpdated"
|
||||
@archived="onArchived"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,54 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted } from 'vue'
|
||||
import { Plus } from 'lucide-vue-next'
|
||||
import { fullTime, plural, relativeTime } from '~/utils/format'
|
||||
|
||||
useHead({ title: 'Rooms · rhema together' })
|
||||
|
||||
const {
|
||||
rooms,
|
||||
loading,
|
||||
error,
|
||||
openCreate,
|
||||
refresh,
|
||||
} = useRooms()
|
||||
|
||||
onMounted(() => {
|
||||
void refresh()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="page-head">
|
||||
<h1 class="page-title">Rooms</h1>
|
||||
<button type="button" class="btn btn-primary" @click="openCreate()">
|
||||
<Plus :size="16" aria-hidden="true" />
|
||||
New room
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
|
||||
|
||||
<div v-if="loading && rooms.length === 0" class="empty">Loading rooms.</div>
|
||||
|
||||
<div v-else-if="rooms.length === 0" class="empty">
|
||||
Create a room to start.
|
||||
</div>
|
||||
|
||||
<div v-else class="rooms-list">
|
||||
<NuxtLink v-for="room in rooms" :key="room.id" :to="`/room/${room.id}`" class="room-row">
|
||||
<div>
|
||||
<div class="room-row-name">{{ room.name }}</div>
|
||||
<div class="room-row-preview">
|
||||
{{ room.last_text || 'No messages yet.' }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="room-row-meta">
|
||||
<span>{{ room.member_count }} {{ plural(room.member_count, 'member', 'members') }}</span>
|
||||
<span v-if="room.last_at" :title="fullTime(room.last_at)">{{ relativeTime(room.last_at) }}</span>
|
||||
</div>
|
||||
</NuxtLink>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,424 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { Check, Copy, Plus, Trash2 } from 'lucide-vue-next'
|
||||
import type {
|
||||
CreateSandboxBody,
|
||||
CreateSandboxResponse,
|
||||
CreateProviderBody,
|
||||
IdResponse,
|
||||
ProviderConfig,
|
||||
ProviderListResponse,
|
||||
SandboxListResponse,
|
||||
SandboxTarget,
|
||||
TestSandboxResponse,
|
||||
} from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
|
||||
useHead({ title: 'Settings · rhema together' })
|
||||
|
||||
const api = useApi()
|
||||
|
||||
const providers = ref<ProviderConfig[]>([])
|
||||
const kinds = ref<string[]>(['anthropic', 'openai', 'openrouter', 'google', 'deepseek', 'zai', 'mistral', 'mistral-vibe', 'opencode', 'llama-cpp'])
|
||||
const targets = ref<SandboxTarget[]>([])
|
||||
const loading = ref(true)
|
||||
const loadError = ref('')
|
||||
|
||||
const providerName = ref('')
|
||||
const providerKind = ref('anthropic')
|
||||
const providerModel = ref('')
|
||||
const providerBaseUrl = ref('')
|
||||
const providerKey = ref('')
|
||||
const providerBusy = ref(false)
|
||||
const providerError = ref('')
|
||||
const llama = computed(() => providerKind.value === 'llama-cpp')
|
||||
|
||||
const sandboxName = ref('')
|
||||
const sandboxHost = ref('')
|
||||
const sandboxPort = ref<number | string>(22)
|
||||
const sandboxUser = ref('root')
|
||||
const sandboxRoot = ref('/root')
|
||||
const sandboxKey = ref('')
|
||||
const sandboxBusy = ref(false)
|
||||
const sandboxError = ref('')
|
||||
|
||||
const deletingProvider = ref<string | null>(null)
|
||||
const deletingTarget = ref<string | null>(null)
|
||||
const deleteBusy = ref(false)
|
||||
const rowError = ref('')
|
||||
|
||||
const testingTarget = ref<string | null>(null)
|
||||
const testResults = ref<Record<string, TestSandboxResponse>>({})
|
||||
const copiedKey = ref<string | null>(null)
|
||||
|
||||
async function loadLists() {
|
||||
loading.value = true
|
||||
loadError.value = ''
|
||||
try {
|
||||
const [providerList, targetList] = await Promise.all([
|
||||
api.get<ProviderListResponse>('/provider-configs'),
|
||||
api.get<SandboxListResponse>('/sandbox-targets'),
|
||||
])
|
||||
providers.value = providerList.providers
|
||||
if (providerList.kinds.length > 0) kinds.value = providerList.kinds
|
||||
targets.value = targetList.targets
|
||||
} catch (err) {
|
||||
loadError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(loadLists)
|
||||
|
||||
async function addProvider() {
|
||||
if (providerBusy.value) return
|
||||
providerBusy.value = true
|
||||
providerError.value = ''
|
||||
const body: CreateProviderBody = {
|
||||
name: providerName.value.trim(),
|
||||
kind: providerKind.value,
|
||||
model: providerModel.value.trim(),
|
||||
}
|
||||
if (providerBaseUrl.value.trim()) body.base_url = providerBaseUrl.value.trim()
|
||||
if (!llama.value) body.api_key = providerKey.value
|
||||
try {
|
||||
await api.post<IdResponse>('/provider-configs', body)
|
||||
providerName.value = ''
|
||||
providerModel.value = ''
|
||||
providerBaseUrl.value = ''
|
||||
providerKey.value = ''
|
||||
await loadLists()
|
||||
} catch (err) {
|
||||
providerError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
providerBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function addSandbox() {
|
||||
if (sandboxBusy.value) return
|
||||
sandboxBusy.value = true
|
||||
sandboxError.value = ''
|
||||
const body: CreateSandboxBody = {
|
||||
name: sandboxName.value.trim(),
|
||||
host: sandboxHost.value.trim(),
|
||||
port: Number(sandboxPort.value) || 22,
|
||||
user_name: sandboxUser.value.trim() || 'root',
|
||||
workspace_root: sandboxRoot.value.trim() || '/root',
|
||||
}
|
||||
if (sandboxKey.value.trim()) body.private_key = sandboxKey.value.trim()
|
||||
try {
|
||||
await api.post<CreateSandboxResponse>('/sandbox-targets', body)
|
||||
sandboxName.value = ''
|
||||
sandboxHost.value = ''
|
||||
sandboxPort.value = 22
|
||||
sandboxUser.value = 'root'
|
||||
sandboxRoot.value = '/root'
|
||||
sandboxKey.value = ''
|
||||
await loadLists()
|
||||
} catch (err) {
|
||||
sandboxError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
sandboxBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function removeProvider(provider: ProviderConfig) {
|
||||
if (deleteBusy.value) return
|
||||
deleteBusy.value = true
|
||||
rowError.value = ''
|
||||
try {
|
||||
await api.del(`/provider-configs/${provider.id}`)
|
||||
deletingProvider.value = null
|
||||
await loadLists()
|
||||
} catch (err) {
|
||||
rowError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
deleteBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function removeTarget(target: SandboxTarget) {
|
||||
if (deleteBusy.value) return
|
||||
deleteBusy.value = true
|
||||
rowError.value = ''
|
||||
try {
|
||||
await api.del(`/sandbox-targets/${target.id}`)
|
||||
deletingTarget.value = null
|
||||
await loadLists()
|
||||
} catch (err) {
|
||||
rowError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
deleteBusy.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function testTarget(target: SandboxTarget) {
|
||||
if (testingTarget.value) return
|
||||
testingTarget.value = target.id
|
||||
rowError.value = ''
|
||||
try {
|
||||
testResults.value[target.id] = await api.post<TestSandboxResponse>(`/sandbox-targets/${target.id}/test`)
|
||||
} catch (err) {
|
||||
rowError.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
testingTarget.value = null
|
||||
}
|
||||
}
|
||||
|
||||
async function copyKey(target: SandboxTarget) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(target.public_key)
|
||||
copiedKey.value = target.id
|
||||
window.setTimeout(() => {
|
||||
if (copiedKey.value === target.id) copiedKey.value = null
|
||||
}, 1800)
|
||||
} catch {
|
||||
rowError.value = 'The clipboard is not available. Select the key and copy it by hand.'
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page">
|
||||
<div class="page-head">
|
||||
<h1 class="page-title">Settings</h1>
|
||||
</div>
|
||||
|
||||
<p v-if="loadError" class="form-error" role="alert">{{ loadError }}</p>
|
||||
<p v-if="rowError" class="form-error" role="alert">{{ rowError }}</p>
|
||||
<p v-if="loading" class="meta">Loading settings.</p>
|
||||
|
||||
<section class="section">
|
||||
<div class="section-head">
|
||||
<h2 class="section-title">Providers</h2>
|
||||
</div>
|
||||
<p class="hint">A provider holds the model backend and key. Rooms spend from the provider their owner picks.</p>
|
||||
|
||||
<div v-if="!loading && providers.length === 0" class="empty">No providers yet. Add one below.</div>
|
||||
|
||||
<div v-else class="list">
|
||||
<div v-for="provider in providers" :key="provider.id" class="settings-row">
|
||||
<div class="settings-row-main">
|
||||
<div class="settings-row-title">{{ provider.name }}</div>
|
||||
<div class="settings-row-detail">
|
||||
{{ provider.kind }}, {{ provider.model }}
|
||||
<template v-if="provider.base_url">, {{ provider.base_url }}</template>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-row-actions">
|
||||
<template v-if="deletingProvider === provider.id">
|
||||
<div class="confirm-line">
|
||||
<span>Delete {{ provider.name }}?</span>
|
||||
<button type="button" class="btn btn-sm btn-quiet" :disabled="deleteBusy" @click="deletingProvider = null">
|
||||
Cancel
|
||||
</button>
|
||||
<button type="button" class="btn btn-sm btn-danger" :disabled="deleteBusy" @click="removeProvider(provider)">
|
||||
{{ deleteBusy ? 'Deleting' : 'Delete' }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Delete provider"
|
||||
title="Delete provider"
|
||||
@click="deletingProvider = provider.id"
|
||||
>
|
||||
<Trash2 :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-panel">
|
||||
<h3 class="panel-title">Add provider</h3>
|
||||
<form class="form" @submit.prevent="addProvider">
|
||||
<div class="form-grid">
|
||||
<div class="field">
|
||||
<label class="field-label" for="provider-name">Name</label>
|
||||
<input id="provider-name" v-model="providerName" class="input" type="text" maxlength="60" required>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="field-label" for="provider-kind">Kind</label>
|
||||
<select id="provider-kind" v-model="providerKind" class="select">
|
||||
<option v-for="kind in kinds" :key="kind" :value="kind">{{ kind }}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="provider-model">Model</label>
|
||||
<input id="provider-model" v-model="providerModel" class="input" type="text" spellcheck="false" required>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="provider-base">
|
||||
{{ llama ? 'Server URL' : 'Base URL' }}
|
||||
<span v-if="!llama" class="field-optional">optional</span>
|
||||
</label>
|
||||
<input
|
||||
id="provider-base"
|
||||
v-model="providerBaseUrl"
|
||||
class="input"
|
||||
type="text"
|
||||
spellcheck="false"
|
||||
:placeholder="llama ? 'http://127.0.0.1:8080' : 'https://api.example.com/v1'"
|
||||
:required="llama"
|
||||
>
|
||||
<span v-if="llama" class="hint">The address of the llama.cpp server.</span>
|
||||
</div>
|
||||
|
||||
<div v-if="!llama" class="field">
|
||||
<label class="field-label" for="provider-key">API key</label>
|
||||
<input
|
||||
id="provider-key"
|
||||
v-model="providerKey"
|
||||
class="input"
|
||||
type="password"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
required
|
||||
>
|
||||
<span class="hint">The key is sealed on the server and never shown again.</span>
|
||||
</div>
|
||||
|
||||
<p v-if="providerError" class="form-error" role="alert">{{ providerError }}</p>
|
||||
|
||||
<div>
|
||||
<button type="submit" class="btn btn-primary" :disabled="providerBusy">
|
||||
<Plus :size="16" aria-hidden="true" />
|
||||
{{ providerBusy ? 'Adding' : 'Add provider' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="section">
|
||||
<div class="section-head">
|
||||
<h2 class="section-title">Sandboxes</h2>
|
||||
</div>
|
||||
<p class="hint">A sandbox is an ssh machine the room works on. The public key belongs in its authorized_keys file.</p>
|
||||
|
||||
<div v-if="!loading && targets.length === 0" class="empty">No sandboxes yet. Add one below.</div>
|
||||
|
||||
<div v-else class="list">
|
||||
<div v-for="target in targets" :key="target.id" class="settings-row">
|
||||
<div class="settings-row-main">
|
||||
<div class="settings-row-title">{{ target.name }}</div>
|
||||
<div class="settings-row-detail">{{ target.user_name }}@{{ target.host }}:{{ target.port }}</div>
|
||||
<div class="settings-row-detail">Workspace root: {{ target.workspace_root }}</div>
|
||||
<div class="key-line">
|
||||
<span class="key-text">{{ target.public_key }}</span>
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm btn-quiet"
|
||||
:aria-label="`Copy public key for ${target.name}`"
|
||||
title="Copy public key"
|
||||
@click="copyKey(target)"
|
||||
>
|
||||
<component :is="copiedKey === target.id ? Check : Copy" :size="14" aria-hidden="true" />
|
||||
{{ copiedKey === target.id ? 'Copied' : 'Copy' }}
|
||||
</button>
|
||||
</div>
|
||||
<div v-if="target.host_fingerprint" class="settings-row-detail">
|
||||
Host fingerprint: {{ target.host_fingerprint }}
|
||||
</div>
|
||||
|
||||
<div v-if="testResults[target.id]" class="small" :class="testResults[target.id]?.ok ? 'muted' : 'form-error'">
|
||||
{{ testResults[target.id]?.detail }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-row-actions">
|
||||
<button
|
||||
type="button"
|
||||
class="btn btn-sm"
|
||||
:disabled="testingTarget !== null"
|
||||
@click="testTarget(target)"
|
||||
>
|
||||
{{ testingTarget === target.id ? 'Testing' : 'Test' }}
|
||||
</button>
|
||||
<template v-if="deletingTarget === target.id">
|
||||
<div class="confirm-line">
|
||||
<span>Delete {{ target.name }}?</span>
|
||||
<button type="button" class="btn btn-sm btn-quiet" :disabled="deleteBusy" @click="deletingTarget = null">
|
||||
Cancel
|
||||
</button>
|
||||
<button type="button" class="btn btn-sm btn-danger" :disabled="deleteBusy" @click="removeTarget(target)">
|
||||
{{ deleteBusy ? 'Deleting' : 'Delete' }}
|
||||
</button>
|
||||
</div>
|
||||
</template>
|
||||
<button
|
||||
v-else
|
||||
type="button"
|
||||
class="icon-btn"
|
||||
aria-label="Delete sandbox"
|
||||
title="Delete sandbox"
|
||||
@click="deletingTarget = target.id"
|
||||
>
|
||||
<Trash2 :size="16" aria-hidden="true" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-panel">
|
||||
<h3 class="panel-title">Add sandbox</h3>
|
||||
<form class="form" @submit.prevent="addSandbox">
|
||||
<div class="form-grid">
|
||||
<div class="field">
|
||||
<label class="field-label" for="sandbox-name">Name</label>
|
||||
<input id="sandbox-name" v-model="sandboxName" class="input" type="text" maxlength="60" required>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="field-label" for="sandbox-host">Host</label>
|
||||
<input id="sandbox-host" v-model="sandboxHost" class="input" type="text" spellcheck="false" required>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="form-grid">
|
||||
<div class="field">
|
||||
<label class="field-label" for="sandbox-port">Port</label>
|
||||
<input id="sandbox-port" v-model.number="sandboxPort" class="input" type="number" min="1" max="65535" required>
|
||||
</div>
|
||||
<div class="field">
|
||||
<label class="field-label" for="sandbox-user">SSH user</label>
|
||||
<input id="sandbox-user" v-model="sandboxUser" class="input" type="text" spellcheck="false">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="sandbox-root">Workspace root</label>
|
||||
<input id="sandbox-root" v-model="sandboxRoot" class="input" type="text" spellcheck="false">
|
||||
<span class="hint">An absolute path. Rooms create their workspace below it unless the owner sets one.</span>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="sandbox-key">Private key <span class="field-optional">optional</span></label>
|
||||
<textarea
|
||||
id="sandbox-key"
|
||||
v-model="sandboxKey"
|
||||
class="textarea"
|
||||
rows="4"
|
||||
spellcheck="false"
|
||||
placeholder="Leave empty to generate an ed25519 key."
|
||||
></textarea>
|
||||
</div>
|
||||
|
||||
<p v-if="sandboxError" class="form-error" role="alert">{{ sandboxError }}</p>
|
||||
|
||||
<div>
|
||||
<button type="submit" class="btn btn-primary" :disabled="sandboxBusy">
|
||||
<Plus :size="16" aria-hidden="true" />
|
||||
{{ sandboxBusy ? 'Adding' : 'Add sandbox' }}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,126 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue'
|
||||
import type { User } from '~/types'
|
||||
import { apiErrorMessage } from '~/utils/errors'
|
||||
|
||||
definePageMeta({ layout: 'auth' })
|
||||
useHead({ title: 'Set up the server · rhema together' })
|
||||
|
||||
const api = useApi()
|
||||
const { load } = useSession()
|
||||
|
||||
const token = ref('')
|
||||
const displayName = ref('')
|
||||
const handle = ref('')
|
||||
const email = ref('')
|
||||
const password = ref('')
|
||||
const checking = ref(true)
|
||||
const submitting = ref(false)
|
||||
const error = ref('')
|
||||
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const state = await load(true)
|
||||
if (!state.needsSetup) {
|
||||
await navigateTo('/login', { replace: true })
|
||||
}
|
||||
} catch (err) {
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
checking.value = false
|
||||
}
|
||||
})
|
||||
|
||||
async function submit() {
|
||||
if (submitting.value) return
|
||||
submitting.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
await api.post<User>('/setup', {
|
||||
token: token.value.trim(),
|
||||
display_name: displayName.value.trim(),
|
||||
handle: handle.value.trim().toLowerCase(),
|
||||
email: email.value.trim() || null,
|
||||
password: password.value,
|
||||
})
|
||||
await load(true)
|
||||
await navigateTo('/rooms', { replace: true })
|
||||
} catch (err) {
|
||||
error.value = apiErrorMessage(err)
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div>
|
||||
<h1 class="auth-title">Set up the server</h1>
|
||||
<p class="auth-note">Create the owner account. The token is printed in the server log at startup.</p>
|
||||
|
||||
<p v-if="checking" class="meta">Checking the server.</p>
|
||||
|
||||
<form v-else class="form" @submit.prevent="submit">
|
||||
<div class="field">
|
||||
<label class="field-label" for="setup-token">Setup token</label>
|
||||
<input
|
||||
id="setup-token"
|
||||
v-model="token"
|
||||
class="input"
|
||||
type="text"
|
||||
autocomplete="off"
|
||||
spellcheck="false"
|
||||
autofocus
|
||||
required
|
||||
>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="setup-name">Display name</label>
|
||||
<input id="setup-name" v-model="displayName" class="input" type="text" autocomplete="name" required>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="setup-handle">Handle</label>
|
||||
<input
|
||||
id="setup-handle"
|
||||
v-model="handle"
|
||||
class="input"
|
||||
type="text"
|
||||
autocomplete="username"
|
||||
spellcheck="false"
|
||||
pattern="[A-Za-z0-9_-]{3,32}"
|
||||
minlength="3"
|
||||
maxlength="32"
|
||||
required
|
||||
>
|
||||
<span class="hint">3 to 32 lowercase letters, digits, _ or -.</span>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="setup-email">Email <span class="field-optional">optional</span></label>
|
||||
<input id="setup-email" v-model="email" class="input" type="email" autocomplete="email">
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label class="field-label" for="setup-password">Password</label>
|
||||
<input
|
||||
id="setup-password"
|
||||
v-model="password"
|
||||
class="input"
|
||||
type="password"
|
||||
autocomplete="new-password"
|
||||
minlength="8"
|
||||
required
|
||||
>
|
||||
<span class="hint">At least 8 characters.</span>
|
||||
</div>
|
||||
|
||||
<p v-if="error" class="form-error" role="alert">{{ error }}</p>
|
||||
|
||||
<button type="submit" class="btn btn-primary" :disabled="submitting">
|
||||
{{ submitting ? 'Creating the account' : 'Create the account' }}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,341 @@
|
||||
export interface User {
|
||||
id: string
|
||||
handle: string
|
||||
display_name: string
|
||||
kind: string
|
||||
}
|
||||
|
||||
export interface BootstrapResponse {
|
||||
needs_setup: boolean
|
||||
user: User | null
|
||||
allow_registration: boolean
|
||||
public_url: string
|
||||
preview_origin: string
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
seq: number
|
||||
id: string
|
||||
author_id: string | null
|
||||
author_name: string
|
||||
author_kind: 'human' | 'agent' | 'system'
|
||||
text: string
|
||||
mentions: boolean
|
||||
created_at: number
|
||||
}
|
||||
|
||||
export interface MessagePage {
|
||||
messages: Message[]
|
||||
has_more: boolean
|
||||
}
|
||||
|
||||
export interface SendMessageResponse {
|
||||
message: Message
|
||||
}
|
||||
|
||||
export interface RoomSummary {
|
||||
id: string
|
||||
name: string
|
||||
role: string
|
||||
member_count: number
|
||||
last_at: number | null
|
||||
last_text: string | null
|
||||
}
|
||||
|
||||
export interface RoomListResponse {
|
||||
rooms: RoomSummary[]
|
||||
}
|
||||
|
||||
export interface Room {
|
||||
id: string
|
||||
name: string
|
||||
owner_id: string
|
||||
provider_config_id: string | null
|
||||
sandbox_target_id: string | null
|
||||
workspace: string
|
||||
repo_url: string | null
|
||||
model: string | null
|
||||
max_turn_steps: number
|
||||
created_at: number
|
||||
archived_at: number | null
|
||||
}
|
||||
|
||||
export interface Member {
|
||||
id: string
|
||||
account_id: string
|
||||
display_name: string
|
||||
role: string
|
||||
color: string
|
||||
online: boolean
|
||||
}
|
||||
|
||||
export interface Me {
|
||||
id: string
|
||||
display_name: string
|
||||
role: string
|
||||
color: string
|
||||
}
|
||||
|
||||
export interface RoomDetailResponse {
|
||||
room: Room
|
||||
members: Member[]
|
||||
me: Me
|
||||
}
|
||||
|
||||
export interface CreateRoomBody {
|
||||
name: string
|
||||
provider_config_id: string
|
||||
sandbox_target_id: string
|
||||
workspace?: string
|
||||
repo_url?: string
|
||||
model?: string
|
||||
}
|
||||
|
||||
export interface CreateRoomResponse {
|
||||
room: Room
|
||||
}
|
||||
|
||||
export interface UpdateRoomBody {
|
||||
name?: string
|
||||
provider_config_id?: string
|
||||
model?: string
|
||||
max_turn_steps?: number
|
||||
}
|
||||
|
||||
export interface UpdateRoomResponse {
|
||||
room: Room
|
||||
}
|
||||
|
||||
export interface Invite {
|
||||
token: string
|
||||
url: string
|
||||
expires_at: number
|
||||
}
|
||||
|
||||
export interface InvitePreview {
|
||||
room_id: string
|
||||
room_name: string
|
||||
owner: string
|
||||
role: string
|
||||
expires_at: number
|
||||
}
|
||||
|
||||
export interface JoinResponse {
|
||||
user: User
|
||||
room_id: string
|
||||
member: { id: string; role: string }
|
||||
}
|
||||
|
||||
export interface ProviderConfig {
|
||||
id: string
|
||||
name: string
|
||||
kind: string
|
||||
model: string
|
||||
base_url: string | null
|
||||
}
|
||||
|
||||
export interface ProviderListResponse {
|
||||
providers: ProviderConfig[]
|
||||
kinds: string[]
|
||||
}
|
||||
|
||||
export interface CreateProviderBody {
|
||||
name: string
|
||||
kind: string
|
||||
model: string
|
||||
base_url?: string | null
|
||||
api_key?: string
|
||||
}
|
||||
|
||||
export interface IdResponse {
|
||||
id: string
|
||||
}
|
||||
|
||||
export interface SandboxTarget {
|
||||
id: string
|
||||
name: string
|
||||
host: string
|
||||
port: number
|
||||
user_name: string
|
||||
workspace_root: string
|
||||
public_key: string
|
||||
host_fingerprint: string | null
|
||||
}
|
||||
|
||||
export interface SandboxListResponse {
|
||||
targets: SandboxTarget[]
|
||||
}
|
||||
|
||||
export interface CreateSandboxBody {
|
||||
name: string
|
||||
host: string
|
||||
port?: number
|
||||
user_name?: string
|
||||
workspace_root?: string
|
||||
private_key?: string
|
||||
}
|
||||
|
||||
export interface CreateSandboxResponse {
|
||||
id: string
|
||||
public_key: string
|
||||
}
|
||||
|
||||
export interface TestSandboxResponse {
|
||||
ok: boolean
|
||||
detail: string
|
||||
}
|
||||
|
||||
export interface FileEntry {
|
||||
name: string
|
||||
path: string
|
||||
kind: 'dir' | 'file' | 'link'
|
||||
size: number
|
||||
}
|
||||
|
||||
export interface FileListResponse {
|
||||
path: string
|
||||
entries: FileEntry[]
|
||||
}
|
||||
|
||||
export interface FileContentResponse {
|
||||
path: string
|
||||
content: string
|
||||
binary: boolean
|
||||
size: number
|
||||
truncated: boolean
|
||||
}
|
||||
|
||||
export interface GitSummaryResponse {
|
||||
text: string
|
||||
code: number | null
|
||||
}
|
||||
|
||||
export interface PreviewResponse {
|
||||
url: string
|
||||
}
|
||||
|
||||
export interface PresencePeer {
|
||||
member_id: string
|
||||
display_name: string
|
||||
color: string
|
||||
state: PresenceState | null
|
||||
}
|
||||
|
||||
export interface PresenceState {
|
||||
typing?: boolean
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
export interface PresenceEvent {
|
||||
type: 'presence'
|
||||
peers: PresencePeer[]
|
||||
}
|
||||
|
||||
export type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }
|
||||
|
||||
export interface Envelope {
|
||||
seq: number
|
||||
kind: string
|
||||
data: JsonValue
|
||||
}
|
||||
|
||||
export interface Usage {
|
||||
input_tokens: number
|
||||
output_tokens: number
|
||||
cached_input_tokens: number
|
||||
cost_usd: number | null
|
||||
}
|
||||
|
||||
export interface NoticeData {
|
||||
level: string
|
||||
text: string
|
||||
at: number
|
||||
}
|
||||
|
||||
export interface TurnStartData {
|
||||
turn_id: string
|
||||
by: string
|
||||
model: string
|
||||
at: number
|
||||
}
|
||||
|
||||
export interface TurnEndData {
|
||||
turn_id: string
|
||||
status: 'done' | 'error' | 'interrupted' | 'step_limit' | 'max_tokens'
|
||||
error?: string
|
||||
usage: Usage
|
||||
steps: number
|
||||
}
|
||||
|
||||
export interface DeltaData {
|
||||
turn_id: string
|
||||
delta: string
|
||||
}
|
||||
|
||||
export interface StepStartData {
|
||||
turn_id: string
|
||||
iteration: number
|
||||
}
|
||||
|
||||
export interface ToolStartData {
|
||||
turn_id: string
|
||||
call_id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export interface ToolArgsData {
|
||||
turn_id: string
|
||||
call_id: string
|
||||
delta: string
|
||||
}
|
||||
|
||||
export interface ToolOutputData {
|
||||
turn_id: string
|
||||
call_id: string
|
||||
chunk: string
|
||||
}
|
||||
|
||||
export interface ToolResultData {
|
||||
turn_id: string
|
||||
call_id: string
|
||||
name: string
|
||||
args: string
|
||||
content: string
|
||||
is_error: boolean
|
||||
code: number | null
|
||||
}
|
||||
|
||||
export interface UsageEventData extends Usage {
|
||||
turn_id: string
|
||||
}
|
||||
|
||||
export interface ToolActivity {
|
||||
call_id: string
|
||||
name: string
|
||||
args: string
|
||||
output: string
|
||||
content: string | null
|
||||
isError: boolean | null
|
||||
code: number | null
|
||||
done: boolean
|
||||
}
|
||||
|
||||
export type TurnStatus = 'running' | 'done' | 'error' | 'interrupted' | 'step_limit' | 'max_tokens'
|
||||
|
||||
export interface TurnActivity {
|
||||
turnId: string
|
||||
seq: number
|
||||
startedAt: number
|
||||
text: string
|
||||
thinking: string
|
||||
steps: number
|
||||
tools: ToolActivity[]
|
||||
usage: Usage | null
|
||||
status: TurnStatus
|
||||
error: string
|
||||
}
|
||||
|
||||
export type TimelineEntry =
|
||||
| { kind: 'message'; seq: number; message: Message }
|
||||
| { kind: 'notice'; seq: number; level: string; text: string }
|
||||
| { kind: 'turn'; seq: number; activity: TurnActivity }
|
||||
@@ -0,0 +1,51 @@
|
||||
export class ApiRequestError extends Error {
|
||||
status: number
|
||||
|
||||
constructor(message: string, status = 0) {
|
||||
super(message)
|
||||
this.name = 'ApiRequestError'
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
export function apiErrorMessage(error: unknown): string {
|
||||
if (error instanceof ApiRequestError) return error.message
|
||||
if (error instanceof Error && error.message) return error.message
|
||||
return 'The request failed. Try again.'
|
||||
}
|
||||
|
||||
function serverMessage(data: unknown): string | null {
|
||||
if (!data || typeof data !== 'object') return null
|
||||
if ('error' in data) {
|
||||
const value = (data as { error: unknown }).error
|
||||
if (typeof value === 'string' && value.trim()) return value
|
||||
if (value && typeof value === 'object' && 'message' in value) {
|
||||
const message = (value as { message: unknown }).message
|
||||
if (typeof message === 'string' && message.trim()) return message
|
||||
}
|
||||
}
|
||||
if ('message' in data) {
|
||||
const value = (data as { message: unknown }).message
|
||||
if (typeof value === 'string' && value.trim()) return value
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function normalizeApiError(error: unknown): ApiRequestError {
|
||||
if (error instanceof ApiRequestError) return error
|
||||
if (error && typeof error === 'object') {
|
||||
const status = 'status' in error && typeof (error as { status: unknown }).status === 'number'
|
||||
? (error as { status: number }).status
|
||||
: 0
|
||||
const data = 'data' in error ? (error as { data: unknown }).data : null
|
||||
const message = serverMessage(data)
|
||||
if (message) return new ApiRequestError(message, status)
|
||||
if (status === 0 && error instanceof Error && error.message) {
|
||||
return new ApiRequestError(error.message, status)
|
||||
}
|
||||
if (status === 401) return new ApiRequestError('Your session has expired. Sign in again.', 401)
|
||||
if (status === 403) return new ApiRequestError('You do not have access to that.', 403)
|
||||
if (status === 404) return new ApiRequestError('That was not found.', 404)
|
||||
}
|
||||
return new ApiRequestError('The request failed. Try again.')
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
const MINUTE = 60_000
|
||||
const HOUR = 3_600_000
|
||||
const DAY = 86_400_000
|
||||
|
||||
export function relativeTime(at: number | null | undefined): string {
|
||||
if (!at) return ''
|
||||
const diff = Date.now() - at
|
||||
if (diff < 45_000) return 'just now'
|
||||
if (diff < HOUR) return `${Math.max(1, Math.round(diff / MINUTE))}m ago`
|
||||
if (diff < DAY) return `${Math.round(diff / HOUR)}h ago`
|
||||
if (diff < 7 * DAY) return `${Math.round(diff / DAY)}d ago`
|
||||
return new Date(at).toLocaleDateString('en', { month: 'short', day: 'numeric' })
|
||||
}
|
||||
|
||||
export function fullTime(at: number | null | undefined): string {
|
||||
if (!at) return ''
|
||||
return new Date(at).toLocaleString('en', {
|
||||
year: 'numeric',
|
||||
month: 'short',
|
||||
day: 'numeric',
|
||||
hour: 'numeric',
|
||||
minute: '2-digit',
|
||||
})
|
||||
}
|
||||
|
||||
export function formatDate(at: number | null | undefined): string {
|
||||
if (!at) return ''
|
||||
return new Date(at).toLocaleDateString('en', { year: 'numeric', month: 'short', day: 'numeric' })
|
||||
}
|
||||
|
||||
export function formatSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`
|
||||
if (bytes < 1024 * 1024) return `${Math.round((bytes / 1024) * 10) / 10} KB`
|
||||
return `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MB`
|
||||
}
|
||||
|
||||
export function initials(name: string): string {
|
||||
const parts = name.trim().split(/\s+/).filter(Boolean)
|
||||
if (parts.length === 0) return '?'
|
||||
const first = parts[0]?.[0] ?? ''
|
||||
const second = parts.length > 1 ? (parts[parts.length - 1]?.[0] ?? '') : ''
|
||||
return (first + second).toUpperCase()
|
||||
}
|
||||
|
||||
export function formatCost(cost: number | null | undefined): string {
|
||||
if (cost === null || cost === undefined) return ''
|
||||
if (cost === 0) return '$0.00'
|
||||
if (cost < 0.01) return `$${cost.toFixed(4)}`
|
||||
return `$${cost.toFixed(2)}`
|
||||
}
|
||||
|
||||
export function plural(count: number, one: string, many: string): string {
|
||||
return count === 1 ? one : many
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
const MEMBER_COLORS = [
|
||||
'#3f6f5a',
|
||||
'#8a5a2b',
|
||||
'#4f5f8f',
|
||||
'#8f4f5a',
|
||||
'#6a5a8f',
|
||||
'#2f6f6f',
|
||||
'#7a6a2f',
|
||||
'#5a6a3f',
|
||||
]
|
||||
|
||||
/** Maps a server-provided identity color to its design token. */
|
||||
export function memberColorVar(color: string | null | undefined): string {
|
||||
if (color?.startsWith('var(')) return color
|
||||
const index = color ? MEMBER_COLORS.indexOf(color.toLowerCase()) : -1
|
||||
return index >= 0 ? `var(--member-${index + 1})` : 'var(--muted)'
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
export default defineNuxtConfig({
|
||||
compatibilityDate: '2025-07-15',
|
||||
ssr: false,
|
||||
devtools: { enabled: false },
|
||||
css: ['~/assets/css/main.css'],
|
||||
app: {
|
||||
head: {
|
||||
htmlAttrs: { lang: 'en' },
|
||||
title: 'rhema together',
|
||||
meta: [
|
||||
{ name: 'viewport', content: 'width=device-width, initial-scale=1' },
|
||||
{ name: 'color-scheme', content: 'light dark' },
|
||||
],
|
||||
link: [{ rel: 'icon', href: '/mark.svg', type: 'image/svg+xml' }],
|
||||
},
|
||||
},
|
||||
nitro: {
|
||||
preset: 'static',
|
||||
prerender: { crawlLinks: false },
|
||||
devProxy: {
|
||||
'/api': {
|
||||
target: 'http://127.0.0.1:7800',
|
||||
changeOrigin: false,
|
||||
ws: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
vite: {
|
||||
server: {
|
||||
proxy: {
|
||||
'/api': {
|
||||
target: 'http://127.0.0.1:7800',
|
||||
changeOrigin: false,
|
||||
ws: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"name": "rhema-together-web",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "nuxt dev",
|
||||
"build": "nuxt generate",
|
||||
"generate": "nuxt generate",
|
||||
"preview": "nuxt preview",
|
||||
"typecheck": "nuxt typecheck"
|
||||
},
|
||||
"dependencies": {
|
||||
"@xterm/addon-fit": "^0.11.0",
|
||||
"@xterm/xterm": "^6.0.0",
|
||||
"lucide-vue-next": "^1.0.0",
|
||||
"nuxt": "^4.7.0",
|
||||
"vue": "^3.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"typescript": "^5.9.0",
|
||||
"vue-tsc": "^2.2.0"
|
||||
}
|
||||
}
|
||||
Generated
+5949
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,4 @@
|
||||
allowBuilds:
|
||||
esbuild: true
|
||||
onlyBuiltDependencies:
|
||||
- esbuild
|
||||
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="8" fill="#2f6f5e"/><path d="M10 24V8h7.2c3 0 5 1.8 5 4.7 0 2.1-1.2 3.7-3.2 4.3L23 24h-3.8l-3.4-6.3H13.3V24H10Zm3.3-8.9h3.4c1.5 0 2.4-.8 2.4-2.2 0-1.4-.9-2.2-2.4-2.2h-3.4v4.4Z" fill="#f7f6f3"/></svg>
|
||||
|
After Width: | Height: | Size: 292 B |
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"extends": "./.nuxt/tsconfig.json"
|
||||
}
|
||||
Reference in new issue
Block a user